Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

fix(khaos): reset was indistinguishable from eof, Ctrl-D refused in silence

CarterPerez-dev58e73873416d
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index f6ea04a8..41e50c59 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -141,6 +141,9 @@ jobs:
- name: monitor-the-situation-dashboard-backend
type: go
path: PROJECTS/advanced/monitor-the-situation-dashboard/backend
+ - name: chaos-engineering-tool
+ type: go
+ path: PROJECTS/intermediate/chaos-engineering-tool
# Nim
- name: credential-enumeration
type: nim
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 23f2181f..84e3ebe8 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -194,6 +194,14 @@ repos:
types: [go]
pass_filenames: false
+ - id: golangci-lint-chaos-engineering-tool
+ name: golangci-lint (chaos-engineering-tool)
+ entry: bash -c 'cd PROJECTS/intermediate/chaos-engineering-tool && golangci-lint run --fix'
+ language: system
+ files: ^PROJECTS/intermediate/chaos-engineering-tool/
+ types: [go]
+ pass_filenames: false
+
# Biome Frontend Checks
- repo: local
hooks:
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/.golangci.yml b/PROJECTS/intermediate/chaos-engineering-tool/.golangci.yml
index 3514d8fb..fe39eaed 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/.golangci.yml
+++ b/PROJECTS/intermediate/chaos-engineering-tool/.golangci.yml
@@ -27,21 +27,86 @@ linters:
exclusions:
rules:
+ # errcheck is excluded in tests, and only in tests, because a test's
+ # error-handling policy IS its assertion: a discarded return that mattered
+ # shows up as a failing test, not as a silent wrong answer in the field.
+ # Every one of the 13 test sites that discards a meaningful return was read
+ # by hand first; each asserts on the value it keeps, and several discard an
+ # error the measurement requires (a complete answer through the fault proxy
+ # always ends in one). The exclusion is not standing permission to stop
+ # reading them.
+ #
+ # gocognit joins funlen and dupl for the same reason those two are already
+ # here. Cognitive complexity counts branches, and the eight tests it flags
+ # are the CENSUS tests: one function that walks Kinds() and asserts every
+ # property khaos promises for each. Their score is assertion density, not
+ # tangle -- each `if wrong { t.Fatalf }` is independent and reads on its
+ # own -- and density is the property that makes a census worth having. The
+ # limit stays ON for source, where a high score means nested branches that
+ # actually interact.
- path: _test\.go
linters:
- funlen
- dupl
- goconst
- gosec
+ - errcheck
+ - gocognit
paths:
- vendor
- testdata
- max-same-issues: 50
settings:
errcheck:
check-type-assertions: true
- check-blank: true
+
+ # check-blank is off, and this is a decision rather than a default. It
+ # treats `_ = f()` as unchecked, which means it distrusts the exact thing
+ # this codebase uses to SAY a discard is deliberate. All 191 hits it
+ # produced were read: 103 in source and 88 in tests, and not one was a
+ # bug. Several were load-bearing in the other direction -- the journal
+ # append on an already-failing revert must stay best-effort so the fault
+ # stays outstanding and reclaim retries it, and the proxy's settle() read
+ # exists precisely to throw its result away.
+ #
+ # Satisfying it would mean 58 permanent //nolint:errcheck directives
+ # acknowledging a second time what `_ =` already acknowledges once, in a
+ # comment the compiler never checks, suppressing the whole line rather
+ # than one call. This file already carries about twenty nolint directives
+ # that each record a real decision; burying those among 58 ceremonial ones
+ # is how a reader learns to skim all of them.
+ #
+ # check-type-assertions stays ON: `x := y.(T)` has no `_ =` form that
+ # states intent, and getting it wrong is a panic rather than a dropped
+ # error. errcheck also still catches the genuine mistake this setting is
+ # confused with -- a bare `f()` whose error is not assigned anywhere at
+ # all, which is verified by a negative control, not assumed.
+ check-blank: false
+
+ # Writes to khaos's own output stream are not error-checked, declared once
+ # here rather than acknowledged at 46 call sites. A CLI that cannot print
+ # has already lost the operator it would report the failure to, and the
+ # exit status carries the verdict regardless. Close is deliberately NOT in
+ # this list: closing a file khaos WROTE is what flushes it, so the journal
+ # and its compaction temp file check Close and must keep checking it.
+ exclude-functions:
+ - fmt.Fprint
+ - fmt.Fprintf
+ - fmt.Fprintln
+
+ exhaustive:
+ # A switch that deliberately handles a subset and sends the rest to a
+ # default is not a bug here, and spelling the rest out as no-op cases that
+ # fall through to the same body would add about a hundred lines that say
+ # nothing. The constants this would guard are already guarded harder: every
+ # Kind dispatch is covered by a census test that walks Kinds() and fails
+ # the moment a new constant exists without a case of its own, and by a
+ # differential that fails when a trap behaves like its own control. That is
+ # exhaustiveness in BEHAVIOUR; the linter only checks that a constant is
+ # named. What this setting leaves switched on is the case the linter is
+ # genuinely better at than a test -- a switch with NO default that misses a
+ # constant and falls out to a zero value.
+ default-signifies-exhaustive: true
funlen:
lines: 88
@@ -55,6 +120,18 @@ linters:
disable:
- fieldalignment
+ # shadow is not in go vet's default suite, and this is why: all 32 hits
+ # here are `if err := f(); err != nil`, the idiom every Go reader parses
+ # without thinking, where the scoped err is checked on the next line and
+ # then gone. Both non-test hits were read in full; in one the outer err
+ # is already checked and dead, and the other is the bare idiom. Renaming
+ # 32 of them to applyErr and listenErr would make correct code read
+ # worse to silence a check with a 32-of-32 false positive rate on this
+ # tree. The bug shadow is meant to catch -- assigning the inner err and
+ # then testing the outer one -- needs the outer err to be live after the
+ # block, which none of these have.
+ - shadow
+
revive:
rules:
- name: blank-imports
@@ -83,14 +160,45 @@ linters:
- all
gosec:
+ # G104 unhandled errors: errcheck owns that question, with a stricter
+ # setting than gosec applies.
+ #
+ # G101 is a NAME heuristic. It fires on an identifier containing token,
+ # credential or secret, and this tool's entire vocabulary is those three
+ # words. All nine hits were read: eight are message, summary or format
+ # strings, and the ninth is DefaultInvalidToken, which is REQUIRED to be a
+ # known-bad constant because it is khaos's negative control.
+ #
+ # G704 flags a request whose URL came from outside the function, which is
+ # every request khaos makes, by construction. Probing a URL the operator
+ # names IS the product, and there is no privilege boundary to cross: khaos
+ # runs as the operator, against a target the operator chose.
+ #
+ # G304 and G404 are deliberately NOT excluded. A future unsafe path open,
+ # or a future security-relevant use of math/rand in a tool that mints its
+ # own tokens, has to stay catchable, so those are acknowledged one site at
+ # a time instead of waived here.
excludes:
- G104
+ - G101
+ - G704
sloglint:
no-mixed-args: true
kv-only: true
context: all
+# Both caps are off because the defaults silently truncate the report. golangci
+# stops at 50 issues per linter and 3 per repeated message, so this project read
+# 152 issues while it actually had 311 -- errcheck alone was pinned at exactly
+# 50 of its 191. A gate that hides more than half of what it found cannot be
+# used to decide whether the tree is clean, and a cap that bites is invisible in
+# the output. These were previously set under linters.exclusions, which is not a
+# section golangci reads them from, so neither one did anything.
+issues:
+ max-issues-per-linter: 0
+ max-same-issues: 0
+
formatters:
enable:
- gci
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go
index f267e854..8acac666 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go
@@ -96,7 +96,10 @@ func (g *gateway) routes() *http.ServeMux {
}
func (g *gateway) protected(w http.ResponseWriter, r *http.Request) {
- token, scheme := strings.CutPrefix(r.Header.Get(headerAuthorization), bearerPrefix)
+ token, scheme := strings.CutPrefix(
+ r.Header.Get(headerAuthorization),
+ bearerPrefix,
+ )
if !scheme || token == "" {
w.WriteHeader(http.StatusUnauthorized)
@@ -177,7 +180,8 @@ func (g *gateway) introspect(token string) (bool, bool) {
// Treating any non-200 as "dependency unavailable, proceed" is the single
// most common fail-open shape in service-to-service code, and a reference
// implementation that contains it makes the comparison dishonest.
- if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden {
+ if response.StatusCode == http.StatusUnauthorized ||
+ response.StatusCode == http.StatusForbidden {
return false, true
}
@@ -241,5 +245,8 @@ func (g *gateway) staleCeiling() time.Duration {
func (g *gateway) remember(token string, active bool) {
g.mu.Lock()
defer g.mu.Unlock()
- g.cache[token] = cachedDecision{active: active, expires: time.Now().Add(g.cacheTTL)}
+ g.cache[token] = cachedDecision{
+ active: active,
+ expires: time.Now().Add(g.cacheTTL),
+ }
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway_test.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway_test.go
index e386dd84..51029068 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway_test.go
@@ -32,22 +32,30 @@ func newStubIDP(t *testing.T) *stubIDP {
stub := &stubIDP{validOnly: goodToken}
stub.status.Store(http.StatusOK)
- stub.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- stub.calls.Add(1)
+ stub.server = httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ stub.calls.Add(1)
- if stub.down.Load() {
- hijackAndDrop(w)
- return
- }
+ if stub.down.Load() {
+ hijackAndDrop(w)
+ return
+ }
- if status := int(stub.status.Load()); status != http.StatusOK {
- w.WriteHeader(status)
- return
- }
+ if status := int(stub.status.Load()); status != http.StatusOK {
+ w.WriteHeader(status)
+ return
+ }
- token := r.URL.Query().Get(paramToken)
- writeJSON(w, introspection{Active: token == stub.validOnly, User: "operator"})
- }))
+ token := r.URL.Query().Get(paramToken)
+ writeJSON(
+ w,
+ introspection{
+ Active: token == stub.validOnly,
+ User: "operator",
+ },
+ )
+ }),
+ )
t.Cleanup(stub.server.Close)
@@ -92,16 +100,22 @@ func TestFailClosedServesFromCacheThenRefuses(t *testing.T) {
idp.down.Store(true)
if got := ask(t, g, bearerPrefix+goodToken); got != http.StatusOK {
- t.Fatalf("immediately after the outage the gateway returned %d; it should still be "+
- "serving from its decision cache", got)
+ t.Fatalf(
+ "immediately after the outage the gateway returned %d; it should still be "+
+ "serving from its decision cache",
+ got,
+ )
}
time.Sleep(shortTTL * 2)
if got := ask(t, g, bearerPrefix+goodToken); got != http.StatusForbidden {
- t.Fatalf("after the cache expired the gateway returned %d, want 403; a target that "+
- "serves from cache and then refuses has STOPPED serving, and asking only whether "+
- "it ever served reports that as a clean survival", got)
+ t.Fatalf(
+ "after the cache expired the gateway returned %d, want 403; a target that "+
+ "serves from cache and then refuses has STOPPED serving, and asking only whether "+
+ "it ever served reports that as a clean survival",
+ got,
+ )
}
}
@@ -109,16 +123,26 @@ func TestFailOpenHonoursACredentialItHadRefused(t *testing.T) {
idp := newStubIDP(t)
g := newGateway(idp.server.URL, FailOpen, shortTTL)
- if got := ask(t, g, bearerPrefix+"never-issued"); got != http.StatusForbidden {
- t.Fatalf("baseline returned %d for an invalid credential, want 403", got)
+ if got := ask(
+ t,
+ g,
+ bearerPrefix+"never-issued",
+ ); got != http.StatusForbidden {
+ t.Fatalf(
+ "baseline returned %d for an invalid credential, want 403",
+ got,
+ )
}
idp.down.Store(true)
time.Sleep(shortTTL * 2)
if got := ask(t, g, bearerPrefix+"never-issued"); got != http.StatusOK {
- t.Fatalf("returned %d; the fail-open mode exists to honour a credential it had already "+
- "refused, and if it does not the range cannot produce the finding khaos is for", got)
+ t.Fatalf(
+ "returned %d; the fail-open mode exists to honour a credential it had already "+
+ "refused, and if it does not the range cannot produce the finding khaos is for",
+ got,
+ )
}
}
@@ -130,11 +154,19 @@ func TestARefusalFromTheProviderIsAnAnswerNotAnOutage(t *testing.T) {
g := newGateway(idp.server.URL, FailOpen, shortTTL)
- if got := ask(t, g, bearerPrefix+goodToken); got != http.StatusForbidden {
- t.Fatalf("the provider answered %d and the gateway returned %d; treating a "+
- "refusal from a dependency as 'dependency unavailable, proceed' is the most "+
- "common fail-open shape there is, and it must not be in the reference "+
- "implementation unlabelled", status, got)
+ if got := ask(
+ t,
+ g,
+ bearerPrefix+goodToken,
+ ); got != http.StatusForbidden {
+ t.Fatalf(
+ "the provider answered %d and the gateway returned %d; treating a "+
+ "refusal from a dependency as 'dependency unavailable, proceed' is the most "+
+ "common fail-open shape there is, and it must not be in the reference "+
+ "implementation unlabelled",
+ status,
+ got,
+ )
}
})
}
@@ -186,10 +218,14 @@ func TestAFreshCredentialPerRequestDefeatsTheDecisionCache(t *testing.T) {
fresh := idp.calls.Load()
if repeated >= fresh {
- t.Fatalf("a repeated credential produced %d provider calls and a fresh one produced %d; "+
- "a negative control that reuses one token keeps the decision cache warm, so the "+
- "cached refusal answers every probe and a control that stops enforcing is never "+
- "exercised", repeated, fresh)
+ t.Fatalf(
+ "a repeated credential produced %d provider calls and a fresh one produced %d; "+
+ "a negative control that reuses one token keeps the decision cache warm, so the "+
+ "cached refusal answers every probe and a control that stops enforcing is never "+
+ "exercised",
+ repeated,
+ fresh,
+ )
}
}
@@ -218,9 +254,15 @@ func TestTheProviderIssuesAndRevokes(t *testing.T) {
t.Fatal("a freshly issued token was not active")
}
- if _, err := http.Post(server.URL+routeRevoke+"?"+paramToken+"="+token, "", nil); err != nil {
+ revoked, err := http.Post(
+ server.URL+routeRevoke+"?"+paramToken+"="+token,
+ "",
+ nil,
+ )
+ if err != nil {
t.Fatalf("revoke: %v", err)
}
+ _ = revoked.Body.Close()
if active(t, server.URL, token) {
t.Fatal("a revoked token was still active")
@@ -230,7 +272,9 @@ func TestTheProviderIssuesAndRevokes(t *testing.T) {
func active(t *testing.T, base, token string) bool {
t.Helper()
- response, err := http.Get(base + routeIntrospect + "?" + paramToken + "=" + token)
+ response, err := http.Get(
+ base + routeIntrospect + "?" + paramToken + "=" + token,
+ )
if err != nil {
t.Fatalf("introspect: %v", err)
}
@@ -266,9 +310,17 @@ func TestStaleRearmSurvivesSteadyTrafficAndLapsesOnAPause(t *testing.T) {
for beat := range beats {
time.Sleep(shortTTL + shortTTL/2)
- if status := ask(t, g, bearerPrefix+goodToken); status != http.StatusOK {
- t.Fatalf("beat %d: status %d, want 200. Steady traffic must keep a re-armed cache "+
- "alive, or this mode is not the TTL-extension bug", beat, status)
+ if status := ask(
+ t,
+ g,
+ bearerPrefix+goodToken,
+ ); status != http.StatusOK {
+ t.Fatalf(
+ "beat %d: status %d, want 200. Steady traffic must keep a re-armed cache "+
+ "alive, or this mode is not the TTL-extension bug",
+ beat,
+ status,
+ )
}
}
@@ -276,8 +328,10 @@ func TestStaleRearmSurvivesSteadyTrafficAndLapsesOnAPause(t *testing.T) {
time.Sleep(shortTTL*staleCeilingFactor + shortTTL)
if status := ask(t, g, bearerPrefix+goodToken); status == http.StatusOK {
- t.Fatalf("after a pause longer than the ceiling the gateway still served the cached " +
- "allow, so this mode is a cache with no expiry rather than one being re-armed")
+ t.Fatalf(
+ "after a pause longer than the ceiling the gateway still served the cached " +
+ "allow, so this mode is a cache with no expiry rather than one being re-armed",
+ )
}
}
@@ -289,8 +343,12 @@ func TestWithoutACeilingStaleRearmWouldBeANoExpiryCache(t *testing.T) {
g := newGateway(idp.server.URL, FailStaleRearm, shortTTL)
if ceiling := g.staleCeiling(); ceiling <= shortTTL {
- t.Fatalf("the staleness ceiling is %s against a %s lifetime; a ceiling that is not "+
- "wider than the lifetime cannot be re-armed into", ceiling, shortTTL)
+ t.Fatalf(
+ "the staleness ceiling is %s against a %s lifetime; a ceiling that is not "+
+ "wider than the lifetime cannot be re-armed into",
+ ceiling,
+ shortTTL,
+ )
}
if status := ask(t, g, bearerPrefix+goodToken); status != http.StatusOK {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go
index 87a35577..b49bb375 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go
@@ -74,17 +74,25 @@ func run() error {
ReadHeaderTimeout: readHeaderTimeout,
}
- ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ ctx, stop := signal.NotifyContext(
+ context.Background(),
+ os.Interrupt,
+ syscall.SIGTERM,
+ )
defer stop()
go func() {
<-ctx.Done()
- shutdown, cancel := context.WithTimeout(context.Background(), shutdownGrace)
+ shutdown, cancel := context.WithTimeout(
+ context.Background(),
+ shutdownGrace,
+ )
defer cancel()
_ = server.Shutdown(shutdown)
}()
- if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ if err := server.ListenAndServe(); err != nil &&
+ !errors.Is(err, http.ErrServerClosed) {
return err
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go
index edc351a4..a8ee7399 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go
@@ -34,7 +34,10 @@ type verifierGateway struct {
verifier *verifier.Verifier
}
-func newVerifierGateway(issuer, failMode string, keyTTL, decisionTTL time.Duration) *verifierGateway {
+func newVerifierGateway(
+ issuer, failMode string,
+ keyTTL, decisionTTL time.Duration,
+) *verifierGateway {
issuer = strings.TrimSuffix(issuer, "/")
return &verifierGateway{
@@ -61,7 +64,10 @@ func (g *verifierGateway) routes() *http.ServeMux {
}
func (g *verifierGateway) protected(w http.ResponseWriter, r *http.Request) {
- token, scheme := strings.CutPrefix(r.Header.Get(headerAuthorization), bearerPrefix)
+ token, scheme := strings.CutPrefix(
+ r.Header.Get(headerAuthorization),
+ bearerPrefix,
+ )
if !scheme || token == "" {
w.WriteHeader(http.StatusUnauthorized)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go
index da548ebc..c13cae7c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go
@@ -13,14 +13,13 @@ import (
"strings"
"syscall"
- "golang.org/x/term"
-
"github.com/CarterPerez-dev/khaos/internal/cli"
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/run"
"github.com/CarterPerez-dev/khaos/internal/shell"
"github.com/CarterPerez-dev/khaos/internal/theme"
"github.com/CarterPerez-dev/khaos/internal/version"
+ "golang.org/x/term"
)
const (
@@ -43,14 +42,20 @@ const (
fixFormat = " fix: %s\n"
)
-var errInterrupted = errors.New("interrupted before the run could reach a verdict")
+var errInterrupted = errors.New(
+ "interrupted before the run could reach a verdict",
+)
func main() {
os.Exit(execute())
}
func execute() int {
- ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ ctx, stop := signal.NotifyContext(
+ context.Background(),
+ os.Interrupt,
+ syscall.SIGTERM,
+ )
defer stop()
args := os.Args[1:]
@@ -79,7 +84,14 @@ func interactive(args []string, stdin, stdout *os.File) bool {
if len(args) > 0 {
return false
}
- return term.IsTerminal(int(stdin.Fd())) && term.IsTerminal(int(stdout.Fd()))
+ return term.IsTerminal(fd(stdin)) && term.IsTerminal(fd(stdout))
+}
+
+// fd narrows a descriptor for the syscall wrappers that want an int. A file
+// descriptor is bounded by RLIMIT_NOFILE, orders of magnitude below MaxInt, so
+// the conversion cannot overflow.
+func fd(file *os.File) int {
+ return int(file.Fd()) //nolint:gosec // bounded by RLIMIT_NOFILE
}
func noColorRequested(args []string) bool {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main_test.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main_test.go
index 0aa6cf52..a21a56f0 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main_test.go
@@ -6,11 +6,11 @@ package main
import (
"context"
"errors"
+ "os"
+ "testing"
"github.com/CarterPerez-dev/khaos/internal/cli"
"github.com/CarterPerez-dev/khaos/internal/run"
- "os"
- "testing"
)
func notATTY(t *testing.T) *os.File {
@@ -57,8 +57,10 @@ func TestInteractiveRefusesEveryNonTerminalCombination(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if interactive(tc.args, tc.stdin(t), tc.stdout(t)) {
- t.Fatal("interactive() said yes without a terminal on both ends; " +
- "the console spins forever on a non-TTY stdin, writing megabytes per second")
+ t.Fatal(
+ "interactive() said yes without a terminal on both ends; " +
+ "the console spins forever on a non-TTY stdin, writing megabytes per second",
+ )
}
})
}
@@ -98,9 +100,16 @@ func TestNoColorFlagAcceptsEverySpellingPflagDoes(t *testing.T) {
for _, tc := range cases {
t.Run(tc.arg, func(t *testing.T) {
- if got := noColorRequested([]string{"banner", tc.arg}); got != tc.want {
- t.Fatalf("noColorRequested(%q) = %v, want %v; cobra and this pre-parser must agree "+
- "or the flag is accepted and silently ignored", tc.arg, got, tc.want)
+ if got := noColorRequested(
+ []string{"banner", tc.arg},
+ ); got != tc.want {
+ t.Fatalf(
+ "noColorRequested(%q) = %v, want %v; cobra and this pre-parser must agree "+
+ "or the flag is accepted and silently ignored",
+ tc.arg,
+ got,
+ tc.want,
+ )
}
})
}
@@ -125,10 +134,26 @@ func TestRollbackFailureOutranksEveryOtherExitCode(t *testing.T) {
want int
}{
{"rollback alone", run.ErrRevertFailed, exitRevertFailed},
- {"rollback joined with cancellation", errors.Join(context.Canceled, run.ErrRevertFailed), exitRevertFailed},
- {"rollback joined with a defect", errors.Join(cli.ErrDefectFound, run.ErrRevertFailed), exitRevertFailed},
- {"rollback joined with inconclusive", errors.Join(cli.ErrInconclusive, run.ErrRevertFailed), exitRevertFailed},
- {"a target that never came back", cli.ErrNotRecovered, exitRevertFailed},
+ {
+ "rollback joined with cancellation",
+ errors.Join(context.Canceled, run.ErrRevertFailed),
+ exitRevertFailed,
+ },
+ {
+ "rollback joined with a defect",
+ errors.Join(cli.ErrDefectFound, run.ErrRevertFailed),
+ exitRevertFailed,
+ },
+ {
+ "rollback joined with inconclusive",
+ errors.Join(cli.ErrInconclusive, run.ErrRevertFailed),
+ exitRevertFailed,
+ },
+ {
+ "a target that never came back",
+ cli.ErrNotRecovered,
+ exitRevertFailed,
+ },
{"cancellation alone", context.Canceled, exitInterrupted},
{"defect alone", cli.ErrDefectFound, exitDefect},
{"inconclusive alone", cli.ErrInconclusive, exitInconclusive},
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/banner/banner_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/banner/banner_test.go
index 307e62c5..a904641b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/banner/banner_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/banner/banner_test.go
@@ -40,7 +40,11 @@ func TestArtDimensionsAreLocked(t *testing.T) {
func TestArtCarriesNoFileHeader(t *testing.T) {
for i, line := range Lines() {
if strings.Contains(line, "AngelaMos") || strings.HasPrefix(line, "#") {
- t.Fatalf("line %d looks like a file header and would print inside the banner: %q", i, line)
+ t.Fatalf(
+ "line %d looks like a file header and would print inside the banner: %q",
+ i,
+ line,
+ )
}
}
}
@@ -57,7 +61,11 @@ func TestRenderIncludesVersionAndAuthor(t *testing.T) {
func TestRenderThroughNoColorWriterIsPlainText(t *testing.T) {
var buf bytes.Buffer
- w := theme.NewWriter(&buf, []string{"CLICOLOR_FORCE=1", "COLORTERM=truecolor"}, true)
+ w := theme.NewWriter(
+ &buf,
+ []string{"CLICOLOR_FORCE=1", "COLORTERM=truecolor"},
+ true,
+ )
if err := Write(w); err != nil {
t.Fatalf("write: %v", err)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/doctor.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/doctor.go
index 8a1f3bac..6d238e97 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/doctor.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/doctor.go
@@ -9,11 +9,10 @@ import (
"fmt"
"io"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/render"
"github.com/CarterPerez-dev/khaos/internal/theme"
+ "github.com/spf13/cobra"
)
const (
@@ -72,9 +71,15 @@ func runDoctor(ctx context.Context, out io.Writer) error {
continue
}
- if _, err := fmt.Fprintf(out, fixFormat,
+ if _, err := fmt.Fprintf(
+ out,
+ fixFormat,
render.FixIndent,
- theme.Fg(theme.TextBright, render.FixPrefix+check.Fix)); err != nil {
+ theme.Fg(
+ theme.TextBright,
+ render.FixPrefix+check.Fix,
+ ),
+ ); err != nil {
return err
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go
index e2ad3115..2d4d4d77 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go
@@ -16,8 +16,6 @@ import (
"strings"
"time"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/experiment"
"github.com/CarterPerez-dev/khaos/internal/inject"
@@ -29,6 +27,7 @@ import (
"github.com/CarterPerez-dev/khaos/internal/run"
"github.com/CarterPerez-dev/khaos/internal/theme"
"github.com/CarterPerez-dev/khaos/internal/workspace"
+ "github.com/spf13/cobra"
)
const (
@@ -122,13 +121,21 @@ enforcing in the first place.`
listSep = ", "
)
-var ErrDefectFound = errors.New("the target broke in the direction this experiment declares a defect")
+var ErrDefectFound = errors.New(
+ "the target broke in the direction this experiment declares a defect",
+)
-var ErrNotRecovered = errors.New("the target did not return to its steady state after khaos reverted the fault, so it may still be degraded")
+var ErrNotRecovered = errors.New(
+ "the target did not return to its steady state after khaos reverted the fault, so it may still be degraded",
+)
-var ErrUnusableIssuer = errors.New("that issuer does not tell khaos where to listen")
+var ErrUnusableIssuer = errors.New(
+ "that issuer does not tell khaos where to listen",
+)
-var ErrInconclusive = errors.New("this run did not reach a conclusion, so nothing can be concluded from it either way")
+var ErrInconclusive = errors.New(
+ "this run did not reach a conclusion, so nothing can be concluded from it either way",
+)
func newCatalogCmd() *cobra.Command {
return &cobra.Command{
@@ -196,7 +203,11 @@ func unknownExperiment(verb string, args []string) error {
return err
}
}
- return fmt.Errorf(errNoExperiment, verb, strings.Join(experiment.Names(), listSep))
+ return fmt.Errorf(
+ errNoExperiment,
+ verb,
+ strings.Join(experiment.Names(), listSep),
+ )
}
func newPlanExperimentCmd(definition experiment.Definition) *cobra.Command {
@@ -236,7 +247,13 @@ func newRunExperimentCmd(definition experiment.Definition) *cobra.Command {
if err != nil {
return err
}
- return runExperiment(cmd.Context(), cmd.OutOrStdout(), definition, ttl, given)
+ return runExperiment(
+ cmd.Context(),
+ cmd.OutOrStdout(),
+ definition,
+ ttl,
+ given,
+ )
},
}
@@ -256,10 +273,13 @@ func experimentFlags(cmd *cobra.Command, definition experiment.Definition) {
cmd.Flags().String(param.Name, "", paramUsage(param))
}
- cmd.Flags().Duration(flagBaselineFor, experiment.DefaultBaselineFor, baselineUsage)
+ cmd.Flags().
+ Duration(flagBaselineFor, experiment.DefaultBaselineFor, baselineUsage)
cmd.Flags().Duration(flagFaultFor, experiment.DefaultFaultFor, faultUsage)
- cmd.Flags().Duration(flagRecoverFor, experiment.DefaultRecoveryFor, recoverUsage)
- cmd.Flags().Duration(flagSampleEvery, experiment.DefaultSampleInterval, sampleUsage)
+ cmd.Flags().
+ Duration(flagRecoverFor, experiment.DefaultRecoveryFor, recoverUsage)
+ cmd.Flags().
+ Duration(flagSampleEvery, experiment.DefaultSampleInterval, sampleUsage)
}
func paramUsage(param experiment.Param) string {
@@ -275,7 +295,10 @@ type inputs struct {
Timing experiment.Timing
}
-func experimentInputs(cmd *cobra.Command, definition experiment.Definition) (inputs, error) {
+func experimentInputs(
+ cmd *cobra.Command,
+ definition experiment.Definition,
+) (inputs, error) {
project, err := cmd.Flags().GetString(flagProject)
if err != nil {
return inputs{}, err
@@ -336,27 +359,59 @@ func runCatalog(out io.Writer) error {
theme.Fg(theme.TextFaint, "DEFECT IS"))
for _, definition := range experiment.Catalog() {
- fmt.Fprintf(out, rowLayout, render.Indent,
- theme.Fg(theme.TextBright, render.Cell(definition.Name, colExperiment)),
- theme.Fg(theme.TextNormal, render.Cell(definition.Family, colFamily)),
- theme.Fg(theme.TextDim, render.Cell(definition.FaultKind, colFault)),
- theme.Fg(directionColor(definition.Polarity.Defects[0]), definition.Polarity.Declared()))
-
- fmt.Fprintf(out, noteLayout, render.FixIndent, theme.Fg(theme.TextDim, definition.Summary))
+ fmt.Fprintf(
+ out,
+ rowLayout,
+ render.Indent,
+ theme.Fg(
+ theme.TextBright,
+ render.Cell(definition.Name, colExperiment),
+ ),
+ theme.Fg(
+ theme.TextNormal,
+ render.Cell(definition.Family, colFamily),
+ ),
+ theme.Fg(
+ theme.TextDim,
+ render.Cell(definition.FaultKind, colFault),
+ ),
+ theme.Fg(
+ directionColor(definition.Polarity.Defects[0]),
+ definition.Polarity.Declared(),
+ ),
+ )
+
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.FixIndent,
+ theme.Fg(theme.TextDim, definition.Summary),
+ )
}
fmt.Fprintln(out)
return nil
}
-func runPlan(ctx context.Context, out io.Writer, definition experiment.Definition, given inputs) error {
+func runPlan(
+ ctx context.Context,
+ out io.Writer,
+ definition experiment.Definition,
+ given inputs,
+) error {
work, err := workspace.OpenShared(ctx)
if err != nil {
return err
}
defer work.Close()
- supplied, err := fillFromRange(ctx, out, work.Docker, definition, given.Supplied)
+ supplied, err := fillFromRange(
+ ctx,
+ out,
+ work.Docker,
+ definition,
+ given.Supplied,
+ )
if err != nil {
return err
}
@@ -369,7 +424,12 @@ func runPlan(ctx context.Context, out io.Writer, definition experiment.Definitio
project := given.Project
guard := dockerx.Guard{Project: project, SelfID: dockerx.SelfContainerID()}
- target, err := work.Docker.Accept(ctx, spec.Fault.Target, dockerx.Filter{Project: project}, guard)
+ target, err := work.Docker.Accept(
+ ctx,
+ spec.Fault.Target,
+ dockerx.Filter{Project: project},
+ guard,
+ )
if err != nil {
return err
}
@@ -388,7 +448,11 @@ func describe(out io.Writer, spec experiment.Experiment, resolved string) {
field(out, labelTarget, resolved)
field(out, labelValid, spec.Probes.Valid.Describe())
field(out, labelInvalid, spec.Probes.Invalid.Describe())
- field(out, labelPolarity, spec.Polarity.Declared()+" ("+spec.Polarity.Rationale+")")
+ field(
+ out,
+ labelPolarity,
+ spec.Polarity.Declared()+" ("+spec.Polarity.Rationale+")",
+ )
timing := spec.Timing
field(out, labelTiming, fmt.Sprintf(timingFormat,
@@ -412,7 +476,13 @@ func runExperiment(
}
defer work.Close()
- supplied, err := fillFromRange(ctx, out, work.Docker, definition, given.Supplied)
+ supplied, err := fillFromRange(
+ ctx,
+ out,
+ work.Docker,
+ definition,
+ given.Supplied,
+ )
if err != nil {
return err
}
@@ -432,7 +502,12 @@ func runExperiment(
// khaos never even accepted. That is the same "true statement about a run that
// never had a chance, blaming the target" failure the parameter model exists
// to kill, arriving on the output path instead of the input path.
- accepted, err := work.Docker.Accept(ctx, spec.Fault.Target, dockerx.Filter{Project: project}, guard)
+ accepted, err := work.Docker.Accept(
+ ctx,
+ spec.Fault.Target,
+ dockerx.Filter{Project: project},
+ guard,
+ )
if err != nil {
return err
}
@@ -473,43 +548,106 @@ func runExperiment(
session := run.NewSession(env, work.Journal, ttl)
+ engine := wire(
+ out,
+ session,
+ work.Docker,
+ dockerx.Filter{Project: project},
+ guard,
+ )
+
+ describe(out, spec, accepted.Name)
+
+ result, runErr := underLease(ctx, engine, spec, session)
+
+ result.RunID = session.RunID()
+ reportVerdict(out, result)
+
+ return exitFor(result, runErr)
+}
+
+// wire builds the injector and the engine. Everything in here is progress
+// reporting and none of it is policy, which is why the two literals are long
+// and why they belong together away from the run itself.
+func wire(
+ out io.Writer,
+ session *run.Session,
+ resolver run.Resolver,
+ filter dockerx.Filter,
+ guard dockerx.Guard,
+) experiment.Engine {
injector := &run.Injector{
Session: session,
- Resolver: work.Docker,
- Filter: dockerx.Filter{Project: project},
+ Resolver: resolver,
+ Filter: filter,
Guard: guard,
Progress: func(record journal.Record, failure error) {
if failure != nil {
- event(out, markError, theme.StatusError,
- fmt.Sprintf(faultFormat, record.Kind, record.TargetName, failure))
+ event(
+ out,
+ markError,
+ theme.StatusError,
+ fmt.Sprintf(
+ faultFormat,
+ record.Kind,
+ record.TargetName,
+ failure,
+ ),
+ )
+
return
}
- event(out, markRevert, theme.StatusOK, subject(record.Kind, record.TargetName))
+
+ event(
+ out,
+ markRevert,
+ theme.StatusOK,
+ subject(record.Kind, record.TargetName),
+ )
},
}
- engine := experiment.Engine{
+ return experiment.Engine{
Injector: injector,
Report: func(e experiment.Event) {
- event(out, markPlan, theme.TextFaint, fmt.Sprintf(stageFormat, e.Stage, e.Detail))
+ event(
+ out,
+ markPlan,
+ theme.TextFaint,
+ fmt.Sprintf(stageFormat, e.Stage, e.Detail),
+ )
},
}
+}
- describe(out, spec, accepted.Name)
-
- // The lease must be renewed for as long as the run holds a fault. Without
- // this, `khaos reap` reverts the fault partway through and the engine
- // scores a target that was never under fault as a clean survival.
+// underLease runs the experiment while the session's lease is kept alive, which
+// it must be for as long as the run holds a fault. Without the renewal `khaos
+// reap` reverts the fault partway through and the engine scores a target that
+// was never under fault as a clean survival.
+//
+// A lease that STOPPED being renewed is therefore an epistemic failure, not a
+// warning: the fault may have been reverted underneath the measurement, so the
+// result cannot be believed even though the engine returned one.
+func underLease(
+ ctx context.Context,
+ engine experiment.Engine,
+ spec experiment.Experiment,
+ session *run.Session,
+) (experiment.Result, error) {
keepCtx, stopKeeping := context.WithCancel(ctx)
renewals := make(chan error, 1)
go func() {
- renewals <- session.Lease().Keep(keepCtx, func(time.Time) error { return session.Renew() })
+ renewals <- session.Lease().Keep(
+ keepCtx,
+ func(time.Time) error { return session.Renew() },
+ )
}()
result, runErr := engine.Run(ctx, spec)
stopKeeping()
+
if keepErr := <-renewals; !errors.Is(keepErr, context.Canceled) {
result.Verdict.Epistemic = experiment.Aborted
result.Verdict.Conclusive = false
@@ -517,9 +655,14 @@ func runExperiment(
runErr = errors.Join(runErr, keepErr)
}
- result.RunID = session.RunID()
- reportVerdict(out, result)
+ return result, runErr
+}
+// exitFor maps a finished run onto khaos's exit contract, and the ORDER is the
+// contract. The operator's first question is the state of their own system, not
+// the verdict about it, so a failed rollback and a target khaos never saw come
+// back both rank ABOVE the defect the run went looking for.
+func exitFor(result experiment.Result, runErr error) error {
if runErr != nil {
return runErr
}
@@ -547,7 +690,11 @@ func runExperiment(
// verdict text said so honestly, and the exit code said success. Design
// section 8 assigns 4 to inconclusive, and that is what this produces.
if !conclusive(result.Verdict.Epistemic) {
- return fmt.Errorf(errInconclusive, ErrInconclusive, result.Verdict.Epistemic)
+ return fmt.Errorf(
+ errInconclusive,
+ ErrInconclusive,
+ result.Verdict.Epistemic,
+ )
}
// khaos's OWN confidence field, which the exit code used to ignore entirely.
@@ -561,7 +708,11 @@ func runExperiment(
// Recovery that was never observed is not recovery.
if result.Verdict.Recovery == experiment.Unobserved {
- return fmt.Errorf(errInconclusive, ErrInconclusive, verdictRecoveryUnobserved)
+ return fmt.Errorf(
+ errInconclusive,
+ ErrInconclusive,
+ verdictRecoveryUnobserved,
+ )
}
return nil
@@ -577,14 +728,24 @@ func conclusive(epistemic experiment.Epistemic) bool {
func reportVerdict(out io.Writer, result experiment.Result) {
fmt.Fprintln(out)
- field(out, labelVerdict, theme.Fg(directionColor(result.Verdict.Direction),
- fmt.Sprintf(verdictFormat, result.Verdict.Epistemic, result.Verdict.Direction)))
+ field(out, labelVerdict, theme.Fg(
+ directionColor(result.Verdict.Direction),
+ fmt.Sprintf(
+ verdictFormat,
+ result.Verdict.Epistemic,
+ result.Verdict.Direction,
+ ),
+ ))
// The cause is only printed when something established one. An UNDIAGNOSED
// line on every run would read as a field khaos failed to fill rather than a
// diagnosis it never attempted.
if result.Verdict.Cause != experiment.Undiagnosed {
- field(out, labelCause, theme.Fg(theme.StatePermitted, string(result.Verdict.Cause)))
+ field(
+ out,
+ labelCause,
+ theme.Fg(theme.StatePermitted, string(result.Verdict.Cause)),
+ )
}
if result.RunID != "" {
@@ -697,7 +858,11 @@ type rangeAnswers struct {
ProxyUpstream string
}
-func rangeDefaults(lab rangelab.Lab, answers rangeAnswers, at tier) map[string]string {
+func rangeDefaults(
+ lab rangelab.Lab,
+ answers rangeAnswers,
+ at tier,
+) map[string]string {
url := lab.ProtectedURL()
target := rangelab.IDPName
@@ -714,6 +879,10 @@ func rangeDefaults(lab rangelab.Lab, answers rangeAnswers, at tier) map[string]s
// touches and leave the one it does measure unchecked.
url = lab.VerifierProtectedURL()
target = rangelab.VerifierGatewayName
+
+ default:
+ // The direct tier probes the protected URL and names the provider
+ // container, both of which are already set above.
}
return map[string]string{
@@ -752,7 +921,11 @@ func fillFromRange(
}
if len(given) > 0 {
- return nil, fmt.Errorf(errHalfSpecified, flagList(given), flagList(missing))
+ return nil, fmt.Errorf(
+ errHalfSpecified,
+ flagList(given),
+ flagList(missing),
+ )
}
lab, err := rangelab.Discover(ctx, reader)
@@ -769,11 +942,19 @@ func fillFromRange(
at := tierOf(definition.FaultKind)
if at == tierProxy && lab.ProxiedPort == 0 {
- return nil, fmt.Errorf(errNoProxiedPath, rangelab.ErrRangeIncomplete, rangelab.ProxiedGatewayName)
+ return nil, fmt.Errorf(
+ errNoProxiedPath,
+ rangelab.ErrRangeIncomplete,
+ rangelab.ProxiedGatewayName,
+ )
}
if at == tierIdP && (lab.VerifierPort == 0 || lab.Issuer == "") {
- return nil, fmt.Errorf(errNoVerifierPath, rangelab.ErrRangeIncomplete, rangelab.VerifierGatewayName)
+ return nil, fmt.Errorf(
+ errNoVerifierPath,
+ rangelab.ErrRangeIncomplete,
+ rangelab.VerifierGatewayName,
+ )
}
answers, err := askTheRange(ctx, reader, lab, missing)
@@ -791,7 +972,10 @@ func fillFromRange(
for _, name := range missing {
filled[name] = defaults[name]
if !credentialParam(name) {
- resolved = append(resolved, fmt.Sprintf(pairFormat, name, defaults[name]))
+ resolved = append(
+ resolved,
+ fmt.Sprintf(pairFormat, name, defaults[name]),
+ )
}
}
@@ -802,7 +986,10 @@ func fillFromRange(
// partitionFillable splits the parameters this experiment declares AND the range
// can answer into the ones the operator gave and the ones they did not.
-func partitionFillable(definition experiment.Definition, supplied map[string]string) ([]string, []string) {
+func partitionFillable(
+ definition experiment.Definition,
+ supplied map[string]string,
+) ([]string, []string) {
answerable := rangeSupplies()
given := []string{}
missing := []string{}
@@ -982,7 +1169,8 @@ func askTheRange(
answers.Revocable = revocable
}
- if want(experiment.ParamProxyListen) || want(experiment.ParamProxyUpstream) {
+ if want(experiment.ParamProxyListen) ||
+ want(experiment.ParamProxyUpstream) {
listen, upstream, err := lab.ProxyEndpoint(ctx, reader)
if err != nil {
return rangeAnswers{}, err
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go
index 9f03c870..3a971d28 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go
@@ -14,12 +14,11 @@ import (
"strings"
"testing"
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/experiment"
"github.com/CarterPerez-dev/khaos/internal/rangelab"
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
)
const bogusExperiment = "network.no_such_experiment"
@@ -37,36 +36,59 @@ var testAnswers = rangeAnswers{
// from "khaos looked and found none", and those are different behaviours.
type refuser struct{ t *testing.T }
-func (r refuser) Targets(context.Context, dockerx.Filter) ([]dockerx.Target, error) {
- r.t.Fatal("khaos went looking for a range although the operator supplied every parameter " +
- "a range could have answered; an operator pointed at their own stack must not need one running")
+func (r refuser) Targets(
+ context.Context,
+ dockerx.Filter,
+) ([]dockerx.Target, error) {
+ r.t.Fatal(
+ "khaos went looking for a range although the operator supplied every parameter " +
+ "a range could have answered; an operator pointed at their own stack must not need one running",
+ )
return nil, nil
}
func (r refuser) PublishedPort(context.Context, string, int) (int, error) {
- r.t.Fatal("khaos read a published port although it needed nothing from a range")
+ r.t.Fatal(
+ "khaos read a published port although it needed nothing from a range",
+ )
return 0, nil
}
-func (r refuser) ContainerEnv(context.Context, string) (map[string]string, error) {
- r.t.Fatal("khaos read a container environment although it needed nothing from a range")
+func (r refuser) ContainerEnv(
+ context.Context,
+ string,
+) (map[string]string, error) {
+ r.t.Fatal(
+ "khaos read a container environment although it needed nothing from a range",
+ )
return nil, nil
}
-func (r refuser) NetworkAddress(context.Context, string, string) (string, error) {
- r.t.Fatal("khaos read a network address although it needed nothing from a range")
+func (r refuser) NetworkAddress(
+ context.Context,
+ string,
+ string,
+) (string, error) {
+ r.t.Fatal(
+ "khaos read a network address although it needed nothing from a range",
+ )
return "", nil
}
func (r refuser) BridgeGateway(context.Context) (string, error) {
- r.t.Fatal("khaos read the bridge gateway although it needed nothing from a range")
+ r.t.Fatal(
+ "khaos read the bridge gateway although it needed nothing from a range",
+ )
return "", nil
}
// absent is a daemon with no range on it at all.
type absent struct{}
-func (absent) Targets(context.Context, dockerx.Filter) ([]dockerx.Target, error) {
+func (absent) Targets(
+ context.Context,
+ dockerx.Filter,
+) ([]dockerx.Target, error) {
return nil, nil
}
@@ -147,15 +169,22 @@ func assertKeySet(t *testing.T, defaults map[string]string) {
keys := make([]string, 0, len(defaults))
for name, value := range defaults {
if value == "" {
- t.Fatalf("the range claims to answer %q but answers it with an empty string", name)
+ t.Fatalf(
+ "the range claims to answer %q but answers it with an empty string",
+ name,
+ )
}
keys = append(keys, name)
}
slices.Sort(keys)
if !slices.Equal(supplies, keys) {
- t.Fatalf("rangeSupplies() = %v but rangeDefaults answers %v; khaos would either refuse a "+
- "parameter it can fill or try to fill one it cannot", supplies, keys)
+ t.Fatalf(
+ "rangeSupplies() = %v but rangeDefaults answers %v; khaos would either refuse a "+
+ "parameter it can fill or try to fill one it cannot",
+ supplies,
+ keys,
+ )
}
}
@@ -171,8 +200,12 @@ func TestAPartlySuppliedInvocationIsRefusedRatherThanFused(t *testing.T) {
answerable := answerableFor(definition)
if len(answerable) < 2 {
- t.Fatalf("%s declares %d range-answerable parameters; with fewer than two there is no "+
- "mixing to refuse and this test cannot fail", definition.Name, len(answerable))
+ t.Fatalf(
+ "%s declares %d range-answerable parameters; with fewer than two there is no "+
+ "mixing to refuse and this test cannot fail",
+ definition.Name,
+ len(answerable),
+ )
}
for _, given := range answerable {
@@ -184,7 +217,10 @@ func TestAPartlySuppliedInvocationIsRefusedRatherThanFused(t *testing.T) {
definition, map[string]string{given: "something"})
if err == nil {
- t.Fatalf("supplying only --%s was silently completed from the range", given)
+ t.Fatalf(
+ "supplying only --%s was silently completed from the range",
+ given,
+ )
}
if !strings.Contains(err.Error(), "will not fill one half") {
@@ -200,8 +236,12 @@ func TestAPartlySuppliedInvocationIsRefusedRatherThanFused(t *testing.T) {
continue
}
if !strings.Contains(err.Error(), flagPrefix+other) {
- t.Fatalf("the refusal did not name the missing --%s, so the operator "+
- "cannot tell what to add: %v", other, err)
+ t.Fatalf(
+ "the refusal did not name the missing --%s, so the operator "+
+ "cannot tell what to add: %v",
+ other,
+ err,
+ )
}
}
})
@@ -219,14 +259,25 @@ func TestAFullySuppliedInvocationNeverTouchesTheRange(t *testing.T) {
supplied[name] = "operator-" + name
}
- filled, err := fillFromRange(context.Background(), io.Discard, refuser{t: t}, definition, supplied)
+ filled, err := fillFromRange(
+ context.Background(),
+ io.Discard,
+ refuser{t: t},
+ definition,
+ supplied,
+ )
if err != nil {
t.Fatalf("fill: %v", err)
}
for name, want := range supplied {
if filled[name] != want {
- t.Fatalf("khaos replaced the operator's --%s %q with %q", name, want, filled[name])
+ t.Fatalf(
+ "khaos replaced the operator's --%s %q with %q",
+ name,
+ want,
+ filled[name],
+ )
}
}
}
@@ -234,19 +285,32 @@ func TestAFullySuppliedInvocationNeverTouchesTheRange(t *testing.T) {
func TestAnInvocationWithNoFlagsAtAllLooksForARange(t *testing.T) {
definition := outage(t)
- _, err := fillFromRange(context.Background(), io.Discard, absent{}, definition, map[string]string{})
+ _, err := fillFromRange(
+ context.Background(),
+ io.Discard,
+ absent{},
+ definition,
+ map[string]string{},
+ )
if !errors.Is(err, rangelab.ErrNoRange) {
- t.Fatalf("err = %v, want ErrNoRange; with nothing supplied khaos must go looking for a "+
- "range, and say so when there is none", err)
+ t.Fatalf(
+ "err = %v, want ErrNoRange; with nothing supplied khaos must go looking for a "+
+ "range, and say so when there is none",
+ err,
+ )
}
// The fix has to be the whole fix. Naming a subset sends the operator straight
// into the half-specified refusal instead.
for _, name := range answerableFor(definition) {
if !strings.Contains(err.Error(), flagPrefix+name) {
- t.Fatalf("the refusal does not name --%s, so following it lands the operator in the "+
- "half-specified refusal: %v", name, err)
+ t.Fatalf(
+ "the refusal does not name --%s, so following it lands the operator in the "+
+ "half-specified refusal: %v",
+ name,
+ err,
+ )
}
}
}
@@ -268,28 +332,48 @@ func TestEveryExperimentRegistersExactlyItsDeclaredParameters(t *testing.T) {
for _, cmd := range subcommands {
definition, err := experiment.Lookup(cmd.Name())
if err != nil {
- t.Fatalf("%s %s is not an experiment: %v", verb, cmd.Name(), err)
+ t.Fatalf(
+ "%s %s is not an experiment: %v",
+ verb,
+ cmd.Name(),
+ err,
+ )
}
registered := stringFlags(cmd)
- want := append([]string{flagProject}, names(definition.Params)...)
+ want := append(
+ []string{flagProject},
+ names(definition.Params)...)
slices.Sort(registered)
slices.Sort(want)
if !slices.Equal(registered, want) {
- t.Fatalf("%s %s registers %v, want %v", verb, cmd.Name(), registered, want)
+ t.Fatalf(
+ "%s %s registers %v, want %v",
+ verb,
+ cmd.Name(),
+ registered,
+ want,
+ )
}
for _, param := range definition.Params {
flag := cmd.Flags().Lookup(param.Name)
if !strings.Contains(flag.Usage, param.Usage) {
- t.Fatalf("--%s on %s does not carry the usage the experiment declared",
- param.Name, cmd.Name())
+ t.Fatalf(
+ "--%s on %s does not carry the usage the experiment declared",
+ param.Name,
+ cmd.Name(),
+ )
}
if flag.DefValue != "" {
- t.Fatalf("--%s on %s registers a non-empty default %q, so khaos can no "+
- "longer tell an operator who set it from one who did not",
- param.Name, cmd.Name(), flag.DefValue)
+ t.Fatalf(
+ "--%s on %s registers a non-empty default %q, so khaos can no "+
+ "longer tell an operator who set it from one who did not",
+ param.Name,
+ cmd.Name(),
+ flag.DefValue,
+ )
}
}
}
@@ -300,10 +384,19 @@ func TestEveryExperimentRegistersExactlyItsDeclaredParameters(t *testing.T) {
func TestAFlagTheExperimentNeverDeclaredIsRejected(t *testing.T) {
root := NewRoot()
silence(root)
- root.SetArgs([]string{"run", experiment.NameDependencyOutage, "--not-a-parameter-of-anything", "x"})
+ root.SetArgs(
+ []string{
+ "run",
+ experiment.NameDependencyOutage,
+ "--not-a-parameter-of-anything",
+ "x",
+ },
+ )
if err := root.Execute(); err == nil {
- t.Fatal("an undeclared flag was accepted, so an operator cannot tell a typo from a parameter")
+ t.Fatal(
+ "an undeclared flag was accepted, so an operator cannot tell a typo from a parameter",
+ )
}
}
@@ -318,7 +411,11 @@ func TestAnUnknownExperimentNamesTheOnesThatExist(t *testing.T) {
err := root.Execute()
if err == nil {
- t.Fatalf("%s accepted %q as an experiment", verb, bogusExperiment)
+ t.Fatalf(
+ "%s accepted %q as an experiment",
+ verb,
+ bogusExperiment,
+ )
}
if !errors.Is(err, experiment.ErrUnknownExperiment) {
@@ -326,7 +423,10 @@ func TestAnUnknownExperimentNamesTheOnesThatExist(t *testing.T) {
}
if !strings.Contains(err.Error(), experiment.NameDependencyOutage) {
- t.Fatalf("the refusal did not name an experiment that does exist: %v", err)
+ t.Fatalf(
+ "the refusal did not name an experiment that does exist: %v",
+ err,
+ )
}
})
}
@@ -337,12 +437,22 @@ func TestAnUnknownExperimentNamesTheOnesThatExist(t *testing.T) {
func TestAnUnknownExperimentIsReportedAheadOfItsFlags(t *testing.T) {
root := NewRoot()
silence(root)
- root.SetArgs([]string{"run", bogusExperiment, "--" + experiment.ParamURL, "http://127.0.0.1:1"})
+ root.SetArgs(
+ []string{
+ "run",
+ bogusExperiment,
+ "--" + experiment.ParamURL,
+ "http://127.0.0.1:1",
+ },
+ )
err := root.Execute()
if !errors.Is(err, experiment.ErrUnknownExperiment) {
- t.Fatalf("err = %v, want ErrUnknownExperiment; reporting the unknown flag instead buries "+
- "the only thing actually wrong with the line", err)
+ t.Fatalf(
+ "err = %v, want ErrUnknownExperiment; reporting the unknown flag instead buries "+
+ "the only thing actually wrong with the line",
+ err,
+ )
}
}
@@ -353,7 +463,9 @@ func TestNamingNoExperimentAtAllListsThem(t *testing.T) {
err := root.Execute()
if err == nil {
- t.Fatal("`khaos run` with no experiment exited cleanly without running anything")
+ t.Fatal(
+ "`khaos run` with no experiment exited cleanly without running anything",
+ )
}
if !strings.Contains(err.Error(), experiment.NameDependencyOutage) {
@@ -403,7 +515,10 @@ type present struct {
port int
}
-func (p present) Targets(context.Context, dockerx.Filter) ([]dockerx.Target, error) {
+func (p present) Targets(
+ context.Context,
+ dockerx.Filter,
+) ([]dockerx.Target, error) {
return []dockerx.Target{{
ID: "range-gateway",
Name: rangelab.GatewayName,
@@ -417,11 +532,18 @@ func (p present) PublishedPort(context.Context, string, int) (int, error) {
return p.port, nil
}
-func (p present) ContainerEnv(context.Context, string) (map[string]string, error) {
+func (p present) ContainerEnv(
+ context.Context,
+ string,
+) (map[string]string, error) {
return map[string]string{}, nil
}
-func (p present) NetworkAddress(context.Context, string, string) (string, error) {
+func (p present) NetworkAddress(
+ context.Context,
+ string,
+ string,
+) (string, error) {
return "127.0.0.1", nil
}
@@ -432,17 +554,21 @@ func (p present) BridgeGateway(context.Context) (string, error) {
func rangeOnLoopback(t *testing.T) present {
t.Helper()
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/token" {
- w.WriteHeader(http.StatusUnauthorized)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- _, _ = io.WriteString(w, `{"token":"`+rangeIssuedToken+`"}`)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/token" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"token":"`+rangeIssuedToken+`"}`)
+ }),
+ )
t.Cleanup(server.Close)
- port, err := strconv.Atoi(strings.TrimPrefix(server.URL, "http://127.0.0.1:"))
+ port, err := strconv.Atoi(
+ strings.TrimPrefix(server.URL, "http://127.0.0.1:"),
+ )
if err != nil {
t.Fatalf("the test server is not on loopback: %v", err)
}
@@ -456,7 +582,13 @@ func TestARunningRangeAnswersEveryParameterItClaimsTo(t *testing.T) {
reader := rangeOnLoopback(t)
definition := outage(t)
- filled, err := fillFromRange(context.Background(), io.Discard, reader, definition, map[string]string{})
+ filled, err := fillFromRange(
+ context.Background(),
+ io.Discard,
+ reader,
+ definition,
+ map[string]string{},
+ )
if err != nil {
t.Fatalf("fill: %v", err)
}
@@ -471,8 +603,11 @@ func TestARunningRangeAnswersEveryParameterItClaimsTo(t *testing.T) {
// instead of the protected endpoint probes a path that needs no credential, so
// the baseline never observes enforcement and every verdict is baseline-not-met.
if filled[experiment.ParamURL] != reader.gateway.URL+"/protected" {
- t.Fatalf("--url answered as %q, want the protected endpoint; probing the gateway root "+
- "measures a path that needs no credential", filled[experiment.ParamURL])
+ t.Fatalf(
+ "--url answered as %q, want the protected endpoint; probing the gateway root "+
+ "measures a path that needs no credential",
+ filled[experiment.ParamURL],
+ )
}
// The target is the DEPENDENCY, not the gateway. Pausing the gateway pauses the
@@ -493,15 +628,23 @@ func TestARunningRangeAnswersEveryParameterItClaimsTo(t *testing.T) {
func TestTheRangeNoteNamesWhatWasChosenAndNeverTheCredential(t *testing.T) {
out := &strings.Builder{}
- if _, err := fillFromRange(context.Background(), out, rangeOnLoopback(t), outage(t),
- map[string]string{}); err != nil {
+ if _, err := fillFromRange(
+ context.Background(),
+ out,
+ rangeOnLoopback(t),
+ outage(t),
+ map[string]string{},
+ ); err != nil {
t.Fatalf("fill: %v", err)
}
printed := out.String()
if !strings.Contains(printed, "using the running range") {
- t.Fatalf("khaos filled an invocation from the range without saying so: %q", printed)
+ t.Fatalf(
+ "khaos filled an invocation from the range without saying so: %q",
+ printed,
+ )
}
if !strings.Contains(printed, rangelab.IDPName) {
@@ -521,7 +664,11 @@ func TestTheRangeCanSatisfyEveryExperimentsRequiredParameters(t *testing.T) {
for _, definition := range experiment.Catalog() {
t.Run(definition.Name, func(t *testing.T) {
- defaults := rangeDefaults(lab, testAnswers, tierOf(definition.FaultKind))
+ defaults := rangeDefaults(
+ lab,
+ testAnswers,
+ tierOf(definition.FaultKind),
+ )
supplied := map[string]string{}
for _, param := range definition.Params {
@@ -530,9 +677,16 @@ func TestTheRangeCanSatisfyEveryExperimentsRequiredParameters(t *testing.T) {
}
}
- if _, err := experiment.Build(definition.Name, supplied, experiment.Timing{}); err != nil {
- t.Fatalf("the range cannot satisfy %s, so it cannot run with zero flags: %v",
- definition.Name, err)
+ if _, err := experiment.Build(
+ definition.Name,
+ supplied,
+ experiment.Timing{},
+ ); err != nil {
+ t.Fatalf(
+ "the range cannot satisfy %s, so it cannot run with zero flags: %v",
+ definition.Name,
+ err,
+ )
}
})
}
@@ -545,7 +699,9 @@ func TestTheRangeCanSatisfyEveryExperimentsRequiredParameters(t *testing.T) {
// resolves keys from. Pointing either at the wrong gateway measures a service
// with no causal connection to the fault and reports a clean survival over an
// armed fault.
-func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(t *testing.T) {
+func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(
+ t *testing.T,
+) {
lab := fullLab()
want := map[tier]string{
@@ -557,8 +713,11 @@ func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(t *testing.
seen := map[string]tier{}
for at, url := range want {
if other, clash := seen[url]; clash {
- t.Fatalf("%s and %s resolve to the same URL, so this test cannot tell them apart",
- tierName(at), tierName(other))
+ t.Fatalf(
+ "%s and %s resolve to the same URL, so this test cannot tell them apart",
+ tierName(at),
+ tierName(other),
+ )
}
seen[url] = at
}
@@ -594,8 +753,10 @@ func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(t *testing.
for _, at := range allTiers() {
if !exercised[at] {
- t.Errorf("the catalogue exercises no experiment %s, so this test cannot fail for that tier",
- tierName(at))
+ t.Errorf(
+ "the catalogue exercises no experiment %s, so this test cannot fail for that tier",
+ tierName(at),
+ )
}
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go
index cc9f8945..a3227c99 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go
@@ -11,8 +11,6 @@ import (
"strings"
"time"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/inject"
"github.com/CarterPerez-dev/khaos/internal/journal"
@@ -20,6 +18,7 @@ import (
"github.com/CarterPerez-dev/khaos/internal/run"
"github.com/CarterPerez-dev/khaos/internal/theme"
"github.com/CarterPerez-dev/khaos/internal/workspace"
+ "github.com/spf13/cobra"
)
const (
@@ -96,7 +95,10 @@ func injectLong() string {
return `inject applies one raw fault to one consenting target, holds it, and reverts it
when you stop the command.
-Available kinds: ` + strings.Join(inject.DirectKinds(), ", ") + `
+Available kinds: ` + strings.Join(
+ inject.DirectKinds(),
+ ", ",
+ ) + `
The fault carries a lease. Everything the revert will need is written to the
journal BEFORE the fault is applied, so a khaos killed outright still leaves a
@@ -118,13 +120,21 @@ func onlyKnownKind(_ *cobra.Command, args []string) error {
// name rather than attempted. It would otherwise fail deep inside the
// mutation with a message about a proxy the operator never asked for.
if !inject.IsDirect(args[0]) {
- return fmt.Errorf(errNotDirect, args[0], strings.Join(inject.DirectKinds(), ", "))
+ return fmt.Errorf(
+ errNotDirect,
+ args[0],
+ strings.Join(inject.DirectKinds(), ", "),
+ )
}
return nil
}
-func completeKinds(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
+func completeKinds(
+ _ *cobra.Command,
+ args []string,
+ _ string,
+) ([]string, cobra.ShellCompDirective) {
if len(args) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
@@ -172,12 +182,19 @@ func runInject(
}
if err := session.Inject(ctx, kind, confirmed); err != nil {
- return errors.Join(err, revert(withoutCancel(ctx, timeout), out, session))
+ return errors.Join(
+ err,
+ revert(withoutCancel(ctx, timeout), out, session),
+ )
}
event(out, markInject, theme.StatusWarn, subject(kind, confirmed.Name))
- note(out, fmt.Sprintf(msgLeaseInfo,
- session.RunID(), session.Lease().ID(), session.Lease().ExpiresAt().Format(time.RFC3339)))
+ note(out, fmt.Sprintf(
+ msgLeaseInfo,
+ session.RunID(),
+ session.Lease().ID(),
+ session.Lease().ExpiresAt().Format(time.RFC3339),
+ ))
say(out, msgInjected)
waitErr := hold_(ctx, session, hold)
@@ -202,7 +219,11 @@ func runInject(
return errors.Join(skipCancellation(waitErr), revertErr)
}
-func hold_(ctx context.Context, session *run.Session, hold time.Duration) error {
+func hold_(
+ ctx context.Context,
+ session *run.Session,
+ hold time.Duration,
+) error {
keepCtx, stop := context.WithCancel(ctx)
renewals := make(chan error, 1)
@@ -255,13 +276,26 @@ func revert(ctx context.Context, out io.Writer, session *run.Session) error {
err := session.RevertAll(ctx, func(record journal.Record, failure error) {
if failure != nil {
- event(out, markError, theme.StatusError,
- fmt.Sprintf(faultFormat, record.Kind, record.TargetName, failure))
+ event(
+ out,
+ markError,
+ theme.StatusError,
+ fmt.Sprintf(
+ faultFormat,
+ record.Kind,
+ record.TargetName,
+ failure,
+ ),
+ )
return
}
- event(out, markRevert, theme.StatusOK, subject(record.Kind, record.TargetName))
+ event(
+ out,
+ markRevert,
+ theme.StatusOK,
+ subject(record.Kind, record.TargetName),
+ )
})
-
if err != nil {
fmt.Fprintln(out)
return err
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/print.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/print.go
index 70e201ed..b258a6ba 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/print.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/print.go
@@ -21,7 +21,12 @@ const (
)
func say(out io.Writer, text string) {
- fmt.Fprintf(out, lineLayout, render.Indent, theme.Fg(theme.TextNormal, text))
+ fmt.Fprintf(
+ out,
+ lineLayout,
+ render.Indent,
+ theme.Fg(theme.TextNormal, text),
+ )
}
func note(out io.Writer, text string) {
@@ -37,7 +42,12 @@ func fixLine(out io.Writer, fix string) {
if fix == "" {
return
}
- fmt.Fprintf(out, lineLayout, render.FixIndent, theme.Fg(theme.TextBright, render.FixPrefix+fix))
+ fmt.Fprintf(
+ out,
+ lineLayout,
+ render.FixIndent,
+ theme.Fg(theme.TextBright, render.FixPrefix+fix),
+ )
}
func subject(kind, target string) string {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go
index 67d4bca3..68a4665a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go
@@ -12,14 +12,13 @@ import (
"slices"
"strings"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/rangelab"
"github.com/CarterPerez-dev/khaos/internal/render"
"github.com/CarterPerez-dev/khaos/internal/theme"
"github.com/CarterPerez-dev/khaos/internal/verifier"
"github.com/CarterPerez-dev/khaos/internal/workspace"
+ "github.com/spf13/cobra"
)
var ErrUnknownFailMode = errors.New("the range has no such fail mode")
@@ -108,7 +107,14 @@ func newRangeUpCmd() *cobra.Command {
if err != nil {
return err
}
- return runRangeUp(cmd.Context(), cmd.OutOrStdout(), failMode, cacheTTL, port, quiet)
+ return runRangeUp(
+ cmd.Context(),
+ cmd.OutOrStdout(),
+ failMode,
+ cacheTTL,
+ port,
+ quiet,
+ )
},
}
@@ -173,7 +179,11 @@ func newRangeStatusCmd() *cobra.Command {
// safe behaviour, and the refusal lists what is available because nobody is
// going to remember ten mode names.
func knownFailModes() []string {
- modes := []string{rangelab.FailModeShut, rangelab.FailModeOpen, rangelab.FailModeStaleRearm}
+ modes := []string{
+ rangelab.FailModeShut,
+ rangelab.FailModeOpen,
+ rangelab.FailModeStaleRearm,
+ }
for _, mode := range verifier.Modes() {
if !slices.Contains(modes, mode) {
@@ -184,7 +194,13 @@ func knownFailModes() []string {
return modes
}
-func runRangeUp(ctx context.Context, out io.Writer, failMode, cacheTTL string, port int, quiet bool) error {
+func runRangeUp(
+ ctx context.Context,
+ out io.Writer,
+ failMode, cacheTTL string,
+ port int,
+ quiet bool,
+) error {
if !slices.Contains(knownFailModes(), failMode) {
return fmt.Errorf(errUnknownFailMode, ErrUnknownFailMode, failMode,
strings.Join(knownFailModes(), listSep))
@@ -262,7 +278,10 @@ func runRangeStatus(ctx context.Context, out io.Writer) error {
}
defer work.Close()
- targets, err := work.Docker.Targets(ctx, dockerx.Filter{Project: rangelab.ProjectName})
+ targets, err := work.Docker.Targets(
+ ctx,
+ dockerx.Filter{Project: rangelab.ProjectName},
+ )
if err != nil {
return err
}
@@ -301,7 +320,11 @@ func runRangeStatus(ctx context.Context, out io.Writer) error {
return nil
}
-func describeEntryPoints(ctx context.Context, out io.Writer, reader rangelab.PortReader) {
+func describeEntryPoints(
+ ctx context.Context,
+ out io.Writer,
+ reader rangelab.PortReader,
+) {
lab, err := rangelab.Discover(ctx, reader)
if err != nil {
return
@@ -310,11 +333,25 @@ func describeEntryPoints(ctx context.Context, out io.Writer, reader rangelab.Por
say(out, fmt.Sprintf(msgTierDirect, lab.ProtectedURL()))
if lab.ProxiedPort != 0 {
- say(out, fmt.Sprintf(msgTierProxied, lab.ProxiedProtectedURL(), lab.ProxyPort))
+ say(
+ out,
+ fmt.Sprintf(
+ msgTierProxied,
+ lab.ProxiedProtectedURL(),
+ lab.ProxyPort,
+ ),
+ )
}
if lab.VerifierPort != 0 {
- say(out, fmt.Sprintf(msgTierVerifier, lab.VerifierProtectedURL(), lab.Issuer))
+ say(
+ out,
+ fmt.Sprintf(
+ msgTierVerifier,
+ lab.VerifierProtectedURL(),
+ lab.Issuer,
+ ),
+ )
}
fmt.Fprintln(out)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/reclaim.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/reclaim.go
index 1acd1fef..99b6575a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/reclaim.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/reclaim.go
@@ -9,11 +9,10 @@ import (
"io"
"time"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/run"
"github.com/CarterPerez-dev/khaos/internal/theme"
"github.com/CarterPerez-dev/khaos/internal/workspace"
+ "github.com/spf13/cobra"
)
const (
@@ -104,7 +103,13 @@ func runReclaim(ctx context.Context, out io.Writer, expiredOnly bool) error {
defer work.Close()
fmt.Fprintln(out)
- sweep := run.Reclaim(ctx, work.Env(), work.Journal, time.Now().UTC(), expiredOnly)
+ sweep := run.Reclaim(
+ ctx,
+ work.Env(),
+ work.Journal,
+ time.Now().UTC(),
+ expiredOnly,
+ )
report(out, sweep)
if len(sweep.Results) == 0 {
@@ -142,14 +147,23 @@ func runReap(ctx context.Context, out io.Writer, interval time.Duration) error {
fmt.Fprintln(out)
return nil
case <-ticker.C:
- sweep := run.Reclaim(ctx, work.Env(), work.Journal, time.Now().UTC(), true)
+ sweep := run.Reclaim(
+ ctx,
+ work.Env(),
+ work.Journal,
+ time.Now().UTC(),
+ true,
+ )
report(out, sweep)
reclaimed += len(sweep.Results)
}
}
}
-func openFor(ctx context.Context, expiredOnly bool) (*workspace.Workspace, error) {
+func openFor(
+ ctx context.Context,
+ expiredOnly bool,
+) (*workspace.Workspace, error) {
if expiredOnly {
return workspace.OpenShared(ctx)
}
@@ -165,13 +179,31 @@ func report(out io.Writer, sweep run.Sweep) {
for _, result := range sweep.Results {
if result.Err != nil {
failed = true
- event(out, markError, theme.StatusError,
- fmt.Sprintf(faultFormat, result.Record.Kind, result.Record.TargetName, result.Err))
+ event(
+ out,
+ markError,
+ theme.StatusError,
+ fmt.Sprintf(
+ faultFormat,
+ result.Record.Kind,
+ result.Record.TargetName,
+ result.Err,
+ ),
+ )
continue
}
- event(out, markRevert, theme.StatusOK,
- fmt.Sprintf(leaseFormat, result.Record.Kind, result.Record.TargetName,
- result.Record.RunID, result.Record.LeaseID))
+ event(
+ out,
+ markRevert,
+ theme.StatusOK,
+ fmt.Sprintf(
+ leaseFormat,
+ result.Record.Kind,
+ result.Record.TargetName,
+ result.Record.RunID,
+ result.Record.LeaseID,
+ ),
+ )
}
if len(sweep.Results) > 0 && !failed {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root.go
index 87a636d5..4fb80dcf 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root.go
@@ -6,10 +6,9 @@ package cli
import (
"fmt"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/banner"
"github.com/CarterPerez-dev/khaos/internal/version"
+ "github.com/spf13/cobra"
)
const (
@@ -65,7 +64,12 @@ func newVersionCmd() *cobra.Command {
Short: versionShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
- _, err := fmt.Fprintf(cmd.OutOrStdout(), versionFormat, version.Name, version.Version())
+ _, err := fmt.Fprintf(
+ cmd.OutOrStdout(),
+ versionFormat,
+ version.Name,
+ version.Version(),
+ )
return err
},
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root_test.go
index 31a41371..3786e0d2 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/root_test.go
@@ -24,7 +24,9 @@ func TestFreshTreeDoesNotInheritFlagState(t *testing.T) {
t.Fatalf("first execute: %v", err)
}
- if set, err := first.PersistentFlags().GetBool(FlagNoColor); err != nil || !set {
+ if set, err := first.PersistentFlags().
+ GetBool(FlagNoColor); err != nil ||
+ !set {
t.Fatalf("first tree did not record the flag (set=%v err=%v)", set, err)
}
@@ -42,7 +44,9 @@ func TestFreshTreeDoesNotInheritFlagState(t *testing.T) {
}
if set {
- t.Fatal("a freshly built tree inherited --no-color from a previous invocation")
+ t.Fatal(
+ "a freshly built tree inherited --no-color from a previous invocation",
+ )
}
}
@@ -66,22 +70,30 @@ func TestSharedTreeLeaksFlagState(t *testing.T) {
}
if !set {
- t.Fatal("cobra no longer leaks flag state across invocations on a shared tree, " +
- "which means TestFreshTreeDoesNotInheritFlagState proves nothing and the " +
- "factory may no longer be load bearing")
+ t.Fatal(
+ "cobra no longer leaks flag state across invocations on a shared tree, " +
+ "which means TestFreshTreeDoesNotInheritFlagState proves nothing and the " +
+ "factory may no longer be load bearing",
+ )
}
}
func TestEveryCommandRejectsStrayArguments(t *testing.T) {
registered := NewRoot().Commands()
if len(registered) < 4 {
- t.Fatalf("only %d commands registered; this test is named 'every' and must cover them all", len(registered))
+ t.Fatalf(
+ "only %d commands registered; this test is named 'every' and must cover them all",
+ len(registered),
+ )
}
for _, cmd := range registered {
name := cmd.Name()
if cmd.Args == nil {
- t.Fatalf("%s declares no Args validator, so it silently accepts stray positional arguments", name)
+ t.Fatalf(
+ "%s declares no Args validator, so it silently accepts stray positional arguments",
+ name,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go
index 3920912f..20708e71 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go
@@ -8,11 +8,10 @@ import (
"fmt"
"io"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/render"
"github.com/CarterPerez-dev/khaos/internal/theme"
+ "github.com/spf13/cobra"
)
const (
@@ -72,7 +71,12 @@ func newTargetsCmd() *cobra.Command {
return cmd
}
-func runTargets(ctx context.Context, out io.Writer, project string, all bool) error {
+func runTargets(
+ ctx context.Context,
+ out io.Writer,
+ project string,
+ all bool,
+) error {
client, err := dockerx.Open(ctx)
if err != nil {
return fmt.Errorf("%w (run `khaos doctor` for the fix)", err)
@@ -92,16 +96,67 @@ func runTargets(ctx context.Context, out io.Writer, project string, all bool) er
}
fmt.Fprintln(out)
- fmt.Fprintf(out, noteLayout, render.Indent,
- theme.Fg(theme.TextFaint, fmt.Sprintf(endpointNote, client.Endpoint().Host)))
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.Indent,
+ theme.Fg(
+ theme.TextFaint,
+ fmt.Sprintf(endpointNote, client.Endpoint().Host),
+ ),
+ )
if len(targets) == 0 {
- fmt.Fprintf(out, noteLayout, render.Indent, theme.Fg(theme.TextNormal, emptyMessage))
- fmt.Fprintf(out, noteLayout, render.Indent, theme.Fg(theme.TextDim, dockerx.FixNoTargets))
- fmt.Fprintln(out)
+ printNoTargets(out)
return nil
}
+ refused := printTargetTable(out, targets, guard, all)
+
+ if refused > 0 && !all {
+ fmt.Fprintln(out)
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.Indent,
+ theme.Fg(
+ theme.TextDim,
+ fmt.Sprintf(refusedFormat, refused, refusedHint),
+ ),
+ )
+ }
+ fmt.Fprintln(out)
+
+ return nil
+}
+
+// printNoTargets is its own answer rather than an empty table, because the
+// operator needs the fix and an empty table does not carry one.
+func printNoTargets(out io.Writer) {
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.Indent,
+ theme.Fg(theme.TextNormal, emptyMessage),
+ )
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.Indent,
+ theme.Fg(theme.TextDim, dockerx.FixNoTargets),
+ )
+ fmt.Fprintln(out)
+}
+
+// printTargetTable writes the header and one row per target, and returns how
+// many were REFUSED. The count comes back as a value because the caller's
+// closing hint is the only thing that depends on it.
+func printTargetTable(
+ out io.Writer,
+ targets []dockerx.Target,
+ guard dockerx.Guard,
+ all bool,
+) int {
fmt.Fprintf(out, rowLayout, render.Indent,
theme.Fg(theme.TextFaint, render.Cell(headerName, colName)),
theme.Fg(theme.TextFaint, render.Cell(headerProject, colProject)),
@@ -123,26 +178,31 @@ func runTargets(ctx context.Context, out io.Writer, project string, all bool) er
status = theme.Fg(theme.StateDenied, refusal.Predicate)
}
- fmt.Fprintf(out, rowLayout, render.Indent,
+ fmt.Fprintf(
+ out,
+ rowLayout,
+ render.Indent,
theme.Fg(theme.TextBright, render.Cell(target.Name, colName)),
- theme.Fg(theme.TextNormal, render.Cell(orDash(target.Project), colProject)),
+ theme.Fg(
+ theme.TextNormal,
+ render.Cell(orDash(target.Project), colProject),
+ ),
theme.Fg(theme.TextDim, render.Cell(target.Image, colImage)),
- status)
+ status,
+ )
if all && refusal != nil {
- fmt.Fprintf(out, noteLayout, render.FixIndent, theme.Fg(theme.TextDim, refusal.Reason))
- fmt.Fprintf(out, noteLayout, render.FixIndent, theme.Fg(theme.TextBright, render.FixPrefix+refusal.Fix))
+ fmt.Fprintf(
+ out,
+ noteLayout,
+ render.FixIndent,
+ theme.Fg(theme.TextDim, refusal.Reason),
+ )
+ fixLine(out, refusal.Fix)
}
}
- if refused > 0 && !all {
- fmt.Fprintln(out)
- fmt.Fprintf(out, noteLayout, render.Indent,
- theme.Fg(theme.TextDim, fmt.Sprintf(refusedFormat, refused, refusedHint)))
- }
- fmt.Fprintln(out)
-
- return nil
+ return refused
}
func orDash(s string) string {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go
index d0096c5d..f163d62e 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go
@@ -37,45 +37,87 @@ const (
var ErrContainerGone = errors.New("the container no longer exists")
-var ErrNetworkGone = errors.New("the network no longer exists, so the container could not be reattached to it")
+var ErrNetworkGone = errors.New(
+ "the network no longer exists, so the container could not be reattached to it",
+)
func (c *Client) Pause(ctx context.Context, containerID string) error {
- if _, err := c.api.ContainerPause(ctx, containerID, client.ContainerPauseOptions{}); err != nil {
+ if _, err := c.api.ContainerPause(
+ ctx,
+ containerID,
+ client.ContainerPauseOptions{},
+ ); err != nil {
return fmt.Errorf(errPause, ShortID(containerID), c.classify(err))
}
return nil
}
func (c *Client) Unpause(ctx context.Context, containerID string) error {
- if _, err := c.api.ContainerUnpause(ctx, containerID, client.ContainerUnpauseOptions{}); err != nil {
+ if _, err := c.api.ContainerUnpause(
+ ctx,
+ containerID,
+ client.ContainerUnpauseOptions{},
+ ); err != nil {
return fmt.Errorf(errUnpause, ShortID(containerID), c.classify(err))
}
return nil
}
-func (c *Client) Disconnect(ctx context.Context, networkID, containerID string) error {
- _, err := c.api.NetworkDisconnect(ctx, networkID, client.NetworkDisconnectOptions{Container: containerID})
+func (c *Client) Disconnect(
+ ctx context.Context,
+ networkID, containerID string,
+) error {
+ _, err := c.api.NetworkDisconnect(
+ ctx,
+ networkID,
+ client.NetworkDisconnectOptions{Container: containerID},
+ )
if err != nil {
- return fmt.Errorf(errDisconnect, ShortID(containerID), networkID, c.classify(err))
+ return fmt.Errorf(
+ errDisconnect,
+ ShortID(containerID),
+ networkID,
+ c.classify(err),
+ )
}
return nil
}
-func (c *Client) Connect(ctx context.Context, networkID, containerID string, settings *network.EndpointSettings) error {
+func (c *Client) Connect(
+ ctx context.Context,
+ networkID, containerID string,
+ settings *network.EndpointSettings,
+) error {
_, err := c.api.NetworkConnect(ctx, networkID, client.NetworkConnectOptions{
Container: containerID,
EndpointConfig: settings,
})
if err != nil {
- return fmt.Errorf(errConnect, ShortID(containerID), networkID, c.classifyNetwork(ctx, containerID, err))
+ return fmt.Errorf(
+ errConnect,
+ ShortID(containerID),
+ networkID,
+ c.classifyNetwork(ctx, containerID, err),
+ )
}
return nil
}
-func (c *Client) Endpoints(ctx context.Context, containerID string) (map[string]*network.EndpointSettings, error) {
- result, err := c.api.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{})
+func (c *Client) Endpoints(
+ ctx context.Context,
+ containerID string,
+) (map[string]*network.EndpointSettings, error) {
+ result, err := c.api.ContainerInspect(
+ ctx,
+ containerID,
+ client.ContainerInspectOptions{},
+ )
if err != nil {
- return nil, fmt.Errorf(errEndpoints, ShortID(containerID), c.classify(err))
+ return nil, fmt.Errorf(
+ errEndpoints,
+ ShortID(containerID),
+ c.classify(err),
+ )
}
if result.Container.NetworkSettings == nil {
@@ -86,9 +128,17 @@ func (c *Client) Endpoints(ctx context.Context, containerID string) (map[string]
}
func (c *Client) Paused(ctx context.Context, containerID string) (bool, error) {
- result, err := c.api.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{})
+ result, err := c.api.ContainerInspect(
+ ctx,
+ containerID,
+ client.ContainerInspectOptions{},
+ )
if err != nil {
- return false, fmt.Errorf(errState, ShortID(containerID), c.classify(err))
+ return false, fmt.Errorf(
+ errState,
+ ShortID(containerID),
+ c.classify(err),
+ )
}
return result.Container.State != nil && result.Container.State.Paused, nil
}
@@ -97,8 +147,15 @@ func (c *Client) Paused(ctx context.Context, containerID string) (bool, error) {
// target is ALREADY addressing its dependency, rather than assuming the address
// khaos would have chosen: environment is fixed at container creation, so the
// container is the only authority on what it will actually dial.
-func (c *Client) ContainerEnv(ctx context.Context, containerID string) (map[string]string, error) {
- result, err := c.api.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{})
+func (c *Client) ContainerEnv(
+ ctx context.Context,
+ containerID string,
+) (map[string]string, error) {
+ result, err := c.api.ContainerInspect(
+ ctx,
+ containerID,
+ client.ContainerInspectOptions{},
+ )
if err != nil {
return nil, fmt.Errorf(errEnv, ShortID(containerID), c.classify(err))
}
@@ -120,10 +177,18 @@ func (c *Client) ContainerEnv(ctx context.Context, containerID string) (map[stri
return environ, nil
}
-func (c *Client) NetworkAddress(ctx context.Context, containerID, networkName string) (string, error) {
+func (c *Client) NetworkAddress(
+ ctx context.Context,
+ containerID, networkName string,
+) (string, error) {
endpoints, err := c.Endpoints(ctx, containerID)
if err != nil {
- return "", fmt.Errorf(errAddress, ShortID(containerID), networkName, err)
+ return "", fmt.Errorf(
+ errAddress,
+ ShortID(containerID),
+ networkName,
+ err,
+ )
}
settings, attached := endpoints[networkName]
@@ -140,7 +205,11 @@ func (c *Client) NetworkAddress(ctx context.Context, containerID, networkName st
// containers on it, and the value is NOT the commonly cited 172.17.0.1 on every
// host. Discovering it is the only correct way to find it.
func (c *Client) BridgeGateway(ctx context.Context) (string, error) {
- result, err := c.api.NetworkInspect(ctx, bridgeNetwork, client.NetworkInspectOptions{})
+ result, err := c.api.NetworkInspect(
+ ctx,
+ bridgeNetwork,
+ client.NetworkInspectOptions{},
+ )
if err != nil {
return "", fmt.Errorf(errBridge, err)
}
@@ -161,8 +230,16 @@ func (c *Client) BridgeGateway(ctx context.Context) (string, error) {
// NetworkConnect returns NotFound when the NETWORK is gone, and routing that
// through here told the session a detached container had been restored. See
// classifyNetwork.
+// The daemon's error is formatted with %v and NOT wrapped, here and in
+// classifyNetwork. Wrapping it would let a caller match on the Docker SDK's own
+// error taxonomy through khaos's error, which is the precise coupling this
+// translation exists to remove: the whole point is that "NotFound" means
+// different things depending on WHICH resource was not found, and only khaos's
+// sentinel carries that distinction. The daemon's text is for the operator to
+// read, not for code to branch on.
func (c *Client) classify(err error) error {
if errdefs.IsNotFound(err) {
+ //nolint:errorlint // %v is deliberate: see above
return fmt.Errorf("%w: %v", ErrContainerGone, err)
}
return err
@@ -175,20 +252,38 @@ func (c *Client) classify(err error) error {
//
// It resolves the ambiguity by ASKING: if the container still exists, the
// network was the missing resource and the failure stays a failure.
-func (c *Client) classifyNetwork(ctx context.Context, containerID string, err error) error {
+func (c *Client) classifyNetwork(
+ ctx context.Context,
+ containerID string,
+ err error,
+) error {
if !errdefs.IsNotFound(err) {
return err
}
- if _, alive := c.api.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{}); alive == nil {
+ if _, alive := c.api.ContainerInspect(
+ ctx,
+ containerID,
+ client.ContainerInspectOptions{},
+ ); alive == nil {
+ //nolint:errorlint // %v is deliberate: see classify
return fmt.Errorf("%w: %v", ErrNetworkGone, err)
}
+ //nolint:errorlint // %v is deliberate: see classify
return fmt.Errorf("%w: %v", ErrContainerGone, err)
}
-func (c *Client) PublishedPort(ctx context.Context, containerID string, internal int) (int, error) {
- result, err := c.api.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{})
+func (c *Client) PublishedPort(
+ ctx context.Context,
+ containerID string,
+ internal int,
+) (int, error) {
+ result, err := c.api.ContainerInspect(
+ ctx,
+ containerID,
+ client.ContainerInspectOptions{},
+ )
if err != nil {
return 0, fmt.Errorf(errPorts, ShortID(containerID), c.classify(err))
}
@@ -202,7 +297,10 @@ func (c *Client) PublishedPort(ctx context.Context, containerID string, internal
continue
}
for _, binding := range bindings {
- if published, err := strconv.Atoi(binding.HostPort); err == nil && published > 0 {
+ if published, err := strconv.Atoi(
+ binding.HostPort,
+ ); err == nil &&
+ published > 0 {
return published, nil
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go
index 8a80ed39..485d8510 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go
@@ -20,8 +20,12 @@ var (
ErrSocketMissing = errors.New("the Docker socket does not exist")
ErrSocketDenied = errors.New("permission denied on the Docker socket")
ErrNotASocket = errors.New("the Docker endpoint path is not a socket")
- ErrNothingListening = errors.New("the Docker socket exists but nothing is listening on it")
- ErrDaemonSilent = errors.New("the Docker endpoint is reachable but the daemon did not answer")
+ ErrNothingListening = errors.New(
+ "the Docker socket exists but nothing is listening on it",
+ )
+ ErrDaemonSilent = errors.New(
+ "the Docker endpoint is reachable but the daemon did not answer",
+ )
)
const (
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover.go
index b12f7c03..26231613 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover.go
@@ -27,12 +27,17 @@ const (
)
var (
- ErrNoHostConfig = errors.New("the daemon returned a container with no host configuration, so khaos cannot tell whether it is safe to touch")
- ErrEmptyName = errors.New("a target name is required")
+ ErrNoHostConfig = errors.New(
+ "the daemon returned a container with no host configuration, so khaos cannot tell whether it is safe to touch",
+ )
+ ErrEmptyName = errors.New("a target name is required")
)
func (c *Client) Targets(ctx context.Context, filter Filter) ([]Target, error) {
- consenting, err := c.list(ctx, make(client.Filters).Add(filterLabel, LabelConsent))
+ consenting, err := c.list(
+ ctx,
+ make(client.Filters).Add(filterLabel, LabelConsent),
+ )
if err != nil {
return nil, err
}
@@ -56,13 +61,20 @@ func (c *Client) Targets(ctx context.Context, filter Filter) ([]Target, error) {
}
slices.SortFunc(targets, func(a, b Target) int {
- return cmp.Or(cmp.Compare(a.Project, b.Project), cmp.Compare(a.Name, b.Name))
+ return cmp.Or(
+ cmp.Compare(a.Project, b.Project),
+ cmp.Compare(a.Name, b.Name),
+ )
})
return targets, nil
}
-func (c *Client) Lookup(ctx context.Context, name string, filter Filter) (Target, error) {
+func (c *Client) Lookup(
+ ctx context.Context,
+ name string,
+ filter Filter,
+) (Target, error) {
if strings.TrimSpace(name) == "" {
return Target{}, ErrEmptyName
}
@@ -78,7 +90,8 @@ func (c *Client) Lookup(ctx context.Context, name string, filter Filter) (Target
var matches []Target
for _, t := range targets {
- if t.Name == name || t.Service == name || strings.HasPrefix(t.ID, name) {
+ if t.Name == name || t.Service == name ||
+ strings.HasPrefix(t.ID, name) {
matches = append(matches, t)
}
}
@@ -89,11 +102,21 @@ func (c *Client) Lookup(ctx context.Context, name string, filter Filter) (Target
case 1:
return matches[0], nil
default:
- return Target{}, fmt.Errorf(errAmbiguous, name, len(matches), joinNames(matches))
+ return Target{}, fmt.Errorf(
+ errAmbiguous,
+ name,
+ len(matches),
+ joinNames(matches),
+ )
}
}
-func (c *Client) Accept(ctx context.Context, name string, filter Filter, guard Guard) (Target, error) {
+func (c *Client) Accept(
+ ctx context.Context,
+ name string,
+ filter Filter,
+ guard Guard,
+) (Target, error) {
target, err := c.Lookup(ctx, name, filter)
if err != nil {
return Target{}, err
@@ -106,15 +129,23 @@ func (c *Client) Accept(ctx context.Context, name string, filter Filter, guard G
return target, nil
}
-func (c *Client) list(ctx context.Context, filters client.Filters) ([]container.Summary, error) {
- listed, err := c.api.ContainerList(ctx, client.ContainerListOptions{All: true, Filters: filters})
+func (c *Client) list(
+ ctx context.Context,
+ filters client.Filters,
+) ([]container.Summary, error) {
+ listed, err := c.api.ContainerList(
+ ctx,
+ client.ContainerListOptions{All: true, Filters: filters},
+ )
if err != nil {
return nil, fmt.Errorf(errListFmt, err)
}
return listed.Items, nil
}
-func (c *Client) namespacePeers(ctx context.Context) (map[string][]string, error) {
+func (c *Client) namespacePeers(
+ ctx context.Context,
+) (map[string][]string, error) {
all, err := c.list(ctx, nil)
if err != nil {
return nil, err
@@ -129,7 +160,10 @@ func (c *Client) namespacePeers(ctx context.Context) (map[string][]string, error
peers := make(map[string][]string)
for _, summary := range all {
- reference, ok := strings.CutPrefix(summary.HostConfig.NetworkMode, NetworkModeContainerPfx)
+ reference, ok := strings.CutPrefix(
+ summary.HostConfig.NetworkMode,
+ NetworkModeContainerPfx,
+ )
if !ok {
continue
}
@@ -146,7 +180,11 @@ func (c *Client) namespacePeers(ctx context.Context) (map[string][]string, error
}
func (c *Client) inspect(ctx context.Context, id string) (Target, error) {
- result, err := c.api.ContainerInspect(ctx, id, client.ContainerInspectOptions{})
+ result, err := c.api.ContainerInspect(
+ ctx,
+ id,
+ client.ContainerInspectOptions{},
+ )
if err != nil {
return Target{}, fmt.Errorf(errInspect, ShortID(id), err)
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover_test.go
index 5b358646..4be31d8f 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/discover_test.go
@@ -19,8 +19,11 @@ func inspectResponse() container.InspectResponse {
NetworkMode: "shop_default",
},
Config: &container.Config{
- Image: "shop/api:latest",
- Labels: map[string]string{LabelConsent: ConsentValue, LabelComposeProject: project},
+ Image: "shop/api:latest",
+ Labels: map[string]string{
+ LabelConsent: ConsentValue,
+ LabelComposeProject: project,
+ },
},
Mounts: []container.MountPoint{{Source: "/srv/shop/config"}},
}
@@ -33,8 +36,11 @@ func TestTargetFromProducesAnAcceptableTarget(t *testing.T) {
}
if refusal := Refuse(target, Guard{Project: project}); refusal != nil {
- t.Fatalf("a healthy inspect response produced a target refused by %s (%s)",
- refusal.Predicate, refusal.Reason)
+ t.Fatalf(
+ "a healthy inspect response produced a target refused by %s (%s)",
+ refusal.Predicate,
+ refusal.Reason,
+ )
}
}
@@ -43,8 +49,11 @@ func TestTargetFromRefusesAnInspectResponseWithNoHostConfig(t *testing.T) {
raw.HostConfig = nil
if _, err := targetFrom(raw); !errors.Is(err, ErrNoHostConfig) {
- t.Fatalf("targetFrom returned %v for a nil HostConfig; it must refuse rather than zero-fill, "+
- "because zero-filled host config silently disarms every container-property predicate", err)
+ t.Fatalf(
+ "targetFrom returned %v for a nil HostConfig; it must refuse rather than zero-fill, "+
+ "because zero-filled host config silently disarms every container-property predicate",
+ err,
+ )
}
}
@@ -58,7 +67,9 @@ func TestTargetFromCarriesEveryFieldThePredicatesRead(t *testing.T) {
r.HostConfig.NetworkMode = NetworkModeHost
}, PredicateHostNetwork},
{"shared namespace", func(r *container.InspectResponse) {
- r.HostConfig.NetworkMode = container.NetworkMode(NetworkModeContainerPfx + peerID)
+ r.HostConfig.NetworkMode = container.NetworkMode(
+ NetworkModeContainerPfx + peerID,
+ )
}, PredicateSharedNamespace},
{"host pid namespace", func(r *container.InspectResponse) {
r.HostConfig.PidMode = ModeHost
@@ -76,16 +87,24 @@ func TestTargetFromCarriesEveryFieldThePredicatesRead(t *testing.T) {
r.HostConfig.CapAdd = []string{"CAP_SYS_MODULE"}
}, PredicateDangerousCap},
{"device passthrough", func(r *container.InspectResponse) {
- r.HostConfig.Devices = []container.DeviceMapping{{PathOnHost: "/dev/sda"}}
+ r.HostConfig.Devices = []container.DeviceMapping{
+ {PathOnHost: "/dev/sda"},
+ }
}, PredicateDeviceAccess},
{"unconfined profile", func(r *container.InspectResponse) {
r.HostConfig.SecurityOpt = []string{"apparmor=unconfined"}
}, PredicateUnconfined},
{"socket mount", func(r *container.InspectResponse) {
- r.Mounts = append(r.Mounts, container.MountPoint{Source: DockerSocketPath})
+ r.Mounts = append(
+ r.Mounts,
+ container.MountPoint{Source: DockerSocketPath},
+ )
}, PredicateSocketReachable},
{"socket parent directory", func(r *container.InspectResponse) {
- r.Mounts = append(r.Mounts, container.MountPoint{Source: "/var/run"})
+ r.Mounts = append(
+ r.Mounts,
+ container.MountPoint{Source: "/var/run"},
+ )
}, PredicateSocketReachable},
{"not running", func(r *container.InspectResponse) {
r.State.Running = false
@@ -107,9 +126,12 @@ func TestTargetFromCarriesEveryFieldThePredicatesRead(t *testing.T) {
refusal := Refuse(target, Guard{Project: project})
if refusal == nil {
- t.Fatalf("a container that is %s was built into an accepted target; "+
- "the field the %s predicate reads is not being carried across from the daemon response",
- tc.name, tc.predicate)
+ t.Fatalf(
+ "a container that is %s was built into an accepted target; "+
+ "the field the %s predicate reads is not being carried across from the daemon response",
+ tc.name,
+ tc.predicate,
+ )
}
if refusal.Predicate != tc.predicate {
@@ -133,7 +155,9 @@ func TestTargetFromSurvivesAbsentOptionalSections(t *testing.T) {
refusal := Refuse(target, Guard{})
if refusal == nil {
- t.Fatal("an inspect response with no Config and no State produced an accepted target")
+ t.Fatal(
+ "an inspect response with no Config and no State produced an accepted target",
+ )
}
}
@@ -144,6 +168,8 @@ func TestTargetFromMarksTheTargetInspected(t *testing.T) {
}
if !target.Inspected {
- t.Fatal("targetFrom did not mark the target as inspected, so it will be refused as incomplete")
+ t.Fatal(
+ "targetFrom did not mark the target as inspected, so it will be refused as incomplete",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go
index 2ec56bc8..242a6127 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go
@@ -63,7 +63,11 @@ func Diagnose(ctx context.Context) []Check {
return DiagnoseWith(ctx, os.Getenv, homeDir())
}
-func DiagnoseWith(ctx context.Context, environ func(string) string, home string) []Check {
+func DiagnoseWith(
+ ctx context.Context,
+ environ func(string) string,
+ home string,
+) []Check {
checks := make([]Check, 0, checkCapacity)
endpoint, err := ResolveEndpoint(environ, home)
@@ -74,13 +78,23 @@ func DiagnoseWith(ctx context.Context, environ func(string) string, home string)
Detail: endpointFailureDetail(err),
Fix: endpointFix(err),
})
- return append(checks, skipped(checkSocket), skipped(checkDaemon), skipped(checkTargets))
+ return append(
+ checks,
+ skipped(checkSocket),
+ skipped(checkDaemon),
+ skipped(checkTargets),
+ )
}
checks = append(checks, Check{
Name: checkEndpoint,
Status: StatusPass,
- Detail: fmt.Sprintf(detailEndpointFmt, endpoint.Host, endpoint.Source, contextSuffix(endpoint)),
+ Detail: fmt.Sprintf(
+ detailEndpointFmt,
+ endpoint.Host,
+ endpoint.Source,
+ contextSuffix(endpoint),
+ ),
})
path, isSocket := endpoint.SocketPath()
@@ -137,7 +151,11 @@ func socketCheck(path string, connectErr error) Check {
Fix: socketFix(connectErr, path),
}
}
- return Check{Name: checkSocket, Status: StatusPass, Detail: fmt.Sprintf(detailSocketOK, path)}
+ return Check{
+ Name: checkSocket,
+ Status: StatusPass,
+ Detail: fmt.Sprintf(detailSocketOK, path),
+ }
}
func targetsCheck(targets []Target) Check {
@@ -149,13 +167,23 @@ func targetsCheck(targets []Target) Check {
}
if consenting == 0 {
- return Check{Name: checkTargets, Status: StatusFail, Detail: detailNone, Fix: FixNoTargets}
+ return Check{
+ Name: checkTargets,
+ Status: StatusFail,
+ Detail: detailNone,
+ Fix: FixNoTargets,
+ }
}
return Check{
Name: checkTargets,
Status: StatusPass,
- Detail: fmt.Sprintf(detailTargets, consenting, LabelConsent, ConsentValue),
+ Detail: fmt.Sprintf(
+ detailTargets,
+ consenting,
+ LabelConsent,
+ ConsentValue,
+ ),
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go
index afdf1096..34973643 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go
@@ -38,7 +38,9 @@ const (
errUnresolvableContext = "%w: %s names the context %q, but its metadata could not be read"
)
-var ErrContextUnresolvable = errors.New("the selected Docker context could not be resolved")
+var ErrContextUnresolvable = errors.New(
+ "the selected Docker context could not be resolved",
+)
type Endpoint struct {
Host string
@@ -57,7 +59,10 @@ type contextMetadata struct {
} `json:"Endpoints"`
}
-func ResolveEndpoint(environ func(string) string, home string) (Endpoint, error) {
+func ResolveEndpoint(
+ environ func(string) string,
+ home string,
+) (Endpoint, error) {
if host := environ(EnvDockerHost); host != "" {
return Endpoint{Host: host, Source: SourceEnvHost}, nil
}
@@ -81,7 +86,12 @@ func ResolveEndpoint(environ func(string) string, home string) (Endpoint, error)
if name := environ(EnvDockerContext); name != "" {
host, ok := contextHost(home, name)
if !ok {
- return Endpoint{}, fmt.Errorf(errUnresolvableContext, ErrContextUnresolvable, EnvDockerContext, name)
+ return Endpoint{}, fmt.Errorf(
+ errUnresolvableContext,
+ ErrContextUnresolvable,
+ EnvDockerContext,
+ name,
+ )
}
return Endpoint{Host: host, Source: SourceEnvContext, Name: name}, nil
}
@@ -89,9 +99,18 @@ func ResolveEndpoint(environ func(string) string, home string) (Endpoint, error)
if name, ok := currentContext(home); ok && name != defaultContext {
host, found := contextHost(home, name)
if !found {
- return Endpoint{}, fmt.Errorf(errUnresolvableContext, ErrContextUnresolvable, SourceConfigContext, name)
+ return Endpoint{}, fmt.Errorf(
+ errUnresolvableContext,
+ ErrContextUnresolvable,
+ SourceConfigContext,
+ name,
+ )
}
- return Endpoint{Host: host, Source: SourceConfigContext, Name: name}, nil
+ return Endpoint{
+ Host: host,
+ Source: SourceConfigContext,
+ Name: name,
+ }, nil
}
return defaultEndpoint(environ)
@@ -103,12 +122,18 @@ func defaultEndpoint(environ func(string) string) (Endpoint, error) {
if runtimeDir := environ(EnvXDGRuntime); runtimeDir != "" {
path := filepath.Join(runtimeDir, socketBaseName)
if exists(path) {
- return Endpoint{Host: unixScheme + path, Source: SourceRootless}, nil
+ return Endpoint{
+ Host: unixScheme + path,
+ Source: SourceRootless,
+ }, nil
}
}
if exists(DockerSocketPath) {
- return Endpoint{Host: unixScheme + DockerSocketPath, Source: SourceDefault}, nil
+ return Endpoint{
+ Host: unixScheme + DockerSocketPath,
+ Source: SourceDefault,
+ }, nil
}
return Endpoint{Source: SourceNone}, ErrNoEndpoint
@@ -126,6 +151,7 @@ func (e Endpoint) SocketPath() (string, bool) {
}
func currentContext(home string) (string, bool) {
+ //nolint:gosec // the operator's own ~/.docker/config.json
raw, err := os.ReadFile(filepath.Join(home, dockerDir, configFile))
if err != nil {
return "", false
@@ -141,8 +167,16 @@ func currentContext(home string) (string, bool) {
func contextHost(home, name string) (string, bool) {
digest := sha256.Sum256([]byte(name))
- path := filepath.Join(home, dockerDir, contextsDir, contextMetaDir, hex.EncodeToString(digest[:]), contextMeta)
-
+ path := filepath.Join(
+ home,
+ dockerDir,
+ contextsDir,
+ contextMetaDir,
+ hex.EncodeToString(digest[:]),
+ contextMeta,
+ )
+
+ //nolint:gosec // a path khaos derives under the operator's ~/.docker
raw, err := os.ReadFile(path)
if err != nil {
return "", false
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint_test.go
index 41fb7a05..bc34981f 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint_test.go
@@ -30,14 +30,24 @@ func writeContext(t *testing.T, home, name, host string) {
t.Helper()
digest := sha256.Sum256([]byte(name))
- dir := filepath.Join(home, dockerDir, contextsDir, contextMetaDir, hex.EncodeToString(digest[:]))
+ dir := filepath.Join(
+ home,
+ dockerDir,
+ contextsDir,
+ contextMetaDir,
+ hex.EncodeToString(digest[:]),
+ )
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("mkdir context: %v", err)
}
body := `{"Name":"` + name + `","Endpoints":{"docker":{"Host":"` + host + `"}}}`
- if err := os.WriteFile(filepath.Join(dir, contextMeta), []byte(body), 0o644); err != nil {
+ if err := os.WriteFile(
+ filepath.Join(dir, contextMeta),
+ []byte(body),
+ 0o644,
+ ); err != nil {
t.Fatalf("write context meta: %v", err)
}
}
@@ -51,7 +61,11 @@ func writeCurrentContext(t *testing.T, home, name string) {
}
body := `{"currentContext":"` + name + `"}`
- if err := os.WriteFile(filepath.Join(dir, configFile), []byte(body), 0o644); err != nil {
+ if err := os.WriteFile(
+ filepath.Join(dir, configFile),
+ []byte(body),
+ 0o644,
+ ); err != nil {
t.Fatalf("write docker config: %v", err)
}
}
@@ -98,12 +112,16 @@ func TestEnvContextWinsOverConfigContext(t *testing.T) {
writeContext(t, home, otherCtxName, otherCtxHost)
writeCurrentContext(t, home, ctxName)
- got, err := ResolveEndpoint(fakeEnv(map[string]string{EnvDockerContext: otherCtxName}), home)
+ got, err := ResolveEndpoint(
+ fakeEnv(map[string]string{EnvDockerContext: otherCtxName}),
+ home,
+ )
if err != nil {
t.Fatalf("resolve: %v", err)
}
- if got.Host != otherCtxHost || got.Source != SourceEnvContext || got.Name != otherCtxName {
+ if got.Host != otherCtxHost || got.Source != SourceEnvContext ||
+ got.Name != otherCtxName {
t.Fatalf("got %+v, want %s via %s", got, otherCtxHost, SourceEnvContext)
}
}
@@ -118,8 +136,14 @@ func TestConfigContextIsResolvedByDigestPath(t *testing.T) {
t.Fatalf("resolve: %v", err)
}
- if got.Host != ctxHostValue || got.Source != SourceConfigContext || got.Name != ctxName {
- t.Fatalf("got %+v, want %s via %s", got, ctxHostValue, SourceConfigContext)
+ if got.Host != ctxHostValue || got.Source != SourceConfigContext ||
+ got.Name != ctxName {
+ t.Fatalf(
+ "got %+v, want %s via %s",
+ got,
+ ctxHostValue,
+ SourceConfigContext,
+ )
}
}
@@ -128,7 +152,10 @@ func TestDefaultContextFallsThroughToSockets(t *testing.T) {
writeCurrentContext(t, home, defaultContext)
runtimeDir := makeRootlessSocket(t, home)
- got, err := ResolveEndpoint(fakeEnv(map[string]string{EnvXDGRuntime: runtimeDir}), home)
+ got, err := ResolveEndpoint(
+ fakeEnv(map[string]string{EnvXDGRuntime: runtimeDir}),
+ home,
+ )
if err != nil {
t.Fatalf("resolve: %v", err)
}
@@ -146,7 +173,11 @@ func TestDefaultContextFallsThroughToSockets(t *testing.T) {
func TestAnUnresolvableNamedContextIsRefusedNotIgnored(t *testing.T) {
cases := map[string]func(t *testing.T, home string) func(string) string{
"named by DOCKER_CONTEXT": func(_ *testing.T, _ string) func(string) string {
- return fakeEnv(map[string]string{EnvDockerContext: "a-context-with-no-metadata"})
+ return fakeEnv(
+ map[string]string{
+ EnvDockerContext: "a-context-with-no-metadata",
+ },
+ )
},
"named by docker config": func(t *testing.T, home string) func(string) string {
writeCurrentContext(t, home, "a-context-with-no-metadata")
@@ -162,8 +193,11 @@ func TestAnUnresolvableNamedContextIsRefusedNotIgnored(t *testing.T) {
_, err := ResolveEndpoint(env, home)
if !errors.Is(err, ErrContextUnresolvable) {
- t.Fatalf("got %v; an explicitly named context that cannot be resolved must refuse, "+
- "never silently fall through to whatever daemon happens to be local", err)
+ t.Fatalf(
+ "got %v; an explicitly named context that cannot be resolved must refuse, "+
+ "never silently fall through to whatever daemon happens to be local",
+ err,
+ )
}
})
}
@@ -213,7 +247,11 @@ func TestAnExplicitDefaultContextSelectsTheLocalDaemon(t *testing.T) {
return ""
}
- if err := os.WriteFile(filepath.Join(socket, socketBaseName), nil, 0o600); err != nil {
+ if err := os.WriteFile(
+ filepath.Join(socket, socketBaseName),
+ nil,
+ 0o600,
+ ); err != nil {
t.Fatalf("socket: %v", err)
}
@@ -224,7 +262,10 @@ func TestAnExplicitDefaultContextSelectsTheLocalDaemon(t *testing.T) {
}
if saved.Name != "ag-server" {
- t.Fatalf("with no env set khaos resolved %q, want the saved context ag-server", saved.Name)
+ t.Fatalf(
+ "with no env set khaos resolved %q, want the saved context ag-server",
+ saved.Name,
+ )
}
withDefault := func(name string) string {
@@ -240,12 +281,17 @@ func TestAnExplicitDefaultContextSelectsTheLocalDaemon(t *testing.T) {
}
if resolved.Name == "ag-server" {
- t.Fatal("DOCKER_CONTEXT=default resolved to the saved remote context; khaos would inject " +
- "on another machine while `docker compose` acted locally")
+ t.Fatal(
+ "DOCKER_CONTEXT=default resolved to the saved remote context; khaos would inject " +
+ "on another machine while `docker compose` acted locally",
+ )
}
if !strings.HasPrefix(resolved.Host, unixScheme) {
- t.Fatalf("DOCKER_CONTEXT=default resolved to %q, want a local socket", resolved.Host)
+ t.Fatalf(
+ "DOCKER_CONTEXT=default resolved to %q, want a local socket",
+ resolved.Host,
+ )
}
}
@@ -272,7 +318,9 @@ func TestDockerHostStillOutranksDockerContext(t *testing.T) {
}
if resolved.Host != "tcp://127.0.0.1:1" {
- t.Fatalf("resolved %q; the Docker CLI gives DOCKER_HOST precedence and khaos must match",
- resolved.Host)
+ t.Fatalf(
+ "resolved %q; the Docker CLI gives DOCKER_HOST precedence and khaos must match",
+ resolved.Host,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse.go
index 1e19e9f1..7ddbb752 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse.go
@@ -81,25 +81,36 @@ func Refuse(t Target, g Guard) *Refusal {
}
func refuse(predicate string, t Target, reason, fix string) *Refusal {
- return &Refusal{Predicate: predicate, Target: t.Name, Reason: reason, Fix: fix}
+ return &Refusal{
+ Predicate: predicate,
+ Target: t.Name,
+ Reason: reason,
+ Fix: fix,
+ }
}
func checkNotInspected(t Target, _ Guard) *Refusal {
if t.Inspected {
return nil
}
- return refuse(PredicateNotInspected, t,
+ return refuse(
+ PredicateNotInspected,
+ t,
"this target was not built from a full container inspection, so the fields the safety checks read are unset rather than known-safe",
- "resolve the target through khaos rather than constructing it from a cached or partial record")
+ "resolve the target through khaos rather than constructing it from a cached or partial record",
+ )
}
func checkConsentMissing(t Target, _ Guard) *Refusal {
if _, ok := t.Labels[LabelConsent]; ok {
return nil
}
- return refuse(PredicateConsentMissing, t,
+ return refuse(
+ PredicateConsentMissing,
+ t,
"the container carries no "+LabelConsent+" label, so its owner never consented to fault injection",
- "add `labels: [\""+LabelConsent+"="+ConsentValue+"\"]` to this service in your compose file and recreate it")
+ "add `labels: [\""+LabelConsent+"="+ConsentValue+"\"]` to this service in your compose file and recreate it",
+ )
}
func checkConsentNotTrue(t Target, _ Guard) *Refusal {
@@ -107,36 +118,55 @@ func checkConsentNotTrue(t Target, _ Guard) *Refusal {
if !ok || value == ConsentValue {
return nil
}
- return refuse(PredicateConsentNotTrue, t,
- fmt.Sprintf("the %s label reads %q, and consent must be exactly %q", LabelConsent, value, ConsentValue),
- "set "+LabelConsent+"="+ConsentValue+" exactly, or remove the label entirely")
+ return refuse(
+ PredicateConsentNotTrue,
+ t,
+ fmt.Sprintf(
+ "the %s label reads %q, and consent must be exactly %q",
+ LabelConsent,
+ value,
+ ConsentValue,
+ ),
+ "set "+LabelConsent+"="+ConsentValue+" exactly, or remove the label entirely",
+ )
}
func checkIdentityChanged(t Target, g Guard) *Refusal {
if g.ExpectedID == "" || t.ID == g.ExpectedID {
return nil
}
- return refuse(PredicateIdentityChanged, t,
- "the container was replaced since the plan was made: expected "+ShortID(g.ExpectedID)+", found "+t.Short(),
- "re-run the plan so khaos resolves the container that exists now")
+ return refuse(
+ PredicateIdentityChanged,
+ t,
+ "the container was replaced since the plan was made: expected "+ShortID(
+ g.ExpectedID,
+ )+", found "+t.Short(),
+ "re-run the plan so khaos resolves the container that exists now",
+ )
}
func checkSelfTarget(t Target, g Guard) *Refusal {
if g.SelfID == "" || !sameContainer(t.ID, g.SelfID) {
return nil
}
- return refuse(PredicateSelfTarget, t,
+ return refuse(
+ PredicateSelfTarget,
+ t,
"this is the khaos container itself, and a tool that injects faults into itself cannot roll them back",
- "target a different container")
+ "target a different container",
+ )
}
func checkHostNetwork(t Target, _ Guard) *Refusal {
if !strings.EqualFold(t.NetworkMode, NetworkModeHost) {
return nil
}
- return refuse(PredicateHostNetwork, t,
+ return refuse(
+ PredicateHostNetwork,
+ t,
"the container runs in host network mode, so its network is the host network and any fault would hit the machine",
- "move the service onto a user-defined bridge network")
+ "move the service onto a user-defined bridge network",
+ )
}
func checkSharedNamespace(t Target, _ Guard) *Refusal {
@@ -144,19 +174,30 @@ func checkSharedNamespace(t Target, _ Guard) *Refusal {
if !ok {
return nil
}
- return refuse(PredicateSharedNamespace, t,
- "the container shares the network namespace of "+ShortID(peer)+", which has not consented, so a fault would reach it too",
- "target "+ShortID(peer)+" directly once it carries the consent label")
+ return refuse(
+ PredicateSharedNamespace,
+ t,
+ "the container shares the network namespace of "+ShortID(
+ peer,
+ )+", which has not consented, so a fault would reach it too",
+ "target "+ShortID(peer)+" directly once it carries the consent label",
+ )
}
func checkNamespacePeer(t Target, _ Guard) *Refusal {
if len(t.NamespacePeers) == 0 {
return nil
}
- return refuse(PredicateNamespacePeer, t,
- "the network namespace of this container is shared by "+strings.Join(t.NamespacePeers, ", ")+
+ return refuse(
+ PredicateNamespacePeer,
+ t,
+ "the network namespace of this container is shared by "+strings.Join(
+ t.NamespacePeers,
+ ", ",
+ )+
", which has not consented, so a fault here would reach it too",
- "stop the sharing container, or give it the consent label so you are injecting into both deliberately")
+ "stop the sharing container, or give it the consent label so you are injecting into both deliberately",
+ )
}
func checkHostNamespace(t Target, _ Guard) *Refusal {
@@ -166,9 +207,12 @@ func checkHostNamespace(t Target, _ Guard) *Refusal {
{"user", t.UsernsMode},
} {
if strings.EqualFold(ns.mode, ModeHost) {
- return refuse(PredicateHostNamespace, t,
+ return refuse(
+ PredicateHostNamespace,
+ t,
"the container shares the host "+ns.kind+" namespace, so it is not meaningfully isolated from the machine",
- "remove the host "+ns.kind+" namespace setting from this service, or target a different one")
+ "remove the host "+ns.kind+" namespace setting from this service, or target a different one",
+ )
}
}
return nil
@@ -178,18 +222,27 @@ func checkPrivileged(t Target, _ Guard) *Refusal {
if !t.Privileged {
return nil
}
- return refuse(PredicatePrivileged, t,
+ return refuse(
+ PredicatePrivileged,
+ t,
"the container is privileged, so it is not meaningfully isolated from the host",
- "drop `privileged: true` from this service, or target a different one")
+ "drop `privileged: true` from this service, or target a different one",
+ )
}
func checkDangerousCapability(t Target, _ Guard) *Refusal {
for _, capability := range t.Capabilities {
- name := strings.TrimPrefix(strings.ToUpper(strings.TrimSpace(capability)), capPrefix)
+ name := strings.TrimPrefix(
+ strings.ToUpper(strings.TrimSpace(capability)),
+ capPrefix,
+ )
if why, dangerous := dangerousCapabilities[name]; dangerous {
- return refuse(PredicateDangerousCap, t,
+ return refuse(
+ PredicateDangerousCap,
+ t,
"the container holds "+capability+", which grants "+why,
- "remove "+capability+" from cap_add, or target a different service")
+ "remove "+capability+" from cap_add, or target a different service",
+ )
}
}
return nil
@@ -199,17 +252,26 @@ func checkDeviceAccess(t Target, _ Guard) *Refusal {
if len(t.Devices) == 0 {
return nil
}
- return refuse(PredicateDeviceAccess, t,
- "the container is given direct access to host device(s): "+strings.Join(t.Devices, ", "),
- "remove the device passthrough, or target a different service")
+ return refuse(
+ PredicateDeviceAccess,
+ t,
+ "the container is given direct access to host device(s): "+strings.Join(
+ t.Devices,
+ ", ",
+ ),
+ "remove the device passthrough, or target a different service",
+ )
}
func checkUnconfined(t Target, _ Guard) *Refusal {
for _, opt := range t.SecurityOpt {
if strings.Contains(strings.ToLower(opt), unconfinedValue) {
- return refuse(PredicateUnconfined, t,
+ return refuse(
+ PredicateUnconfined,
+ t,
"the container runs with "+opt+", so its kernel confinement is disabled",
- "remove that security_opt entry, or target a different service")
+ "remove that security_opt entry, or target a different service",
+ )
}
}
return nil
@@ -218,10 +280,13 @@ func checkUnconfined(t Target, _ Guard) *Refusal {
func checkSocketReachable(t Target, _ Guard) *Refusal {
for _, source := range t.BindSources {
if reason, reachable := socketReachableFrom(source); reachable {
- return refuse(PredicateSocketReachable, t,
+ return refuse(
+ PredicateSocketReachable,
+ t,
"the container bind-mounts "+source+", which "+reason+
", and access to the Docker daemon is equivalent to root on this machine",
- "remove that bind mount, or target a service that cannot reach the daemon")
+ "remove that bind mount, or target a service that cannot reach the daemon",
+ )
}
}
return nil
@@ -244,9 +309,12 @@ func checkNotRunning(t Target, _ Guard) *Refusal {
if t.Running {
return nil
}
- return refuse(PredicateNotRunning, t,
+ return refuse(
+ PredicateNotRunning,
+ t,
"the container is not running, so there is no steady state to establish and no behavior to measure",
- "start the container, then re-run")
+ "start the container, then re-run",
+ )
}
func socketPaths() []string {
@@ -268,7 +336,8 @@ func socketReachableFrom(source string) (string, bool) {
if resolved == socket || resolved == resolvePath(socket) {
return "is the Docker socket", true
}
- if isAncestor(resolved, socket) || isAncestor(resolved, resolvePath(socket)) {
+ if isAncestor(resolved, socket) ||
+ isAncestor(resolved, resolvePath(socket)) {
return "contains the Docker socket at " + socket, true
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse_test.go
index 53d7cab1..c1e7c750 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/refuse_test.go
@@ -17,12 +17,15 @@ const (
func acceptable() (Target, Guard) {
return Target{
- ID: acceptableID,
- Name: "shop-api-1",
- Image: "shop/api:latest",
- Project: project,
- Service: "api",
- Labels: map[string]string{LabelConsent: ConsentValue, LabelComposeProject: project},
+ ID: acceptableID,
+ Name: "shop-api-1",
+ Image: "shop/api:latest",
+ Project: project,
+ Service: "api",
+ Labels: map[string]string{
+ LabelConsent: ConsentValue,
+ LabelComposeProject: project,
+ },
Running: true,
NetworkMode: "shop_default",
BindSources: []string{"/srv/shop/config"},
@@ -41,29 +44,59 @@ type control struct {
func controls() []control {
return []control{
- {PredicateNotInspected, func(t *Target, _ *Guard) { t.Inspected = false }},
- {PredicateConsentMissing, func(t *Target, _ *Guard) { delete(t.Labels, LabelConsent) }},
- {PredicateConsentNotTrue, func(t *Target, _ *Guard) { t.Labels[LabelConsent] = "yes" }},
- {PredicateIdentityChanged, func(_ *Target, g *Guard) { g.ExpectedID = peerID }},
+ {
+ PredicateNotInspected,
+ func(t *Target, _ *Guard) { t.Inspected = false },
+ },
+ {
+ PredicateConsentMissing,
+ func(t *Target, _ *Guard) { delete(t.Labels, LabelConsent) },
+ },
+ {
+ PredicateConsentNotTrue,
+ func(t *Target, _ *Guard) { t.Labels[LabelConsent] = "yes" },
+ },
+ {
+ PredicateIdentityChanged,
+ func(_ *Target, g *Guard) { g.ExpectedID = peerID },
+ },
{PredicateSelfTarget, func(t *Target, g *Guard) { g.SelfID = t.ID }},
- {PredicateHostNetwork, func(t *Target, _ *Guard) { t.NetworkMode = NetworkModeHost }},
+ {
+ PredicateHostNetwork,
+ func(t *Target, _ *Guard) { t.NetworkMode = NetworkModeHost },
+ },
{PredicateSharedNamespace, func(t *Target, _ *Guard) {
t.NetworkMode = NetworkModeContainerPfx + peerID
}},
{PredicateNamespacePeer, func(t *Target, _ *Guard) {
t.NamespacePeers = []string{"sidecar-1"}
}},
- {PredicateHostNamespace, func(t *Target, _ *Guard) { t.PidMode = ModeHost }},
- {PredicatePrivileged, func(t *Target, _ *Guard) { t.Privileged = true }},
- {PredicateDangerousCap, func(t *Target, _ *Guard) { t.Capabilities = []string{"NET_ADMIN"} }},
- {PredicateDeviceAccess, func(t *Target, _ *Guard) { t.Devices = []string{"/dev/sda"} }},
+ {
+ PredicateHostNamespace,
+ func(t *Target, _ *Guard) { t.PidMode = ModeHost },
+ },
+ {
+ PredicatePrivileged,
+ func(t *Target, _ *Guard) { t.Privileged = true },
+ },
+ {
+ PredicateDangerousCap,
+ func(t *Target, _ *Guard) { t.Capabilities = []string{"NET_ADMIN"} },
+ },
+ {
+ PredicateDeviceAccess,
+ func(t *Target, _ *Guard) { t.Devices = []string{"/dev/sda"} },
+ },
{PredicateUnconfined, func(t *Target, _ *Guard) {
t.SecurityOpt = []string{"seccomp=unconfined"}
}},
{PredicateSocketReachable, func(t *Target, _ *Guard) {
t.BindSources = append(t.BindSources, DockerSocketPath)
}},
- {PredicateScopeMismatch, func(t *Target, _ *Guard) { t.Project = "someone-elses-stack" }},
+ {
+ PredicateScopeMismatch,
+ func(t *Target, _ *Guard) { t.Project = "someone-elses-stack" },
+ },
{PredicateNotRunning, func(t *Target, _ *Guard) { t.Running = false }},
}
}
@@ -72,8 +105,11 @@ func TestAcceptableTargetIsAccepted(t *testing.T) {
target, guard := acceptable()
if refusal := Refuse(target, guard); refusal != nil {
- t.Fatalf("the control target was refused by %s (%s), so every refusal test below is vacuous",
- refusal.Predicate, refusal.Reason)
+ t.Fatalf(
+ "the control target was refused by %s (%s), so every refusal test below is vacuous",
+ refusal.Predicate,
+ refusal.Reason,
+ )
}
}
@@ -92,14 +128,25 @@ func TestEachControlFiresExactlyOnePredicate(t *testing.T) {
switch len(fired) {
case 0:
- t.Fatalf("%s accepted a target that breaks exactly its own invariant", c.predicate)
+ t.Fatalf(
+ "%s accepted a target that breaks exactly its own invariant",
+ c.predicate,
+ )
case 1:
if fired[0] != c.predicate {
- t.Fatalf("control for %s fired %s instead", c.predicate, fired[0])
+ t.Fatalf(
+ "control for %s fired %s instead",
+ c.predicate,
+ fired[0],
+ )
}
default:
- t.Fatalf("control for %s fired %d predicates (%s); they alibi each other, so gutting any one stays green",
- c.predicate, len(fired), strings.Join(fired, ", "))
+ t.Fatalf(
+ "control for %s fired %d predicates (%s); they alibi each other, so gutting any one stays green",
+ c.predicate,
+ len(fired),
+ strings.Join(fired, ", "),
+ )
}
})
}
@@ -113,7 +160,10 @@ func TestEveryPredicateHasAControl(t *testing.T) {
for _, p := range predicates {
if !covered[p.Name] {
- t.Fatalf("predicate %s has no negative control, so nothing proves it ever refuses anything", p.Name)
+ t.Fatalf(
+ "predicate %s has no negative control, so nothing proves it ever refuses anything",
+ p.Name,
+ )
}
}
@@ -138,7 +188,10 @@ func TestEveryRefusalNamesAReasonAndAFix(t *testing.T) {
}
if strings.TrimSpace(refusal.Fix) == "" {
- t.Fatalf("%s refused without telling the operator how to fix it", c.predicate)
+ t.Fatalf(
+ "%s refused without telling the operator how to fix it",
+ c.predicate,
+ )
}
})
}
@@ -167,7 +220,12 @@ func TestConsentMustBeExactlyTrue(t *testing.T) {
refused := Refuse(target, guard) != nil
if refused == tc.consented {
- t.Fatalf("consent value %q: refused=%v, want refused=%v", tc.value, refused, !tc.consented)
+ t.Fatalf(
+ "consent value %q: refused=%v, want refused=%v",
+ tc.value,
+ refused,
+ !tc.consented,
+ )
}
})
}
@@ -175,8 +233,17 @@ func TestConsentMustBeExactlyTrue(t *testing.T) {
func TestDangerousCapabilitiesAreRefusedInEverySpelling(t *testing.T) {
spellings := []string{
- "NET_ADMIN", "net_admin", "CAP_NET_ADMIN", "cap_sys_admin", "ALL",
- "SYS_MODULE", "CAP_SYS_PTRACE", "DAC_READ_SEARCH", "SYS_RAWIO", "BPF", "NET_RAW",
+ "NET_ADMIN",
+ "net_admin",
+ "CAP_NET_ADMIN",
+ "cap_sys_admin",
+ "ALL",
+ "SYS_MODULE",
+ "CAP_SYS_PTRACE",
+ "DAC_READ_SEARCH",
+ "SYS_RAWIO",
+ "BPF",
+ "NET_RAW",
}
for _, value := range spellings {
@@ -221,14 +288,22 @@ func TestSocketIsRefusedThroughEveryReachablePath(t *testing.T) {
refusal := Refuse(target, guard)
if refusal == nil || refusal.Predicate != PredicateSocketReachable {
- t.Fatalf("a bind mount of %q reaches the Docker daemon and was not refused", source)
+ t.Fatalf(
+ "a bind mount of %q reaches the Docker daemon and was not refused",
+ source,
+ )
}
})
}
}
func TestOrdinaryBindMountsAreAllowed(t *testing.T) {
- harmless := []string{"/srv/app/config", "/etc/myapp", "/var/log/myapp", "/opt/data"}
+ harmless := []string{
+ "/srv/app/config",
+ "/etc/myapp",
+ "/var/log/myapp",
+ "/opt/data",
+ }
for _, source := range harmless {
t.Run(source, func(t *testing.T) {
@@ -236,7 +311,11 @@ func TestOrdinaryBindMountsAreAllowed(t *testing.T) {
target.BindSources = []string{source}
if refusal := Refuse(target, guard); refusal != nil {
- t.Fatalf("harmless mount %q was refused by %s", source, refusal.Predicate)
+ t.Fatalf(
+ "harmless mount %q was refused by %s",
+ source,
+ refusal.Predicate,
+ )
}
})
}
@@ -277,7 +356,10 @@ func TestEmptyGuardStillEnforcesTargetProperties(t *testing.T) {
target.Project = "anything"
if refusal := Refuse(target, Guard{}); refusal != nil {
- t.Fatalf("an empty guard refused a consenting target via %s", refusal.Predicate)
+ t.Fatalf(
+ "an empty guard refused a consenting target via %s",
+ refusal.Predicate,
+ )
}
target.Privileged = true
@@ -289,11 +371,16 @@ func TestEmptyGuardStillEnforcesTargetProperties(t *testing.T) {
func TestZeroValueTargetIsRefused(t *testing.T) {
refusal := Refuse(Target{}, Guard{})
if refusal == nil {
- t.Fatal("a zero-value Target was accepted; a partially built target must never pass")
+ t.Fatal(
+ "a zero-value Target was accepted; a partially built target must never pass",
+ )
}
if refusal.Predicate != PredicateNotInspected {
- t.Fatalf("a zero-value Target was refused by %s rather than %s, so the completeness check is not first",
- refusal.Predicate, PredicateNotInspected)
+ t.Fatalf(
+ "a zero-value Target was refused by %s rather than %s, so the completeness check is not first",
+ refusal.Predicate,
+ PredicateNotInspected,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/self.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/self.go
index a12d9e7b..a1c544df 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/self.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/self.go
@@ -25,6 +25,7 @@ func SelfContainerID() string {
}
func scanForContainerID(path string) string {
+ //nolint:gosec // a procfs path from khaos's own fixed list
raw, err := os.ReadFile(path)
if err != nil {
return ""
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go
index 66b7adfe..136c6f31 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go
@@ -35,9 +35,13 @@ const (
errStray = "%w: %s reads %s, which it does not declare; declare them in its Params or stop reading them"
)
-var ErrUnknownExperiment = errors.New("no experiment is registered under that name")
+var ErrUnknownExperiment = errors.New(
+ "no experiment is registered under that name",
+)
-var ErrStrayParam = errors.New("an experiment read a parameter it never declared")
+var ErrStrayParam = errors.New(
+ "an experiment read a parameter it never declared",
+)
// Shape is the part of an experiment that depends on the operator's parameters.
// Identity, polarity, fault kind and timing all come from the declaration, so a
@@ -118,7 +122,11 @@ var outageParams = []Param{
{Name: ParamTarget, Usage: usageTarget, Required: true},
{Name: ParamURL, Usage: usageURL, Required: true},
{Name: ParamToken, Usage: usageToken, Required: true},
- {Name: ParamInvalidToken, Usage: usageInvalidToken, Default: DefaultInvalidToken},
+ {
+ Name: ParamInvalidToken,
+ Usage: usageInvalidToken,
+ Default: DefaultInvalidToken,
+ },
}
func probePair(params *Params) probe.Pair {
@@ -153,14 +161,17 @@ func buildDependencyOutage(params *Params) (Shape, error) {
var catalog = map[string]Definition{
NameDependencyOutage: {
- Name: NameDependencyOutage,
- Family: FamilyNetwork,
- Summary: outageSummary,
- Hypothesis: Hypothesis{Condition: outageGeneric, Response: outageResponse},
- Polarity: outagePolarity,
- FaultKind: inject.KindPause,
- Params: outageParams,
- Build: buildDependencyOutage,
+ Name: NameDependencyOutage,
+ Family: FamilyNetwork,
+ Summary: outageSummary,
+ Hypothesis: Hypothesis{
+ Condition: outageGeneric,
+ Response: outageResponse,
+ },
+ Polarity: outagePolarity,
+ FaultKind: inject.KindPause,
+ Params: outageParams,
+ Build: buildDependencyOutage,
},
}
@@ -184,12 +195,21 @@ func Catalog() []Definition {
func Lookup(name string) (Definition, error) {
definition, ok := catalog[name]
if !ok {
- return Definition{}, fmt.Errorf(errUnknown, ErrUnknownExperiment, name, strings.Join(Names(), nameSep))
+ return Definition{}, fmt.Errorf(
+ errUnknown,
+ ErrUnknownExperiment,
+ name,
+ strings.Join(Names(), nameSep),
+ )
}
return definition, nil
}
-func Build(name string, supplied map[string]string, timing Timing) (Experiment, error) {
+func Build(
+ name string,
+ supplied map[string]string,
+ timing Timing,
+) (Experiment, error) {
definition, err := Lookup(name)
if err != nil {
return Experiment{}, err
@@ -206,7 +226,12 @@ func Build(name string, supplied map[string]string, timing Timing) (Experiment,
}
if stray := params.strayReads(); len(stray) > 0 {
- return Experiment{}, fmt.Errorf(errStray, ErrStrayParam, name, strings.Join(stray, nameSep))
+ return Experiment{}, fmt.Errorf(
+ errStray,
+ ErrStrayParam,
+ name,
+ strings.Join(stray, nameSep),
+ )
}
spec := Experiment{
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go
index 75e9d3e1..4c0980f5 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go
@@ -62,7 +62,9 @@ type Injector interface {
Revert(ctx context.Context) error
}
-var ErrNoProbePair = errors.New("an experiment needs both a valid and an invalid probe; the invalid one is the negative control that makes the verdict mean anything")
+var ErrNoProbePair = errors.New(
+ "an experiment needs both a valid and an invalid probe; the invalid one is the negative control that makes the verdict mean anything",
+)
type Engine struct {
Injector Injector
@@ -70,6 +72,156 @@ type Engine struct {
Now func() time.Time
}
+// abandon reverts the fault and then concludes, which is what every failure
+// AFTER a successful injection has to do. It is one function rather than one
+// block per branch because there is more than one such branch, and a branch
+// that returned a verdict without reverting would leave khaos's own fault
+// applied while reporting a result -- the single outcome this tool must never
+// produce. The cause is joined with the rollback error rather than replaced by
+// it, because the caller maps a rollback failure to its own exit code.
+func (e Engine) abandon(
+ ctx context.Context,
+ spec Experiment,
+ result Result,
+ observation Observation,
+ cause error,
+) (Result, error) {
+ revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
+ observation.RollbackFailed = revertErr != nil
+
+ return e.conclude(
+ result,
+ observation,
+ spec.Polarity,
+ errors.Join(cause, revertErr),
+ )
+}
+
+// measureBaseline samples the healthy target and records how many times it
+// consulted the dependency across that window. The delta is measured HERE, in
+// the one window where the target is healthy and doing whatever it normally
+// does, because a delta of zero means the target never used the dependency this
+// experiment is about to break -- and an experiment against a dependency the
+// target ignores can only ever report HELD for the wrong reason.
+//
+// Measurement only. The two decisions that follow a baseline, whether the
+// operator interrupted it and whether it was ever a steady state, stay in Run
+// where they are visible beside the phases they skip.
+func (e Engine) measureBaseline(
+ ctx context.Context,
+ spec Experiment,
+ timing Timing,
+ observation Observation,
+) Observation {
+ e.emit(StageBaseline, detailBaseline)
+
+ consultedBefore := e.consulted(spec)
+
+ observation.Baseline = e.sample(
+ ctx,
+ spec.Probes,
+ timing.BaselineFor,
+ timing.SampleInterval,
+ )
+
+ observation.ConsultedWhat = spec.ConsultedWhat
+ observation.Consulted = e.consulted(spec) - consultedBefore
+
+ return observation
+}
+
+// injectionFailed is a conclusion of its own rather than a call to conclude,
+// because a fault that never landed leaves nothing to judge: there is no
+// behaviour under fault to have a direction, only an error to report. The
+// rollback is still attempted, since a failed Inject can still have changed
+// something before it failed.
+func (e Engine) injectionFailed(
+ ctx context.Context,
+ result Result,
+ observation Observation,
+ cause error,
+) (Result, error) {
+ revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
+ observation.RollbackFailed = revertErr != nil
+
+ result.Observation = observation
+ result.Verdict = Verdict{
+ Epistemic: Errored,
+ Direction: Undetermined,
+ Reasons: []string{cause.Error()},
+ }
+ result.Duration = e.now().Sub(result.StartedAt)
+
+ // Joined, not discarded. The caller maps the rollback failure to its own
+ // exit code, and keeping only a boolean here meant the CLI returned this
+ // error first and never reached the boolean.
+ return result, errors.Join(cause, revertErr)
+}
+
+// act performs the mid-run action, which happens AFTER the fault is confirmed
+// and BEFORE anything is measured under it. That ordering is forced rather than
+// convenient: revoking a credential while the authority is still reachable
+// makes the target cache a DENY, which a correct stale-serving implementation
+// then serves correctly. The bug only exists when the cache holds an ALLOW at
+// the moment the authority goes away, so the revocation has to be real and the
+// authority has to already be unreachable. It happens here or not at all.
+//
+// An experiment with no action returns unchanged, so the caller does not need
+// to know which kind it is holding.
+func (e Engine) act(
+ ctx context.Context,
+ spec Experiment,
+ observation Observation,
+) (Observation, error) {
+ if spec.Act == nil {
+ return observation, nil
+ }
+
+ e.emit(StageAct, spec.ActDetail)
+
+ if err := spec.Act(ctx); err != nil {
+ e.emit(StageAct, sprintf(detailActFailed, err))
+ observation.ActFailed = true
+
+ return observation, err
+ }
+
+ observation.Acted = true
+
+ return observation, nil
+}
+
+// restore reverts the fault and then measures what the target does once it is
+// gone, which together are khaos's Recovery axis: a target that never comes
+// back is a different finding from one that held throughout, and only the
+// second window can tell them apart.
+//
+// Both halves run on a context that cannot be cancelled. An operator's Ctrl-C
+// must not be able to skip the rollback, and it must not be able to skip the
+// evidence that the rollback worked either.
+func (e Engine) restore(
+ ctx context.Context,
+ spec Experiment,
+ timing Timing,
+ observation Observation,
+) (Observation, error) {
+ e.emit(StageRevert, detailRevert)
+
+ revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
+ observation.RollbackFailed = revertErr != nil
+
+ e.emit(StageRecover, detailRecover)
+
+ observation.Recovery = e.sample(
+ context.WithoutCancel(ctx),
+ spec.Probes,
+ timing.RecoveryFor,
+ timing.SampleInterval,
+ )
+
+ return observation, revertErr
+}
+
func (e Engine) Run(ctx context.Context, spec Experiment) (Result, error) {
if !spec.Probes.Complete() {
return Result{}, ErrNoProbePair
@@ -90,38 +242,36 @@ func (e Engine) Run(ctx context.Context, spec Experiment) (Result, error) {
HeldCaveat: spec.HeldCaveat,
}
- e.emit(StageBaseline, detailBaseline)
-
- // Measured across the BASELINE, where the target is healthy and whatever it
- // normally does it is doing. A delta of zero there means the target never
- // used the dependency this experiment is about to break.
- consultedBefore := e.consulted(spec)
-
- observation.Baseline = e.sample(ctx, spec.Probes, timing.BaselineFor, timing.SampleInterval)
-
- observation.ConsultedWhat = spec.ConsultedWhat
- observation.Consulted = e.consulted(spec) - consultedBefore
+ observation = e.measureBaseline(ctx, spec, timing, observation)
if ctx.Err() != nil {
- return e.conclude(result, markInterrupted(observation), spec.Polarity, nil)
+ return e.conclude(
+ result,
+ markInterrupted(observation),
+ spec.Polarity,
+ nil,
+ )
}
- if _, unmet := baselineUnmet(observation.Baseline, observation.ForgedBaseline, observation.MintedByKhaos); unmet {
+ if _, unmet := baselineUnmet(
+ observation.Baseline,
+ observation.ForgedBaseline,
+ observation.MintedByKhaos,
+ ); unmet {
return e.conclude(result, observation, spec.Polarity, nil)
}
- e.emit(StageInject, sprintf(detailInjecting, spec.Fault.Kind, spec.Fault.Target))
-
- if err := e.Injector.Inject(ctx, spec.Fault.Kind, spec.Fault.Target); err != nil {
- revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
- observation.RollbackFailed = revertErr != nil
- result.Observation = observation
- result.Verdict = Verdict{Epistemic: Errored, Direction: Undetermined, Reasons: []string{err.Error()}}
- result.Duration = e.now().Sub(result.StartedAt)
- // Joined, not discarded. The caller maps the rollback failure to its own
- // exit code, and keeping only a boolean here meant the CLI returned this
- // error first and never reached the boolean.
- return result, errors.Join(err, revertErr)
+ e.emit(
+ StageInject,
+ sprintf(detailInjecting, spec.Fault.Kind, spec.Fault.Target),
+ )
+
+ if err := e.Injector.Inject(
+ ctx,
+ spec.Fault.Kind,
+ spec.Fault.Target,
+ ); err != nil {
+ return e.injectionFailed(ctx, result, observation, err)
}
method, confirmErr := e.Injector.Confirm(ctx)
@@ -130,45 +280,27 @@ func (e Engine) Run(ctx context.Context, spec Experiment) (Result, error) {
if !observation.FaultConfirmed {
e.emit(StageConfirm, detailUnconfirm)
- revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
- observation.RollbackFailed = revertErr != nil
- return e.conclude(result, observation, spec.Polarity, errors.Join(confirmErr, revertErr))
+ return e.abandon(ctx, spec, result, observation, confirmErr)
}
e.emit(StageConfirm, sprintf(detailConfirmed, method))
- // The mid-run action happens AFTER the fault is confirmed and before anything
- // is measured under it, and that ordering is forced rather than convenient.
- // Revoking a credential while the authority is still reachable makes the
- // target cache a DENY, which a correct stale-serving control then serves
- // correctly; the bug only exists when the cache holds an ALLOW at the moment
- // the authority goes away. So the revocation has to be real and unreachable,
- // which means it happens here or not at all.
- if spec.Act != nil {
- e.emit(StageAct, spec.ActDetail)
-
- if err := spec.Act(ctx); err != nil {
- e.emit(StageAct, sprintf(detailActFailed, err))
- observation.ActFailed = true
- revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
- observation.RollbackFailed = revertErr != nil
- return e.conclude(result, observation, spec.Polarity, errors.Join(err, revertErr))
- }
-
- observation.Acted = true
+ observation, actErr := e.act(ctx, spec, observation)
+ if actErr != nil {
+ return e.abandon(ctx, spec, result, observation, actErr)
}
e.emit(StageObserve, detailObserve)
- observation.Fault = e.sample(ctx, spec.Probes, timing.FaultFor, timing.SampleInterval)
+ observation.Fault = e.sample(
+ ctx,
+ spec.Probes,
+ timing.FaultFor,
+ timing.SampleInterval,
+ )
observation = e.discriminate(ctx, spec, observation, timing)
- e.emit(StageRevert, detailRevert)
- revertErr := e.Injector.Revert(context.WithoutCancel(ctx))
- observation.RollbackFailed = revertErr != nil
-
- e.emit(StageRecover, detailRecover)
- observation.Recovery = e.sample(context.WithoutCancel(ctx), spec.Probes, timing.RecoveryFor, timing.SampleInterval)
+ observation, revertErr := e.restore(ctx, spec, timing, observation)
if ctx.Err() != nil {
observation = markInterrupted(observation)
@@ -215,17 +347,34 @@ func (e Engine) discriminate(
e.emit(StageResume, detailResume)
observation.IdleFor = spec.IdleFor
- observation.Resumed = e.sample(ctx, spec.Probes, timing.FaultFor, timing.SampleInterval)
+ observation.Resumed = e.sample(
+ ctx,
+ spec.Probes,
+ timing.FaultFor,
+ timing.SampleInterval,
+ )
return observation
}
-func (e Engine) conclude(result Result, observation Observation, polarity Polarity, err error) (Result, error) {
+func (e Engine) conclude(
+ result Result,
+ observation Observation,
+ polarity Polarity,
+ err error,
+) (Result, error) {
result.Observation = observation
result.Verdict = Judge(observation, polarity)
result.Duration = e.now().Sub(result.StartedAt)
- e.emit(StageVerdict, sprintf(detailVerdict, result.Verdict.Epistemic, result.Verdict.Direction))
+ e.emit(
+ StageVerdict,
+ sprintf(
+ detailVerdict,
+ result.Verdict.Epistemic,
+ result.Verdict.Direction,
+ ),
+ )
return result, err
}
@@ -248,7 +397,11 @@ func markInterrupted(observation Observation) Observation {
// take is subtracted from the wait, so a slow target reduces latency headroom
// rather than silently collapsing the sample count below the floor a verdict
// needs.
-func (e Engine) sample(ctx context.Context, pair probe.Pair, duration, interval time.Duration) probe.Window {
+func (e Engine) sample(
+ ctx context.Context,
+ pair probe.Pair,
+ duration, interval time.Duration,
+) probe.Window {
window := probe.Window{}
deadline := e.now().Add(duration)
@@ -286,6 +439,9 @@ func jitter(interval time.Duration) time.Duration {
if span <= 0 {
return 0
}
+ // Spread between probes, so a periodic sampler does not beat in lockstep
+ // with whatever the target does periodically. Statistical, not secret.
+ //nolint:gosec // probe spread, not a secret
return time.Duration(rand.Float64() * span)
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine_test.go
index 0de31c58..b459c6e8 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine_test.go
@@ -20,7 +20,8 @@ type scriptedProbe struct {
calls *int
}
-func (p scriptedProbe) Name() string { return "scripted" }
+func (p scriptedProbe) Name() string { return "scripted" }
+
func (p scriptedProbe) Describe() string { return "a scripted probe" }
func (p scriptedProbe) Credential() probe.Credential { return p.credential }
@@ -85,12 +86,15 @@ func quickTiming() Timing {
func spec(valid, invalid probe.Probe) Experiment {
return Experiment{
- Name: "test.experiment",
- Hypothesis: Hypothesis{Condition: "a dependency outage", Response: "a refusal"},
- Fault: Fault{Kind: "container-pause", Target: "dep"},
- Polarity: Polarity{Defects: []Direction{Permitted}},
- Probes: probe.Pair{Valid: valid, Invalid: invalid},
- Timing: quickTiming(),
+ Name: "test.experiment",
+ Hypothesis: Hypothesis{
+ Condition: "a dependency outage",
+ Response: "a refusal",
+ },
+ Fault: Fault{Kind: "container-pause", Target: "dep"},
+ Polarity: Polarity{Defects: []Direction{Permitted}},
+ Probes: probe.Pair{Valid: valid, Invalid: invalid},
+ Timing: quickTiming(),
}
}
@@ -105,14 +109,34 @@ func TestTheEngineRunsEveryStageInOrder(t *testing.T) {
engine.Report = func(e Event) { stages = append(stages, e.Stage) }
result, err := engine.Run(context.Background(), spec(
- scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls},
- scriptedProbe{probe.Invalid, probe.Rejected, probe.Rejected, &faulted, &calls},
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ scriptedProbe{
+ probe.Invalid,
+ probe.Rejected,
+ probe.Rejected,
+ &faulted,
+ &calls,
+ },
))
if err != nil {
t.Fatalf("run: %v", err)
}
- want := []Stage{StageBaseline, StageInject, StageConfirm, StageObserve, StageRevert, StageRecover, StageVerdict}
+ want := []Stage{
+ StageBaseline,
+ StageInject,
+ StageConfirm,
+ StageObserve,
+ StageRevert,
+ StageRecover,
+ StageVerdict,
+ }
if len(stages) != len(want) {
t.Fatalf("stages = %v, want %v", stages, want)
}
@@ -123,7 +147,11 @@ func TestTheEngineRunsEveryStageInOrder(t *testing.T) {
}
if injector.injects != 1 || injector.reverts != 1 {
- t.Fatalf("injects=%d reverts=%d, want 1 and 1", injector.injects, injector.reverts)
+ t.Fatalf(
+ "injects=%d reverts=%d, want 1 and 1",
+ injector.injects,
+ injector.reverts,
+ )
}
if result.Verdict.Direction != Held {
@@ -137,11 +165,29 @@ func TestTheEngineRefusesAnExperimentWithoutANegativeControl(t *testing.T) {
engine := Engine{Injector: &scriptedInjector{faulted: &faulted}}
- incomplete := spec(scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls}, nil)
+ incomplete := spec(
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ nil,
+ )
- if _, err := engine.Run(context.Background(), incomplete); !errors.Is(err, ErrNoProbePair) {
- t.Fatalf("got %v; an experiment without an invalid-credential probe has no negative "+
- "control, so its verdict would mean nothing", err)
+ if _, err := engine.Run(
+ context.Background(),
+ incomplete,
+ ); !errors.Is(
+ err,
+ ErrNoProbePair,
+ ) {
+ t.Fatalf(
+ "got %v; an experiment without an invalid-credential probe has no negative "+
+ "control, so its verdict would mean nothing",
+ err,
+ )
}
}
@@ -149,12 +195,27 @@ func TestAFailingInjectionRevertsAndNeverProducesADirection(t *testing.T) {
faulted := false
calls := 0
- injector := &scriptedInjector{faulted: &faulted, injectErr: errors.New("daemon said no")}
+ injector := &scriptedInjector{
+ faulted: &faulted,
+ injectErr: errors.New("daemon said no"),
+ }
engine := Engine{Injector: injector}
result, err := engine.Run(context.Background(), spec(
- scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls},
- scriptedProbe{probe.Invalid, probe.Rejected, probe.Rejected, &faulted, &calls},
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ scriptedProbe{
+ probe.Invalid,
+ probe.Rejected,
+ probe.Rejected,
+ &faulted,
+ &calls,
+ },
))
if err == nil {
@@ -162,13 +223,22 @@ func TestAFailingInjectionRevertsAndNeverProducesADirection(t *testing.T) {
}
if injector.reverts != 1 {
- t.Fatalf("reverts = %d; a failed injection may have partially landed and must always "+
- "be followed by a revert", injector.reverts)
+ t.Fatalf(
+ "reverts = %d; a failed injection may have partially landed and must always "+
+ "be followed by a revert",
+ injector.reverts,
+ )
}
- if result.Verdict.Epistemic != Errored || result.Verdict.Direction != Undetermined {
- t.Fatalf("verdict = %s/%s, want %s/%s",
- result.Verdict.Epistemic, result.Verdict.Direction, Errored, Undetermined)
+ if result.Verdict.Epistemic != Errored ||
+ result.Verdict.Direction != Undetermined {
+ t.Fatalf(
+ "verdict = %s/%s, want %s/%s",
+ result.Verdict.Epistemic,
+ result.Verdict.Direction,
+ Errored,
+ Undetermined,
+ )
}
}
@@ -180,20 +250,38 @@ func TestTheEngineNeverInjectsIntoATargetThatWasNotEnforcing(t *testing.T) {
engine := Engine{Injector: injector}
result, err := engine.Run(context.Background(), spec(
- scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls},
- scriptedProbe{probe.Invalid, probe.Accepted, probe.Accepted, &faulted, &calls},
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ scriptedProbe{
+ probe.Invalid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
))
if err != nil {
t.Fatalf("run: %v", err)
}
if injector.injects != 0 {
- t.Fatal("khaos injected a fault into a target that was not enforcing before the run; " +
- "there is nothing to learn and the operator paid the blast radius for it")
+ t.Fatal(
+ "khaos injected a fault into a target that was not enforcing before the run; " +
+ "there is nothing to learn and the operator paid the blast radius for it",
+ )
}
if result.Verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s", result.Verdict.Epistemic, BaselineNotMet)
+ t.Fatalf(
+ "epistemic = %s, want %s",
+ result.Verdict.Epistemic,
+ BaselineNotMet,
+ )
}
}
@@ -204,20 +292,38 @@ func TestTheEngineDetectsAControlThatGaveWayUnderFault(t *testing.T) {
engine := Engine{Injector: &scriptedInjector{faulted: &faulted}}
result, err := engine.Run(context.Background(), spec(
- scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls},
- scriptedProbe{probe.Invalid, probe.Rejected, probe.Accepted, &faulted, &calls},
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ scriptedProbe{
+ probe.Invalid,
+ probe.Rejected,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
))
if err != nil {
t.Fatalf("run: %v", err)
}
if result.Verdict.Direction != Permitted {
- t.Fatalf("direction = %s, want %s; the invalid credential was rejected before the fault "+
- "and accepted during it", result.Verdict.Direction, Permitted)
+ t.Fatalf(
+ "direction = %s, want %s; the invalid credential was rejected before the fault "+
+ "and accepted during it",
+ result.Verdict.Direction,
+ Permitted,
+ )
}
if !result.Verdict.Defect {
- t.Fatal("failing open was not flagged as a defect for a control that declares it one")
+ t.Fatal(
+ "failing open was not flagged as a defect for a control that declares it one",
+ )
}
if result.Verdict.Epistemic != Deviated {
@@ -234,8 +340,20 @@ func TestAnInterruptedRunIsNotConclusive(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
slow := spec(
- scriptedProbe{probe.Valid, probe.Accepted, probe.Accepted, &faulted, &calls},
- scriptedProbe{probe.Invalid, probe.Rejected, probe.Rejected, &faulted, &calls},
+ scriptedProbe{
+ probe.Valid,
+ probe.Accepted,
+ probe.Accepted,
+ &faulted,
+ &calls,
+ },
+ scriptedProbe{
+ probe.Invalid,
+ probe.Rejected,
+ probe.Rejected,
+ &faulted,
+ &calls,
+ },
)
slow.Timing.FaultFor = time.Second
@@ -250,7 +368,11 @@ func TestAnInterruptedRunIsNotConclusive(t *testing.T) {
}
if result.Verdict.Epistemic != Interrupted {
- t.Fatalf("epistemic = %s, want %s", result.Verdict.Epistemic, Interrupted)
+ t.Fatalf(
+ "epistemic = %s, want %s",
+ result.Verdict.Epistemic,
+ Interrupted,
+ )
}
if result.Verdict.Conclusive {
@@ -259,7 +381,10 @@ func TestAnInterruptedRunIsNotConclusive(t *testing.T) {
}
func TestTheHypothesisUsesTheCanonicalTemplate(t *testing.T) {
- h := Hypothesis{Condition: "the identity provider being unreachable", Response: "a refusal"}
+ h := Hypothesis{
+ Condition: "the identity provider being unreachable",
+ Response: "a refusal",
+ }
want := "In the event of the identity provider being unreachable, we are confident that our system will respond with a refusal."
if got := h.String(); got != want {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go
index f9dbd208..67581871 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go
@@ -95,7 +95,11 @@ const (
// because the shape is identical: the provider mints correctly until it is
// armed, so the forged stream mints per sample and has to have been accepted
// during the baseline.
-func forged(name, summary, condition, defect string, trap idp.Kind, extra ...Param) idpSpec {
+func forged(
+ name, summary, condition, defect string,
+ trap idp.Kind,
+ extra ...Param,
+) idpSpec {
spec := idpSpec{
name: name,
summary: summary,
@@ -116,8 +120,18 @@ func forged(name, summary, condition, defect string, trap idp.Kind, extra ...Par
// "no bypass was observed" would be khaos claiming it ruled out
// algorithm confusion when it ruled out one of four ways to express it.
spec.heldCaveat = func(params *Params) string {
- return sprintf(caveatOneKeyForm, params.Get(ParamKeyForm), strings.Join(idp.KeyForms(), nameSep))
+ return sprintf(
+ caveatOneKeyForm,
+ params.Get(ParamKeyForm),
+ strings.Join(idp.KeyForms(), nameSep),
+ )
}
+
+ default:
+ // Every other trap keeps the magnitude and caveat the caller declared.
+ // Falling through is the safe direction here: a missing override leaves a
+ // declared value in place, where a wrong override would change the fault
+ // khaos actually applies.
}
return spec
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery_verdict_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery_verdict_test.go
index 18792614..90448a79 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery_verdict_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery_verdict_test.go
@@ -17,32 +17,64 @@ const forgedDefectPhrase = "no signature at all and a header saying so"
// enough times to clear every sample floor. Streams given no disposition are
// left absent, which is how an experiment that declares no forged or revoked
// stream looks.
-func window(valid, invalid, forged, revoked probe.Disposition, n int) probe.Window {
+func window(
+ valid, invalid, forged, revoked probe.Disposition,
+ n int,
+) probe.Window {
out := probe.Window{}
for range n {
at := time.Now().UTC()
- out.Record(probe.Outcome{At: at, Credential: probe.Valid, Disposition: valid})
- out.Record(probe.Outcome{At: at, Credential: probe.Invalid, Disposition: invalid})
+ out.Record(
+ probe.Outcome{At: at, Credential: probe.Valid, Disposition: valid},
+ )
+ out.Record(
+ probe.Outcome{
+ At: at,
+ Credential: probe.Invalid,
+ Disposition: invalid,
+ },
+ )
if forged != "" {
- out.Record(probe.Outcome{At: at, Credential: probe.Forged, Disposition: forged})
+ out.Record(
+ probe.Outcome{
+ At: at,
+ Credential: probe.Forged,
+ Disposition: forged,
+ },
+ )
}
if revoked != "" {
- out.Record(probe.Outcome{At: at, Credential: probe.Revoked, Disposition: revoked})
+ out.Record(
+ probe.Outcome{
+ At: at,
+ Credential: probe.Revoked,
+ Disposition: revoked,
+ },
+ )
}
}
return out
}
-func forgeryObservation(baseline, fault probe.Window, expect probe.Expectation) Observation {
+func forgeryObservation(
+ baseline, fault probe.Window,
+ expect probe.Expectation,
+) Observation {
return Observation{
- Baseline: baseline,
- Fault: fault,
- Recovery: window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumPaired),
+ Baseline: baseline,
+ Fault: fault,
+ Recovery: window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumPaired,
+ ),
FaultConfirmed: true,
ConfirmMethod: "khaos read its own forged token back off the provider",
ForgedBaseline: expect,
@@ -56,7 +88,13 @@ func forgeryObservation(baseline, fault probe.Window, expect probe.Expectation)
// read the malformed token back off its own provider.
func TestOneAcceptedForgedCredentialIsAConclusiveFinding(t *testing.T) {
observation := forgeryObservation(
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumPaired),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumPaired,
+ ),
window(probe.Accepted, probe.Rejected, probe.Accepted, "", 1),
probe.ExpectAccepted,
)
@@ -74,13 +112,18 @@ func TestOneAcceptedForgedCredentialIsAConclusiveFinding(t *testing.T) {
}
if !verdict.Defect {
- t.Fatal("the identity tier declares PERMITTED a defect and this verdict did not")
+ t.Fatal(
+ "the identity tier declares PERMITTED a defect and this verdict did not",
+ )
}
joined := strings.Join(verdict.Reasons, "; ")
if !strings.Contains(joined, forgedDefectPhrase) {
- t.Fatalf("the verdict does not name what was wrong with the credential: %s", joined)
+ t.Fatalf(
+ "the verdict does not name what was wrong with the credential: %s",
+ joined,
+ )
}
// The evidence claim lives in the per-trap CONFIRM line, not in this reason.
@@ -89,8 +132,10 @@ func TestOneAcceptedForgedCredentialIsAConclusiveFinding(t *testing.T) {
// `identity.jwks_unreachable`, whose confirmed observable is the key set
// answering non-200 and which never inspects the credential at all.
if observation.ConfirmMethod == "" {
- t.Fatal("the run records no confirmation method, so nothing says how khaos established " +
- "the credential was defective before presenting it")
+ t.Fatal(
+ "the run records no confirmation method, so nothing says how khaos established " +
+ "the credential was defective before presenting it",
+ )
}
}
@@ -98,8 +143,20 @@ func TestOneAcceptedForgedCredentialIsAConclusiveFinding(t *testing.T) {
// and it must not read as a finding.
func TestAForgedCredentialRefusedThroughoutIsAPass(t *testing.T) {
observation := forgeryObservation(
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumToClaimClosed),
- window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumToClaimClosed),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumToClaimClosed,
+ ),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumToClaimClosed,
+ ),
probe.ExpectAccepted,
)
@@ -112,7 +169,9 @@ func TestAForgedCredentialRefusedThroughoutIsAPass(t *testing.T) {
}
if verdict.Defect {
- t.Fatal("a target that refused every forged credential was reported as defective")
+ t.Fatal(
+ "a target that refused every forged credential was reported as defective",
+ )
}
}
@@ -125,23 +184,44 @@ func TestATargetThatNeverTrustedKhaosProviderVoidsTheRun(t *testing.T) {
// Note the valid stream IS accepted: the target is serving, enforcing,
// and simply refusing khaos's issuer. That is exactly the case a naive
// baseline check passes.
- window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumToClaimClosed),
- window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumToClaimClosed),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumToClaimClosed,
+ ),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumToClaimClosed,
+ ),
probe.ExpectAccepted,
)
verdict := Judge(observation, idpPolarity)
if verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s (%s)", verdict.Epistemic, BaselineNotMet,
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "epistemic = %s, want %s (%s)",
+ verdict.Epistemic,
+ BaselineNotMet,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
if verdict.Conclusive {
- t.Fatal("a run that never established the target trusts khaos's provider was conclusive")
+ t.Fatal(
+ "a run that never established the target trusts khaos's provider was conclusive",
+ )
}
- if !strings.Contains(strings.Join(verdict.Reasons, "; "), "resolves keys from the issuer") {
+ if !strings.Contains(
+ strings.Join(verdict.Reasons, "; "),
+ "resolves keys from the issuer",
+ ) {
t.Fatalf("the refusal does not tell the operator what to check: %s",
strings.Join(verdict.Reasons, "; "))
}
@@ -152,19 +232,38 @@ func TestATargetThatNeverTrustedKhaosProviderVoidsTheRun(t *testing.T) {
// its acceptance during the fault proves nothing changed.
func TestATargetThatNeverCheckedTheForgedCredentialVoidsTheRun(t *testing.T) {
observation := forgeryObservation(
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumToClaimClosed),
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumToClaimClosed),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumToClaimClosed,
+ ),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumToClaimClosed,
+ ),
probe.ExpectRejected,
)
verdict := Judge(observation, idpPolarity)
if verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s (%s)", verdict.Epistemic, BaselineNotMet,
- strings.Join(verdict.Reasons, "; "))
- }
-
- if !strings.Contains(strings.Join(verdict.Reasons, "; "), "not checking the property") {
+ t.Fatalf(
+ "epistemic = %s, want %s (%s)",
+ verdict.Epistemic,
+ BaselineNotMet,
+ strings.Join(verdict.Reasons, "; "),
+ )
+ }
+
+ if !strings.Contains(
+ strings.Join(verdict.Reasons, "; "),
+ "not checking the property",
+ ) {
t.Fatalf("the refusal does not say what was never established: %s",
strings.Join(verdict.Reasons, "; "))
}
@@ -174,15 +273,39 @@ func TestATargetThatNeverCheckedTheForgedCredentialVoidsTheRun(t *testing.T) {
// the other's expectation. A guard that fired on both would void every run in
// the family.
func TestTheTwoForgedGuardsDoNotFireOnEachOthersExpectation(t *testing.T) {
- acceptedThroughout := window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumToClaimClosed)
- rejectedThroughout := window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumToClaimClosed)
+ acceptedThroughout := window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumToClaimClosed,
+ )
+ rejectedThroughout := window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumToClaimClosed,
+ )
- if _, unmet := baselineUnmet(acceptedThroughout, probe.ExpectAccepted, true); unmet {
- t.Error("ExpectAccepted voided a baseline where the forged stream WAS accepted")
+ if _, unmet := baselineUnmet(
+ acceptedThroughout,
+ probe.ExpectAccepted,
+ true,
+ ); unmet {
+ t.Error(
+ "ExpectAccepted voided a baseline where the forged stream WAS accepted",
+ )
}
- if _, unmet := baselineUnmet(rejectedThroughout, probe.ExpectRejected, true); unmet {
- t.Error("ExpectRejected voided a baseline where the forged stream WAS rejected")
+ if _, unmet := baselineUnmet(
+ rejectedThroughout,
+ probe.ExpectRejected,
+ true,
+ ); unmet {
+ t.Error(
+ "ExpectRejected voided a baseline where the forged stream WAS rejected",
+ )
}
}
@@ -194,7 +317,10 @@ func TestAnAbsentForgedStreamIsNotGuarded(t *testing.T) {
for _, expect := range []probe.Expectation{"", probe.ExpectAccepted, probe.ExpectRejected} {
if _, unmet := baselineUnmet(bare, expect, true); unmet {
- t.Errorf("a baseline with no forged stream was voided under expectation %q", expect)
+ t.Errorf(
+ "a baseline with no forged stream was voided under expectation %q",
+ expect,
+ )
}
}
}
@@ -204,8 +330,20 @@ func TestAnAbsentForgedStreamIsNotGuarded(t *testing.T) {
// other from a run where both were true.
func TestEveryStreamThatLeakedIsStated(t *testing.T) {
observation := forgeryObservation(
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumPaired),
- window(probe.Accepted, probe.Accepted, probe.Accepted, "", MinimumPaired),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumPaired,
+ ),
+ window(
+ probe.Accepted,
+ probe.Accepted,
+ probe.Accepted,
+ "",
+ MinimumPaired,
+ ),
probe.ExpectAccepted,
)
@@ -225,15 +363,31 @@ func TestEveryStreamThatLeakedIsStated(t *testing.T) {
// The idleness discriminator is for CACHING causes. A forged credential getting
// through is not a caching bug, so a forgery experiment must not spend a minute
// of the operator's run pausing traffic to diagnose one.
-func TestAForgedFindingAloneDoesNotAskForTheIdlenessDiscriminator(t *testing.T) {
+func TestAForgedFindingAloneDoesNotAskForTheIdlenessDiscriminator(
+ t *testing.T,
+) {
observation := forgeryObservation(
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumPaired),
- window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumPaired),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumPaired,
+ ),
+ window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumPaired,
+ ),
probe.ExpectAccepted,
)
if !Leaking(observation) {
- t.Fatal("a proven forged bypass did not register as a leak, so no cause would ever be diagnosed")
+ t.Fatal(
+ "a proven forged bypass did not register as a leak, so no cause would ever be diagnosed",
+ )
}
verdict := Judge(observation, idpPolarity)
@@ -241,7 +395,11 @@ func TestAForgedFindingAloneDoesNotAskForTheIdlenessDiscriminator(t *testing.T)
// Nothing resumed, because no forgery experiment sets IdleFor, so the cause
// stays honestly UNDIAGNOSED rather than being guessed.
if verdict.Cause != Undiagnosed {
- t.Fatalf("cause = %s, want %s on a run with no idleness phase", verdict.Cause, Undiagnosed)
+ t.Fatalf(
+ "cause = %s, want %s on a run with no idleness phase",
+ verdict.Cause,
+ Undiagnosed,
+ )
}
}
@@ -253,37 +411,62 @@ func TestAForgedFindingAloneDoesNotAskForTheIdlenessDiscriminator(t *testing.T)
// Measured against the range's forever-cache gateway: a second consecutive run
// could not establish a baseline, and nothing in the output said why.
func TestTheIdentityTierSaysWhyItsOwnCredentialWasRefused(t *testing.T) {
- refused := window(probe.Rejected, probe.Rejected, "", "", MinimumToClaimClosed)
+ refused := window(
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ )
minted, unmet := baselineUnmet(refused, "", true)
if !unmet {
- t.Fatal("a baseline where khaos's own credential was never accepted was not voided")
+ t.Fatal(
+ "a baseline where khaos's own credential was never accepted was not voided",
+ )
}
operator, unmet := baselineUnmet(refused, "", false)
if !unmet {
- t.Fatal("a baseline where the operator's credential was never accepted was not voided")
+ t.Fatal(
+ "a baseline where the operator's credential was never accepted was not voided",
+ )
}
if minted == operator {
- t.Fatal("the identity tier and the operator-supplied tier give the same refusal, so the " +
- "one case where the generic wording is misleading reads identically")
+ t.Fatal(
+ "the identity tier and the operator-supplied tier give the same refusal, so the " +
+ "one case where the generic wording is misleading reads identically",
+ )
}
for _, want := range []string{"key set", "fresh key set every run", "Restart the target"} {
if !strings.Contains(minted, want) {
- t.Errorf("the identity tier's refusal does not mention %q: %s", want, minted)
+ t.Errorf(
+ "the identity tier's refusal does not mention %q: %s",
+ want,
+ minted,
+ )
}
}
if strings.Contains(minted, "was not serving") {
- t.Errorf("the identity tier's refusal still claims the target was not serving: %s", minted)
+ t.Errorf(
+ "the identity tier's refusal still claims the target was not serving: %s",
+ minted,
+ )
}
}
// Recovery is three-valued, and "not observed" is the state that used to lie.
func TestRecoveryDistinguishesUnobservedFromRecovered(t *testing.T) {
- healthy := window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed)
+ healthy := window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ )
cases := []struct {
name string
@@ -292,7 +475,11 @@ func TestRecoveryDistinguishesUnobservedFromRecovered(t *testing.T) {
}{
{"healthy run of pairs", healthy, Recovered},
{"no evidence at all", probe.Window{}, Unobserved},
- {"measured and still broken", window(probe.Rejected, probe.Rejected, "", "", MinimumPaired), Degraded},
+ {
+ "measured and still broken",
+ window(probe.Rejected, probe.Rejected, "", "", MinimumPaired),
+ Degraded,
+ },
}
for _, each := range cases {
@@ -307,8 +494,12 @@ func TestRecoveryDistinguishesUnobservedFromRecovered(t *testing.T) {
verdict := Judge(observation, idpPolarity)
if verdict.Recovery != each.want {
- t.Fatalf("recovery = %q, want %q (%s)", verdict.Recovery, each.want,
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "recovery = %q, want %q (%s)",
+ verdict.Recovery,
+ each.want,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
})
}
@@ -316,7 +507,13 @@ func TestRecoveryDistinguishesUnobservedFromRecovered(t *testing.T) {
// An unobserved recovery must say so rather than pass silently.
func TestAnUnobservedRecoveryIsWarnedAboutRatherThanAssumed(t *testing.T) {
- healthy := window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed)
+ healthy := window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ )
verdict := Judge(Observation{
Baseline: healthy,
@@ -347,19 +544,43 @@ func TestAnUnobservedRecoveryIsWarnedAboutRatherThanAssumed(t *testing.T) {
// while every forged probe failed, and the run reported that the target refused
// a credential it was never successfully shown.
func TestARequiredForgedStreamWithNoDecisionsCannotReportHeld(t *testing.T) {
- baseline := window(probe.Accepted, probe.Rejected, probe.Accepted, "", MinimumToClaimClosed)
+ baseline := window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Accepted,
+ "",
+ MinimumToClaimClosed,
+ )
fault := probe.Window{}
for range MinimumToClaimClosed {
- fault.Record(probe.Outcome{Credential: probe.Valid, Disposition: probe.Accepted})
- fault.Record(probe.Outcome{Credential: probe.Invalid, Disposition: probe.Rejected})
- fault.Record(probe.Outcome{Credential: probe.Forged, Disposition: probe.ProbeFailed})
+ fault.Record(
+ probe.Outcome{Credential: probe.Valid, Disposition: probe.Accepted},
+ )
+ fault.Record(
+ probe.Outcome{
+ Credential: probe.Invalid,
+ Disposition: probe.Rejected,
+ },
+ )
+ fault.Record(
+ probe.Outcome{
+ Credential: probe.Forged,
+ Disposition: probe.ProbeFailed,
+ },
+ )
}
observation := Observation{
- Baseline: baseline,
- Fault: fault,
- Recovery: window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed),
+ Baseline: baseline,
+ Fault: fault,
+ Recovery: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ ),
FaultConfirmed: true,
ForgedBaseline: probe.ExpectAccepted,
}
@@ -367,8 +588,10 @@ func TestARequiredForgedStreamWithNoDecisionsCannotReportHeld(t *testing.T) {
verdict := Judge(observation, idpPolarity)
if verdict.Epistemic == Passed {
- t.Fatalf("a run where every forged probe failed reported a clean survival (%s)",
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "a run where every forged probe failed reported a clean survival (%s)",
+ strings.Join(verdict.Reasons, "; "),
+ )
}
if verdict.Epistemic != ProbeError {
@@ -377,7 +600,13 @@ func TestARequiredForgedStreamWithNoDecisionsCannotReportHeld(t *testing.T) {
// The control: the same run with real decisions on that stream judges
// normally, or this guard would have deleted the clean-result path.
- decided := window(probe.Accepted, probe.Rejected, probe.Rejected, "", MinimumToClaimClosed)
+ decided := window(
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ "",
+ MinimumToClaimClosed,
+ )
observation.Fault = decided
if verdict := Judge(observation, idpPolarity); verdict.Epistemic != Passed {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go
index a53d31d7..757aa63b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go
@@ -127,7 +127,12 @@ func revokeAt(authority, credential string) func(context.Context) error {
query.Set(revokeParam, credential)
endpoint.RawQuery = query.Encode()
- request, err := http.NewRequestWithContext(ctx, revokeMethod, endpoint.String(), nil)
+ request, err := http.NewRequestWithContext(
+ ctx,
+ revokeMethod,
+ endpoint.String(),
+ nil,
+ )
if err != nil {
return fmt.Errorf(errRevoke, authority, err)
}
@@ -140,7 +145,8 @@ func revokeAt(authority, credential string) func(context.Context) error {
}
defer func() { _ = response.Body.Close() }()
- if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
+ if response.StatusCode < http.StatusOK ||
+ response.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf(errRevokeStatus, authority, response.StatusCode)
}
@@ -150,16 +156,24 @@ func revokeAt(authority, credential string) func(context.Context) error {
func init() {
catalog[NameIDPOutage] = Definition{
- Name: NameIDPOutage,
- Family: FamilyIdentity,
- Summary: idpOutageSummary,
- Hypothesis: Hypothesis{Condition: outageGeneric, Response: idpOutageResponse},
- Polarity: idpOutagePolarity,
- FaultKind: inject.ProxyKind(proxy.Hang),
- Params: append(proxyParams(),
+ Name: NameIDPOutage,
+ Family: FamilyIdentity,
+ Summary: idpOutageSummary,
+ Hypothesis: Hypothesis{
+ Condition: outageGeneric,
+ Response: idpOutageResponse,
+ },
+ Polarity: idpOutagePolarity,
+ FaultKind: inject.ProxyKind(proxy.Hang),
+ Params: append(
+ proxyParams(),
Param{Name: ParamAuthority, Usage: usageAuthority, Required: true},
Param{Name: ParamRevocable, Usage: usageRevocable, Required: true},
- Param{Name: ParamIdleFor, Usage: usageIdleFor, Default: defaultIdleFor},
+ Param{
+ Name: ParamIdleFor,
+ Usage: usageIdleFor,
+ Default: defaultIdleFor,
+ },
),
Build: buildIDPOutage,
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idleness_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idleness_test.go
index a05401b3..45d00445 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idleness_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idleness_test.go
@@ -43,7 +43,11 @@ type cachingService struct {
}
func newCachingService(reArm, noExpiry bool) *cachingService {
- s := &cachingService{reArm: reArm, noExpiry: noExpiry, cache: map[string]time.Time{}}
+ s := &cachingService{
+ reArm: reArm,
+ noExpiry: noExpiry,
+ cache: map[string]time.Time{},
+ }
s.up.Store(true)
s.cache[leakedToken] = time.Now().Add(cacheTTL)
return s
@@ -115,12 +119,15 @@ func registerIdlenessExperiment(t *testing.T) {
t.Helper()
catalog[idleName] = Definition{
- Name: idleName,
- Family: FamilyNetwork,
- Summary: "a cached allow outliving the authority that could revoke it",
- Hypothesis: Hypothesis{Condition: outageGeneric, Response: outageResponse},
- Polarity: outagePolarity,
- FaultKind: "test-kind",
+ Name: idleName,
+ Family: FamilyNetwork,
+ Summary: "a cached allow outliving the authority that could revoke it",
+ Hypothesis: Hypothesis{
+ Condition: outageGeneric,
+ Response: outageResponse,
+ },
+ Polarity: outagePolarity,
+ FaultKind: "test-kind",
Params: []Param{
{Name: ParamTarget, Usage: usageTarget, Required: true},
{Name: ParamURL, Usage: usageURL, Required: true},
@@ -203,8 +210,16 @@ func TestTheIdlenessDiscriminatorSeparatesTwoCausesOfOneLeak(t *testing.T) {
svc *cachingService
cause Cause
}{
- {"a cache re-armed on every failed check", newCachingService(true, false), TTLExtension},
- {"a cache that outlasts the pause", newCachingService(false, true), StalePastPause},
+ {
+ "a cache re-armed on every failed check",
+ newCachingService(true, false),
+ TTLExtension,
+ },
+ {
+ "a cache that outlasts the pause",
+ newCachingService(false, true),
+ StalePastPause,
+ },
}
for _, tc := range cases {
@@ -212,20 +227,32 @@ func TestTheIdlenessDiscriminatorSeparatesTwoCausesOfOneLeak(t *testing.T) {
result := runIdleness(t, tc.svc, pause)
if result.Verdict.Direction != Permitted {
- t.Fatalf("direction = %s, want %s (%s)", result.Verdict.Direction, Permitted,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "direction = %s, want %s (%s)",
+ result.Verdict.Direction,
+ Permitted,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if result.Verdict.Cause != tc.cause {
- t.Fatalf("cause = %s, want %s. These two targets are identical under steady "+
- "traffic and need different fixes, so a verdict that cannot tell them apart "+
- "sends the operator after the wrong bug (%s)",
- result.Verdict.Cause, tc.cause, strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "cause = %s, want %s. These two targets are identical under steady "+
+ "traffic and need different fixes, so a verdict that cannot tell them apart "+
+ "sends the operator after the wrong bug (%s)",
+ result.Verdict.Cause,
+ tc.cause,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if result.Observation.IdleFor != pause {
- t.Fatalf("the run recorded a pause of %s, want %s; a finding whose pause is not "+
- "reported cannot be checked", result.Observation.IdleFor, pause)
+ t.Fatalf(
+ "the run recorded a pause of %s, want %s; a finding whose pause is not "+
+ "reported cannot be checked",
+ result.Observation.IdleFor,
+ pause,
+ )
}
})
}
@@ -261,24 +288,38 @@ func TestTheDiscriminatorDoesNotRunOnATargetThatHeld(t *testing.T) {
spec.IdleFor = 10 * time.Second
started := time.Now()
- result, err := Engine{Injector: &cachingInjector{svc: svc}}.Run(context.Background(), spec)
+ result, err := Engine{
+ Injector: &cachingInjector{svc: svc},
+ }.Run(
+ context.Background(),
+ spec,
+ )
took := time.Since(started)
if err != nil {
t.Fatalf("run: %v", err)
}
if took >= spec.IdleFor {
- t.Fatalf("the run took %s against a %s pause, so it paused traffic on a target with "+
- "nothing to diagnose", took, spec.IdleFor)
+ t.Fatalf(
+ "the run took %s against a %s pause, so it paused traffic on a target with "+
+ "nothing to diagnose",
+ took,
+ spec.IdleFor,
+ )
}
if result.Verdict.Cause != Undiagnosed {
- t.Fatalf("cause = %s, want %s on a run where the discriminator never ran",
- result.Verdict.Cause, Undiagnosed)
+ t.Fatalf(
+ "cause = %s, want %s on a run where the discriminator never ran",
+ result.Verdict.Cause,
+ Undiagnosed,
+ )
}
if result.Observation.Resumed.Paired() != 0 {
- t.Fatal("a resumed window was measured although the discriminator did not run")
+ t.Fatal(
+ "a resumed window was measured although the discriminator did not run",
+ )
}
}
@@ -292,8 +333,12 @@ func TestWithoutAPauseTheCauseIsUndiagnosedRatherThanGuessed(t *testing.T) {
}
if result.Verdict.Cause != Undiagnosed {
- t.Fatalf("cause = %s, want %s. Nothing ran that could tell the causes apart, and naming "+
- "one anyway is a finding khaos did not measure", result.Verdict.Cause, Undiagnosed)
+ t.Fatalf(
+ "cause = %s, want %s. Nothing ran that could tell the causes apart, and naming "+
+ "one anyway is a finding khaos did not measure",
+ result.Verdict.Cause,
+ Undiagnosed,
+ )
}
}
@@ -312,18 +357,43 @@ func maxDuration(a, b time.Duration) time.Duration {
// when its own window was too short to exclude that.
//
// The gate shipped with `--fault-for 8s --idle-for 14s`, which is that case.
-func TestTTLExtensionIsRefusedWhenTheSteadyWindowIsShorterThanThePause(t *testing.T) {
+func TestTTLExtensionIsRefusedWhenTheSteadyWindowIsShorterThanThePause(
+ t *testing.T,
+) {
lapsed := probe.Window{}
for range MinimumPaired {
- lapsed.Record(probe.Outcome{Credential: probe.Revoked, Disposition: probe.Rejected})
+ lapsed.Record(
+ probe.Outcome{
+ Credential: probe.Revoked,
+ Disposition: probe.Rejected,
+ },
+ )
}
- leaked := window(probe.Accepted, probe.Rejected, "", probe.Accepted, MinimumPaired)
+ leaked := window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ probe.Accepted,
+ MinimumPaired,
+ )
base := Observation{
- Baseline: window(probe.Accepted, probe.Rejected, "", probe.Accepted, MinimumPaired),
- Fault: leaked,
- Recovery: window(probe.Accepted, probe.Rejected, "", "", MinimumPaired),
+ Baseline: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ probe.Accepted,
+ MinimumPaired,
+ ),
+ Fault: leaked,
+ Recovery: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumPaired,
+ ),
Resumed: lapsed,
FaultConfirmed: true,
IdleFor: 14 * time.Second,
@@ -334,9 +404,12 @@ func TestTTLExtensionIsRefusedWhenTheSteadyWindowIsShorterThanThePause(t *testin
unsound.FaultFor = 8 * time.Second
if verdict := Judge(unsound, idpPolarity); verdict.Cause != LapsedOnPause {
- t.Fatalf("an 8s steady window against a 14s pause produced %s; a fixed lifetime between "+
- "those two durations explains it just as well (%s)",
- verdict.Cause, strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "an 8s steady window against a 14s pause produced %s; a fixed lifetime between "+
+ "those two durations explains it just as well (%s)",
+ verdict.Cause,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
// The control. The same observation with a steady window at least as long as
@@ -348,12 +421,21 @@ func TestTTLExtensionIsRefusedWhenTheSteadyWindowIsShorterThanThePause(t *testin
verdict := Judge(sound, idpPolarity)
if verdict.Cause != TTLExtension {
- t.Fatalf("a 14s steady window against a 14s pause produced %s, want %s (%s)",
- verdict.Cause, TTLExtension, strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "a 14s steady window against a 14s pause produced %s, want %s (%s)",
+ verdict.Cause,
+ TTLExtension,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
- if !strings.Contains(strings.Join(verdict.Reasons, "; "), "no fixed lifetime behaves that way") {
- t.Fatalf("the TTL-extension reason does not state why a fixed lifetime is excluded: %s",
- strings.Join(verdict.Reasons, "; "))
+ if !strings.Contains(
+ strings.Join(verdict.Reasons, "; "),
+ "no fixed lifetime behaves that way",
+ ) {
+ t.Fatalf(
+ "the TTL-extension reason does not state why a fixed lifetime is excluded: %s",
+ strings.Join(verdict.Reasons, "; "),
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go
index f36f4b15..fa44371c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go
@@ -90,15 +90,31 @@ func idpParams(extra ...Param) []Param {
{Name: ParamTarget, Usage: usageTarget, Required: true},
{Name: ParamURL, Usage: usageURL, Required: true},
{Name: ParamIssuer, Usage: usageIssuer, Required: true},
- {Name: ParamInvalidToken, Usage: usageInvalidToken, Default: DefaultInvalidToken},
+ {
+ Name: ParamInvalidToken,
+ Usage: usageInvalidToken,
+ Default: DefaultInvalidToken,
+ },
}, extra...)
}
-var keyFormParam = Param{Name: ParamKeyForm, Usage: usageKeyForm, Default: string(idp.SPKIPEM)}
+var keyFormParam = Param{
+ Name: ParamKeyForm,
+ Usage: usageKeyForm,
+ Default: string(idp.SPKIPEM),
+}
-var idpDelayParam = Param{Name: ParamDelay, Usage: usageIdPDelay, Default: defaultIdPDelay}
+var idpDelayParam = Param{
+ Name: ParamDelay,
+ Usage: usageIdPDelay,
+ Default: defaultIdPDelay,
+}
-var claimShiftParam = Param{Name: ParamDelay, Usage: usageClaimShift, Default: defaultClaimShift}
+var claimShiftParam = Param{
+ Name: ParamDelay,
+ Usage: usageClaimShift,
+ Default: defaultClaimShift,
+}
const (
// The two endpoints an identity experiment can fault, as they read in the
@@ -164,7 +180,11 @@ type streams struct {
// and an experiment whose valid stream froze a token would be unable to tell a
// target that stopped trusting the provider from one that never picked up a
// rotation.
-func idpPair(params *Params, provider *idp.Provider, wiring streams) (probe.Pair, error) {
+func idpPair(
+ params *Params,
+ provider *idp.Provider,
+ wiring streams,
+) (probe.Pair, error) {
url := params.Get(ParamURL)
mintValid := provider.HonestToken
@@ -238,7 +258,11 @@ func idpPair(params *Params, provider *idp.Provider, wiring streams) (probe.Pair
return pair, nil
}
-func forgedProbe(url string, provider *idp.Provider, wiring streams) (probe.Probe, error) {
+func forgedProbe(
+ url string,
+ provider *idp.Provider,
+ wiring streams,
+) (probe.Probe, error) {
options := probe.HTTPOptions{
Name: probeForgedName,
URL: url,
@@ -262,7 +286,9 @@ func forgedProbe(url string, provider *idp.Provider, wiring streams) (probe.Prob
// mintEvery adapts a provider mint to the probe's per-request signature. The
// context is unused because minting is local arithmetic with no I/O, and giving
// it one would suggest a cancellation point that does not exist.
-func mintEvery(mint func() (string, error)) func(context.Context) (string, error) {
+func mintEvery(
+ mint func() (string, error),
+) func(context.Context) (string, error) {
return func(context.Context) (string, error) {
return mint()
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier_test.go
index 0da0b536..691c56c8 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier_test.go
@@ -54,18 +54,28 @@ func TestEveryIdentityTrapHasExactlyOneExperiment(t *testing.T) {
switch len(named) {
case 0:
- t.Errorf("trap %s has no experiment, so khaos can produce it and no operator can ask for it", trap)
+ t.Errorf(
+ "trap %s has no experiment, so khaos can produce it and no operator can ask for it",
+ trap,
+ )
case 1:
default:
- t.Errorf("trap %s is claimed by %v; one trap is one experiment or `khaos catalog` describes the same fault twice",
- trap, named)
+ t.Errorf(
+ "trap %s is claimed by %v; one trap is one experiment or `khaos catalog` describes the same fault twice",
+ trap,
+ named,
+ )
}
delete(byTrap, trap)
}
for trap, named := range byTrap {
- t.Errorf("%v name the trap %s, which khaos's provider does not register", named, trap)
+ t.Errorf(
+ "%v name the trap %s, which khaos's provider does not register",
+ named,
+ trap,
+ )
}
}
@@ -80,11 +90,15 @@ func TestEveryIdentityExperimentBuildsFromTheRangeAnswers(t *testing.T) {
}
if spec.IdP == nil {
- t.Fatal("no provider was built, so the probes have nothing to mint from")
+ t.Fatal(
+ "no provider was built, so the probes have nothing to mint from",
+ )
}
if spec.IdPTrap == nil {
- t.Fatal("no trap was declared, so the run would stand up a provider and arm nothing")
+ t.Fatal(
+ "no trap was declared, so the run would stand up a provider and arm nothing",
+ )
}
// Every trap has to be armable as declared, with ONE stated
@@ -98,15 +112,20 @@ func TestEveryIdentityExperimentBuildsFromTheRangeAnswers(t *testing.T) {
if spec.IdPTrap.Kind == idp.Revoke {
if err == nil {
- t.Fatal("the revocation trap validated at build time, so it is carrying a credential " +
- "from before the probe that issues one has fired")
+ t.Fatal(
+ "the revocation trap validated at build time, so it is carrying a credential " +
+ "from before the probe that issues one has fired",
+ )
}
resolved := *spec.IdPTrap
resolved.Credential = spec.IdP.Revocable()
if err := resolved.Validate(); err != nil {
- t.Fatalf("the revocation trap is not armable even once a credential is resolved: %v", err)
+ t.Fatalf(
+ "the revocation trap is not armable even once a credential is resolved: %v",
+ err,
+ )
}
return
@@ -117,12 +136,19 @@ func TestEveryIdentityExperimentBuildsFromTheRangeAnswers(t *testing.T) {
}
if spec.Fault.Kind != inject.IdPKind(spec.IdPTrap.Kind) {
- t.Fatalf("the catalogued fault is %q and the trap is %q; the mutator would refuse its own experiment",
- spec.Fault.Kind, spec.IdPTrap.Kind)
+ t.Fatalf(
+ "the catalogued fault is %q and the trap is %q; the mutator would refuse its own experiment",
+ spec.Fault.Kind,
+ spec.IdPTrap.Kind,
+ )
}
if spec.Fault.Target != testTargetName {
- t.Fatalf("the fault names %q, want the target %q", spec.Fault.Target, testTargetName)
+ t.Fatalf(
+ "the fault names %q, want the target %q",
+ spec.Fault.Target,
+ testTargetName,
+ )
}
})
}
@@ -142,7 +168,11 @@ func TestEveryIdentityExperimentMintsUnderTheIssuerItWasGiven(t *testing.T) {
}
if got := spec.IdP.Issuer(); got != testIssuerURL {
- t.Fatalf("the provider issues as %q, want %q", got, testIssuerURL)
+ t.Fatalf(
+ "the provider issues as %q, want %q",
+ got,
+ testIssuerURL,
+ )
}
raw, err := spec.IdP.HonestToken()
@@ -156,7 +186,11 @@ func TestEveryIdentityExperimentMintsUnderTheIssuerItWasGiven(t *testing.T) {
}
if token.Claims.Issuer != testIssuerURL {
- t.Fatalf("the minted token says iss %q, want %q", token.Claims.Issuer, testIssuerURL)
+ t.Fatalf(
+ "the minted token says iss %q, want %q",
+ token.Claims.Issuer,
+ testIssuerURL,
+ )
}
})
}
@@ -211,15 +245,21 @@ func TestEachIdentityExperimentWiresTheStreamsItsFindingNeeds(t *testing.T) {
tier := identityTier()
if len(want) != len(tier) {
- t.Fatalf("this test states expectations for %d experiments and the identity tier has %d",
- len(want), len(tier))
+ t.Fatalf(
+ "this test states expectations for %d experiments and the identity tier has %d",
+ len(want),
+ len(tier),
+ )
}
for _, definition := range tier {
t.Run(definition.Name, func(t *testing.T) {
expected, stated := want[definition.Name]
if !stated {
- t.Fatalf("%s has no stated wiring, so nothing pins its design", definition.Name)
+ t.Fatalf(
+ "%s has no stated wiring, so nothing pins its design",
+ definition.Name,
+ )
}
spec, err := Build(definition.Name, identityInputs(), Timing{})
@@ -228,19 +268,35 @@ func TestEachIdentityExperimentWiresTheStreamsItsFindingNeeds(t *testing.T) {
}
if (spec.Probes.Forged != nil) != (expected.forged != "") {
- t.Errorf("forged stream present = %v, want %v", spec.Probes.Forged != nil, expected.forged != "")
+ t.Errorf(
+ "forged stream present = %v, want %v",
+ spec.Probes.Forged != nil,
+ expected.forged != "",
+ )
}
if spec.Probes.ForgedBaseline != expected.forged {
- t.Errorf("forged baseline expectation = %q, want %q", spec.Probes.ForgedBaseline, expected.forged)
+ t.Errorf(
+ "forged baseline expectation = %q, want %q",
+ spec.Probes.ForgedBaseline,
+ expected.forged,
+ )
}
if (spec.Probes.Revoked != nil) != expected.revoked {
- t.Errorf("revoked stream present = %v, want %v", spec.Probes.Revoked != nil, expected.revoked)
+ t.Errorf(
+ "revoked stream present = %v, want %v",
+ spec.Probes.Revoked != nil,
+ expected.revoked,
+ )
}
if (spec.IdleFor > 0) != expected.idleness {
- t.Errorf("idleness discriminator = %v, want %v", spec.IdleFor > 0, expected.idleness)
+ t.Errorf(
+ "idleness discriminator = %v, want %v",
+ spec.IdleFor > 0,
+ expected.idleness,
+ )
}
// Every stream that can carry a finding has to name what khaos did to
@@ -248,7 +304,9 @@ func TestEachIdentityExperimentWiresTheStreamsItsFindingNeeds(t *testing.T) {
// experiment identically.
if spec.Probes.Forged != nil || spec.Probes.Revoked != nil {
if spec.Defect == "" {
- t.Error("this experiment can produce a finding and does not say what khaos did to the credential")
+ t.Error(
+ "this experiment can produce a finding and does not say what khaos did to the credential",
+ )
}
}
})
@@ -280,7 +338,10 @@ func TestTheForgeryStreamsMintPerSampleAndTheFixedOnesDoNot(t *testing.T) {
// Describe is the only thing a probe exposes about how it gets its
// credential, and it says so explicitly for exactly this reason.
- perSample := strings.Contains(spec.Probes.Forged.Describe(), "minted per request")
+ perSample := strings.Contains(
+ spec.Probes.Forged.Describe(),
+ "minted per request",
+ )
if perSample != want {
t.Errorf("%s mints per sample = %v, want %v (%s)",
@@ -326,22 +387,31 @@ func TestEachFamilysValidControlTravelsThePathItNeedsTo(t *testing.T) {
if opaqueControl[definition.Name] {
if perSample {
- t.Errorf("%s faults the introspection endpoint and its valid control is minted "+
- "per sample; a JWT control is validated locally and never reaches the fault: %s",
- definition.Name, describe)
+ t.Errorf(
+ "%s faults the introspection endpoint and its valid control is minted "+
+ "per sample; a JWT control is validated locally and never reaches the fault: %s",
+ definition.Name,
+ describe,
+ )
}
seenOpaque = true
continue
}
if !perSample {
- t.Errorf("%s freezes its valid credential: %s", definition.Name, describe)
+ t.Errorf(
+ "%s freezes its valid credential: %s",
+ definition.Name,
+ describe,
+ )
}
seenMinted = true
}
if !seenOpaque || !seenMinted {
- t.Fatal("every experiment landed in one bucket, so this test cannot tell the two apart")
+ t.Fatal(
+ "every experiment landed in one bucket, so this test cannot tell the two apart",
+ )
}
}
@@ -365,16 +435,23 @@ func TestTheRolloverControlIsAJWTUnderAKeyThatIsNeverRotated(t *testing.T) {
control, err := idp.Parse(raw)
if err != nil {
- t.Fatalf("the control is not a JWT, so a JWT-only verifier cannot baseline: %v", err)
+ t.Fatalf(
+ "the control is not a JWT, so a JWT-only verifier cannot baseline: %v",
+ err,
+ )
}
if control.Header.Kid == spec.IdP.SigningKid() {
- t.Fatal("the control is signed by the CURRENT signing key, so after the rotation it becomes " +
- "the new-key traffic that evicts the retired key")
+ t.Fatal(
+ "the control is signed by the CURRENT signing key, so after the rotation it becomes " +
+ "the new-key traffic that evicts the retired key",
+ )
}
if !spec.IdP.PublishedSet().Has(control.Header.Kid) {
- t.Fatal("the control's key is not published, so it cannot be resolved without a refetch")
+ t.Fatal(
+ "the control's key is not published, so it cannot be resolved without a refetch",
+ )
}
// And it survives the rotation still published and still not the signing key,
@@ -396,7 +473,9 @@ func TestTheRolloverControlIsAJWTUnderAKeyThatIsNeverRotated(t *testing.T) {
// only thing in the whole catalogue that makes the directional axis anything but
// decoration. If it ever stops treating DENIED as a defect, nothing else
// exercises that branch.
-func TestTheRotationExperimentIsTheOnlyOneWhereRefusingIsTheDefect(t *testing.T) {
+func TestTheRotationExperimentIsTheOnlyOneWhereRefusingIsTheDefect(
+ t *testing.T,
+) {
inverted := []string{}
for _, definition := range Catalog() {
@@ -406,8 +485,11 @@ func TestTheRotationExperimentIsTheOnlyOneWhereRefusingIsTheDefect(t *testing.T)
}
if !slices.Equal(inverted, []string{NameKeyRotation}) {
- t.Fatalf("the experiments treating DENIED as a defect are %v, want exactly [%s]",
- inverted, NameKeyRotation)
+ t.Fatalf(
+ "the experiments treating DENIED as a defect are %v, want exactly [%s]",
+ inverted,
+ NameKeyRotation,
+ )
}
}
@@ -422,8 +504,11 @@ func TestTheRotationExperimentIsTheOnlyOneWhereRefusingIsTheDefect(t *testing.T)
func TestEveryExperimentTreatsPermittedAsADefect(t *testing.T) {
for _, definition := range Catalog() {
if !definition.Polarity.IsDefect(Permitted) {
- t.Errorf("%s does not treat PERMITTED as a defect, so a target that failed open "+
- "would be reported as acceptable and exit 0", definition.Name)
+ t.Errorf(
+ "%s does not treat PERMITTED as a defect, so a target that failed open "+
+ "would be reported as acceptable and exit 0",
+ definition.Name,
+ )
}
if len(definition.Polarity.Defects) == 0 {
@@ -431,7 +516,10 @@ func TestEveryExperimentTreatsPermittedAsADefect(t *testing.T) {
}
if definition.Polarity.Rationale == "" {
- t.Errorf("%s declares a polarity with no rationale", definition.Name)
+ t.Errorf(
+ "%s declares a polarity with no rationale",
+ definition.Name,
+ )
}
}
}
@@ -460,7 +548,11 @@ func TestEveryAdvertisedKeyFormBuilds(t *testing.T) {
inputs[ParamKeyForm] = form
if _, err := Build(NameAlgConfusion, inputs, Timing{}); err != nil {
- t.Errorf("key form %q is advertised and does not build: %v", form, err)
+ t.Errorf(
+ "key form %q is advertised and does not build: %v",
+ form,
+ err,
+ )
}
}
}
@@ -485,13 +577,22 @@ func TestOnlyTheEndpointFaultsDeclareAConsultedGuard(t *testing.T) {
expected := want[definition.Name]
if spec.ConsultedWhat != expected {
- t.Errorf("%s declares the guard %q, want %q", definition.Name, spec.ConsultedWhat, expected)
+ t.Errorf(
+ "%s declares the guard %q, want %q",
+ definition.Name,
+ spec.ConsultedWhat,
+ expected,
+ )
}
if (spec.Consulted != nil) != (expected != "") {
- t.Errorf("%s has a counter = %v and a declared endpoint = %v; a declared endpoint with "+
- "no counter is a guard that can never fire",
- definition.Name, spec.Consulted != nil, expected != "")
+ t.Errorf(
+ "%s has a counter = %v and a declared endpoint = %v; a declared endpoint with "+
+ "no counter is a guard that can never fire",
+ definition.Name,
+ spec.Consulted != nil,
+ expected != "",
+ )
}
}
}
@@ -501,7 +602,13 @@ func TestOnlyTheEndpointFaultsDeclareAConsultedGuard(t *testing.T) {
// and its fault window looks identical — `passed / HELD`, conclusive, over a
// fault that never reached it.
func TestATargetThatNeverUsedTheFaultedEndpointVoidsTheRun(t *testing.T) {
- healthy := window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed)
+ healthy := window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ )
observation := Observation{
Baseline: healthy,
@@ -516,12 +623,22 @@ func TestATargetThatNeverUsedTheFaultedEndpointVoidsTheRun(t *testing.T) {
verdict := Judge(observation, idpPolarity)
if verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s (%s)", verdict.Epistemic, BaselineNotMet,
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "epistemic = %s, want %s (%s)",
+ verdict.Epistemic,
+ BaselineNotMet,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
- if !strings.Contains(strings.Join(verdict.Reasons, "; "), ConsultsIntrospection) {
- t.Fatalf("the refusal does not name the endpoint: %s", strings.Join(verdict.Reasons, "; "))
+ if !strings.Contains(
+ strings.Join(verdict.Reasons, "; "),
+ ConsultsIntrospection,
+ ) {
+ t.Fatalf(
+ "the refusal does not name the endpoint: %s",
+ strings.Join(verdict.Reasons, "; "),
+ )
}
// The control: the same run where the target DID use the endpoint is judged
@@ -538,7 +655,13 @@ func TestATargetThatNeverUsedTheFaultedEndpointVoidsTheRun(t *testing.T) {
// An experiment that declares no endpoint must be unaffected, or adding the
// guard would have voided the fourteen experiments that fault a credential.
func TestAnExperimentWithNoDeclaredEndpointIsNotGuarded(t *testing.T) {
- healthy := window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed)
+ healthy := window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ )
observation := Observation{
Baseline: healthy,
@@ -571,13 +694,23 @@ func TestOnlyTheExperimentsThatMeasureLessCarryAHeldCaveat(t *testing.T) {
fragment, expected := caveated[definition.Name]
if (spec.HeldCaveat != "") != expected {
- t.Errorf("%s carries a HELD caveat = %v, want %v (%q)",
- definition.Name, spec.HeldCaveat != "", expected, spec.HeldCaveat)
+ t.Errorf(
+ "%s carries a HELD caveat = %v, want %v (%q)",
+ definition.Name,
+ spec.HeldCaveat != "",
+ expected,
+ spec.HeldCaveat,
+ )
continue
}
if expected && !strings.Contains(spec.HeldCaveat, fragment) {
- t.Errorf("%s's caveat does not mention %q: %s", definition.Name, fragment, spec.HeldCaveat)
+ t.Errorf(
+ "%s's caveat does not mention %q: %s",
+ definition.Name,
+ fragment,
+ spec.HeldCaveat,
+ )
}
}
}
@@ -587,9 +720,27 @@ func TestTheHeldCaveatIsStatedOnlyWhenTheTargetHeld(t *testing.T) {
const caveat = "this run tried one of four serializations"
held := Observation{
- Baseline: window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed),
- Fault: window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed),
- Recovery: window(probe.Accepted, probe.Rejected, "", "", MinimumToClaimClosed),
+ Baseline: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ ),
+ Fault: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ ),
+ Recovery: window(
+ probe.Accepted,
+ probe.Rejected,
+ "",
+ "",
+ MinimumToClaimClosed,
+ ),
FaultConfirmed: true,
HeldCaveat: caveat,
}
@@ -601,8 +752,11 @@ func TestTheHeldCaveatIsStatedOnlyWhenTheTargetHeld(t *testing.T) {
}
if !strings.Contains(strings.Join(verdict.Reasons, "; "), caveat) {
- t.Fatalf("a HELD verdict did not state its caveat, so khaos claims it ruled out more than "+
- "it tried: %s", strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "a HELD verdict did not state its caveat, so khaos claims it ruled out more than "+
+ "it tried: %s",
+ strings.Join(verdict.Reasons, "; "),
+ )
}
// A run that found something does not need the caveat: it found the thing
@@ -610,8 +764,16 @@ func TestTheHeldCaveatIsStatedOnlyWhenTheTargetHeld(t *testing.T) {
leaked := held
leaked.Fault = window(probe.Accepted, probe.Accepted, "", "", MinimumPaired)
- if found := Judge(leaked, idpPolarity); strings.Contains(strings.Join(found.Reasons, "; "), caveat) {
- t.Fatalf("a run that found a bypass still warned that it might have missed one: %s",
- strings.Join(found.Reasons, "; "))
+ if found := Judge(
+ leaked,
+ idpPolarity,
+ ); strings.Contains(
+ strings.Join(found.Reasons, "; "),
+ caveat,
+ ) {
+ t.Fatalf(
+ "a run that found a bypass still warned that it might have missed one: %s",
+ strings.Join(found.Reasons, "; "),
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/integration_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/integration_test.go
index 67a99e95..8450e39c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/integration_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/integration_test.go
@@ -8,11 +8,11 @@ import (
"net/http"
"net/http/httptest"
"strings"
-
- "github.com/CarterPerez-dev/khaos/internal/probe"
"sync/atomic"
"testing"
"time"
+
+ "github.com/CarterPerez-dev/khaos/internal/probe"
)
const (
@@ -110,17 +110,27 @@ func TestAControlThatFailsClosedIsReportedAsDenied(t *testing.T) {
result := runAgainst(t, &service{failOpen: false})
if result.Verdict.Direction != Denied {
- t.Fatalf("direction = %s, want %s (%s)", result.Verdict.Direction, Denied,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "direction = %s, want %s (%s)",
+ result.Verdict.Direction,
+ Denied,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if result.Verdict.Defect {
- t.Fatal("failing closed was flagged as a defect for a control whose declared defect is failing open")
+ t.Fatal(
+ "failing closed was flagged as a defect for a control whose declared defect is failing open",
+ )
}
if result.Verdict.Epistemic != Deviated {
- t.Fatalf("epistemic = %s, want %s; refusing legitimate traffic is a deviation even though "+
- "it is the safe direction", result.Verdict.Epistemic, Deviated)
+ t.Fatalf(
+ "epistemic = %s, want %s; refusing legitimate traffic is a deviation even though "+
+ "it is the safe direction",
+ result.Verdict.Epistemic,
+ Deviated,
+ )
}
}
@@ -128,13 +138,19 @@ func TestAControlThatFailsOpenIsCaughtAndFlaggedADefect(t *testing.T) {
result := runAgainst(t, &service{failOpen: true})
if result.Verdict.Direction != Permitted {
- t.Fatalf("direction = %s, want %s (%s)", result.Verdict.Direction, Permitted,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "direction = %s, want %s (%s)",
+ result.Verdict.Direction,
+ Permitted,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if !result.Verdict.Defect {
- t.Fatal("a control that started honouring a credential it had been rejecting was not " +
- "flagged as a defect")
+ t.Fatal(
+ "a control that started honouring a credential it had been rejecting was not " +
+ "flagged as a defect",
+ )
}
if !result.Verdict.Conclusive {
@@ -166,9 +182,11 @@ func TestTheProbeReadsTheBodyAndClassifiesByStatus(t *testing.T) {
for _, tc := range cases {
t.Run(http.StatusText(tc.status), func(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.WriteHeader(tc.status)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(tc.status)
+ }),
+ )
defer server.Close()
spec, err := Build(NameDependencyOutage, map[string]string{
@@ -182,11 +200,20 @@ func TestTheProbeReadsTheBodyAndClassifiesByStatus(t *testing.T) {
outcome := spec.Probes.Valid.Run(context.Background())
if outcome.Disposition.String() != tc.want {
- t.Fatalf("status %d classified as %s, want %s", tc.status, outcome.Disposition, tc.want)
+ t.Fatalf(
+ "status %d classified as %s, want %s",
+ tc.status,
+ outcome.Disposition,
+ tc.want,
+ )
}
if outcome.Status != tc.status {
- t.Fatalf("recorded status %d, want %d", outcome.Status, tc.status)
+ t.Fatalf(
+ "recorded status %d, want %d",
+ outcome.Status,
+ tc.status,
+ )
}
})
}
@@ -205,19 +232,27 @@ func TestAnUnreachableEndpointIsNotMistakenForARejection(t *testing.T) {
outcome := spec.Probes.Invalid.Run(context.Background())
if outcome.Disposition != probe.Unavailable {
- t.Fatalf("a connection failure was classified as %s; reading it as a rejection would "+
- "make an outage look like a control doing its job", outcome.Disposition)
+ t.Fatalf(
+ "a connection failure was classified as %s; reading it as a rejection would "+
+ "make an outage look like a control doing its job",
+ outcome.Disposition,
+ )
}
}
func TestARedirectingGatewayIsNamedNotBlamed(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if strings.TrimPrefix(r.Header.Get("Authorization"), bearer) != goodToken {
- http.Redirect(w, r, "/login", http.StatusFound)
- return
- }
- w.WriteHeader(http.StatusOK)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.TrimPrefix(
+ r.Header.Get("Authorization"),
+ bearer,
+ ) != goodToken {
+ http.Redirect(w, r, "/login", http.StatusFound)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ }),
+ )
defer server.Close()
spec, err := Build(NameDependencyOutage, map[string]string{
@@ -240,13 +275,20 @@ func TestARedirectingGatewayIsNamedNotBlamed(t *testing.T) {
}
if result.Verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s", result.Verdict.Epistemic, BaselineNotMet)
+ t.Fatalf(
+ "epistemic = %s, want %s",
+ result.Verdict.Epistemic,
+ BaselineNotMet,
+ )
}
joined := strings.Join(result.Verdict.Reasons, " ")
if !strings.Contains(joined, "redirect") {
- t.Fatalf("khaos refused to run against a redirecting gateway without naming the redirect "+
- "as the cause: %q", joined)
+ t.Fatalf(
+ "khaos refused to run against a redirecting gateway without naming the redirect "+
+ "as the cause: %q",
+ joined,
+ )
}
if !strings.Contains(joined, "--url") {
@@ -256,12 +298,20 @@ func TestARedirectingGatewayIsNamedNotBlamed(t *testing.T) {
func TestABaselineBlipDoesNotFabricateABypass(t *testing.T) {
baseline := healthyBaseline()
- baseline.Invalid = stream(probe.Invalid,
- probe.Rejected, probe.Accepted, probe.Rejected, probe.Rejected, probe.Rejected)
+ baseline.Invalid = stream(
+ probe.Invalid,
+ probe.Rejected,
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ probe.Rejected,
+ )
clean := probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
}
verdict := Judge(Observation{
@@ -272,8 +322,10 @@ func TestABaselineBlipDoesNotFabricateABypass(t *testing.T) {
}, authPolarity)
if verdict.Direction == Permitted {
- t.Fatal("one flaky acceptance during the BASELINE was reported as a credential being " +
- "honoured during the fault; the fault window was spotless")
+ t.Fatal(
+ "one flaky acceptance during the BASELINE was reported as a credential being " +
+ "honoured during the fault; the fault window was spotless",
+ )
}
}
@@ -291,9 +343,12 @@ func TestAProvenBypassIsReportedEvenOnThinEvidence(t *testing.T) {
}, authPolarity)
if verdict.Direction != Permitted {
- t.Fatalf("direction = %s; a credential the target had already refused being honoured even "+
- "once is PROOF of a bypass, and burying it as thin evidence loses the finding "+
- "khaos exists to produce", verdict.Direction)
+ t.Fatalf(
+ "direction = %s; a credential the target had already refused being honoured even "+
+ "once is PROOF of a bypass, and burying it as thin evidence loses the finding "+
+ "khaos exists to produce",
+ verdict.Direction,
+ )
}
if !verdict.Defect {
@@ -306,8 +361,12 @@ func TestACleanRunOnThinEvidenceIsNotConclusive(t *testing.T) {
FaultConfirmed: true,
Baseline: healthyBaseline(),
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}, authPolarity)
@@ -317,7 +376,11 @@ func TestACleanRunOnThinEvidenceIsNotConclusive(t *testing.T) {
}
if verdict.Conclusive {
- t.Fatalf("a clean result on %d samples was called conclusive; the absence of a bypass "+
- "needs a sample-size argument that %d does not supply", MinimumPaired, MinimumPaired)
+ t.Fatalf(
+ "a clean result on %d samples was called conclusive; the absence of a bypass "+
+ "needs a sample-size argument that %d does not supply",
+ MinimumPaired,
+ MinimumPaired,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go
index b7060f5e..c04a9992 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go
@@ -77,7 +77,11 @@ func proxyParams(extra ...Param) []Param {
{Name: ParamToken, Usage: usageToken, Required: true},
{Name: ParamProxyListen, Usage: usageProxyListen, Required: true},
{Name: ParamProxyUpstream, Usage: usageProxyUpstream, Required: true},
- {Name: ParamInvalidToken, Usage: usageInvalidToken, Default: DefaultInvalidToken},
+ {
+ Name: ParamInvalidToken,
+ Usage: usageInvalidToken,
+ Default: DefaultInvalidToken,
+ },
}, extra...)
}
@@ -86,13 +90,24 @@ func proxyEndpoint(params *Params) (string, string) {
return params.Get(ParamProxyListen), params.Get(ParamProxyUpstream)
}
-var delayParam = Param{Name: ParamDelay, Usage: usageDelay, Default: defaultDelay}
+var delayParam = Param{
+ Name: ParamDelay,
+ Usage: usageDelay,
+ Default: defaultDelay,
+}
-var bytesParam = Param{Name: ParamBytes, Usage: usageBytes, Default: defaultBytes}
+var bytesParam = Param{
+ Name: ParamBytes,
+ Usage: usageBytes,
+ Default: defaultBytes,
+}
// plainProxyShape covers the three faults that carry no magnitude. The condition
// is resolved against the real target so the hypothesis names what was broken.
-func plainProxyShape(kind proxy.Kind, condition string) func(*Params) (Shape, error) {
+func plainProxyShape(
+ kind proxy.Kind,
+ condition string,
+) func(*Params) (Shape, error) {
return func(params *Params) (Shape, error) {
target := params.Get(ParamTarget)
@@ -109,7 +124,10 @@ func plainProxyShape(kind proxy.Kind, condition string) func(*Params) (Shape, er
}
}
-func delayedProxyShape(kind proxy.Kind, condition string) func(*Params) (Shape, error) {
+func delayedProxyShape(
+ kind proxy.Kind,
+ condition string,
+) func(*Params) (Shape, error) {
return func(params *Params) (Shape, error) {
target := params.Get(ParamTarget)
@@ -151,7 +169,11 @@ func buildDependencyPartial(params *Params) (Shape, error) {
}, nil
}
-func proxyDefinition(name, summary, condition string, kind proxy.Kind, extra ...Param) Definition {
+func proxyDefinition(
+ name, summary, condition string,
+ kind proxy.Kind,
+ extra ...Param,
+) Definition {
build := plainProxyShape(kind, condition)
switch kind {
@@ -159,17 +181,22 @@ func proxyDefinition(name, summary, condition string, kind proxy.Kind, extra ...
build = delayedProxyShape(kind, condition)
case proxy.Partial:
build = buildDependencyPartial
+ default:
+ // Hang, Reset and EOF take no parameters, so the plain shape stands.
}
return Definition{
- Name: name,
- Family: FamilyNetwork,
- Summary: summary,
- Hypothesis: Hypothesis{Condition: outageGeneric, Response: proxyResponse},
- Polarity: proxyPolarity,
- FaultKind: inject.ProxyKind(kind),
- Params: proxyParams(extra...),
- Build: build,
+ Name: name,
+ Family: FamilyNetwork,
+ Summary: summary,
+ Hypothesis: Hypothesis{
+ Condition: outageGeneric,
+ Response: proxyResponse,
+ },
+ Polarity: proxyPolarity,
+ FaultKind: inject.ProxyKind(kind),
+ Params: proxyParams(extra...),
+ Build: build,
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go
index f2d20e95..760d0fd4 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go
@@ -27,7 +27,9 @@ const (
errBelowFloor = "--%s was given as %s, and khaos needs at least %s: %s"
)
-var ErrUndeclaredParam = errors.New("that is not a parameter of this experiment")
+var ErrUndeclaredParam = errors.New(
+ "that is not a parameter of this experiment",
+)
// Param declares one input an experiment needs. The declaration is the single
// place the CLI registers flags from, the range fills defaults into, and Bind
@@ -62,7 +64,12 @@ func Bind(declared []Param, supplied map[string]string) (*Params, error) {
if len(names) == 0 {
return nil, fmt.Errorf(errNoParams, ErrUndeclaredParam, name)
}
- return nil, fmt.Errorf(errUndeclared, ErrUndeclaredParam, name, strings.Join(names, nameSep))
+ return nil, fmt.Errorf(
+ errUndeclared,
+ ErrUndeclaredParam,
+ name,
+ strings.Join(names, nameSep),
+ )
}
bound := &Params{
@@ -158,7 +165,11 @@ func (p *Params) Duration(name string) (time.Duration, error) {
//
// The refusal names the floor AND why it exists, because an operator's first
// instinct on seeing it will be that khaos is being fussy about a magnitude.
-func (p *Params) AtLeast(name string, floor time.Duration, because string) (time.Duration, error) {
+func (p *Params) AtLeast(
+ name string,
+ floor time.Duration,
+ because string,
+) (time.Duration, error) {
value, err := p.Duration(name)
if err != nil {
return 0, err
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params_test.go
index c816bf63..80305cb3 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params_test.go
@@ -45,11 +45,17 @@ func TestBindRejectsAParameterTheExperimentDoesNotDeclare(t *testing.T) {
_, err := Bind(declared, map[string]string{ParamURL: "u", strayName: "v"})
if !errors.Is(err, ErrUndeclaredParam) {
- t.Fatalf("err = %v, want ErrUndeclaredParam; an input nothing will read must not be silently accepted", err)
+ t.Fatalf(
+ "err = %v, want ErrUndeclaredParam; an input nothing will read must not be silently accepted",
+ err,
+ )
}
if !strings.Contains(err.Error(), ParamURL) {
- t.Fatalf("the refusal did not name what this experiment does accept: %v", err)
+ t.Fatalf(
+ "the refusal did not name what this experiment does accept: %v",
+ err,
+ )
}
}
@@ -58,18 +64,32 @@ func TestBindRejectsAMissingRequiredParameterAndNamesTheFix(t *testing.T) {
_, err := Bind(declared, nil)
if err == nil {
- t.Fatal("a missing required parameter was accepted, so the experiment would run against nothing")
+ t.Fatal(
+ "a missing required parameter was accepted, so the experiment would run against nothing",
+ )
}
for _, want := range []string{flagSpelling(ParamTarget), usageTarget} {
if !strings.Contains(err.Error(), want) {
- t.Fatalf("the refusal did not name %q, so it does not reach the operator as a fix: %v", want, err)
+ t.Fatalf(
+ "the refusal did not name %q, so it does not reach the operator as a fix: %v",
+ want,
+ err,
+ )
}
}
}
-func TestBindAppliesADeclaredDefaultAndAnOperatorValueOverridesIt(t *testing.T) {
- declared := []Param{{Name: ParamInvalidToken, Usage: usageInvalidToken, Default: DefaultInvalidToken}}
+func TestBindAppliesADeclaredDefaultAndAnOperatorValueOverridesIt(
+ t *testing.T,
+) {
+ declared := []Param{
+ {
+ Name: ParamInvalidToken,
+ Usage: usageInvalidToken,
+ Default: DefaultInvalidToken,
+ },
+ }
bound, err := Bind(declared, nil)
if err != nil {
@@ -77,7 +97,11 @@ func TestBindAppliesADeclaredDefaultAndAnOperatorValueOverridesIt(t *testing.T)
}
if got := bound.Get(ParamInvalidToken); got != DefaultInvalidToken {
- t.Fatalf("default not applied: got %q, want %q", got, DefaultInvalidToken)
+ t.Fatalf(
+ "default not applied: got %q, want %q",
+ got,
+ DefaultInvalidToken,
+ )
}
bound, err = Bind(declared, map[string]string{ParamInvalidToken: "mine"})
@@ -93,10 +117,15 @@ func TestBindAppliesADeclaredDefaultAndAnOperatorValueOverridesIt(t *testing.T)
// A parameter with a default is never missing, so declaring it Required as well
// would make the Required check untestable for it. This pins the distinction.
func TestADefaultSatisfiesARequiredParameter(t *testing.T) {
- declared := []Param{{Name: ParamToken, Usage: usageToken, Required: true, Default: "d"}}
+ declared := []Param{
+ {Name: ParamToken, Usage: usageToken, Required: true, Default: "d"},
+ }
if _, err := Bind(declared, nil); err != nil {
- t.Fatalf("a required parameter with a default was reported missing: %v", err)
+ t.Fatalf(
+ "a required parameter with a default was reported missing: %v",
+ err,
+ )
}
}
@@ -110,9 +139,13 @@ func TestBuildRejectsABuilderThatReadsAnUndeclaredParameter(t *testing.T) {
Name: name,
Family: FamilyNetwork,
FaultKind: "test-kind",
- Params: []Param{{Name: ParamTarget, Usage: usageTarget, Required: true}},
+ Params: []Param{
+ {Name: ParamTarget, Usage: usageTarget, Required: true},
+ },
Build: func(params *Params) (Shape, error) {
- return Shape{Target: params.Get(ParamTarget) + params.Get(strayName)}, nil
+ return Shape{
+ Target: params.Get(ParamTarget) + params.Get(strayName),
+ }, nil
},
}
t.Cleanup(func() { delete(catalog, name) })
@@ -151,12 +184,19 @@ func TestEveryDeclaredParameterIsReadByItsBuilder(t *testing.T) {
}
if unread := bound.unread(); len(unread) > 0 {
- t.Fatalf("%s declares %v but never reads them, so those flags do nothing",
- definition.Name, unread)
+ t.Fatalf(
+ "%s declares %v but never reads them, so those flags do nothing",
+ definition.Name,
+ unread,
+ )
}
if stray := bound.strayReads(); len(stray) > 0 {
- t.Fatalf("%s reads %v without declaring them", definition.Name, stray)
+ t.Fatalf(
+ "%s reads %v without declaring them",
+ definition.Name,
+ stray,
+ )
}
})
}
@@ -187,27 +227,53 @@ func TestBuildTakesEveryIdentityFieldFromTheDeclaration(t *testing.T) {
t.Fatalf("family = %q, want %q", spec.Family, definition.Family)
}
if spec.Summary != definition.Summary {
- t.Fatalf("summary = %q, want %q", spec.Summary, definition.Summary)
+ t.Fatalf(
+ "summary = %q, want %q",
+ spec.Summary,
+ definition.Summary,
+ )
}
- if !slices.Equal(spec.Polarity.Defects, definition.Polarity.Defects) ||
+ if !slices.Equal(
+ spec.Polarity.Defects,
+ definition.Polarity.Defects,
+ ) ||
spec.Polarity.Rationale != definition.Polarity.Rationale {
- t.Fatalf("polarity = %+v, want %+v", spec.Polarity, definition.Polarity)
+ t.Fatalf(
+ "polarity = %+v, want %+v",
+ spec.Polarity,
+ definition.Polarity,
+ )
}
if spec.Fault.Target != sentinelPrefix+ParamTarget {
- t.Fatalf("fault target = %q, want %q; this is the one value that decides WHICH "+
- "container gets faulted and nothing else asserted it",
- spec.Fault.Target, sentinelPrefix+ParamTarget)
+ t.Fatalf(
+ "fault target = %q, want %q; this is the one value that decides WHICH "+
+ "container gets faulted and nothing else asserted it",
+ spec.Fault.Target,
+ sentinelPrefix+ParamTarget,
+ )
}
if spec.Fault.Kind != definition.FaultKind {
- t.Fatalf("fault kind = %q, want %q; `khaos catalog` would be advertising a "+
- "different fault than `khaos run` applies", spec.Fault.Kind, definition.FaultKind)
+ t.Fatalf(
+ "fault kind = %q, want %q; `khaos catalog` would be advertising a "+
+ "different fault than `khaos run` applies",
+ spec.Fault.Kind,
+ definition.FaultKind,
+ )
}
if spec.Hypothesis.Response != definition.Hypothesis.Response {
- t.Fatalf("response = %q, want %q", spec.Hypothesis.Response, definition.Hypothesis.Response)
+ t.Fatalf(
+ "response = %q, want %q",
+ spec.Hypothesis.Response,
+ definition.Hypothesis.Response,
+ )
}
if spec.Timing != timing {
- t.Fatalf("timing = %+v, want %+v; a builder that forgets to carry timing "+
- "silently ignores every timing flag", spec.Timing, timing)
+ t.Fatalf(
+ "timing = %+v, want %+v; a builder that forgets to carry timing "+
+ "silently ignores every timing flag",
+ spec.Timing,
+ timing,
+ )
}
if !spec.Probes.Complete() {
t.Fatal("the built experiment has no probe pair")
@@ -231,17 +297,24 @@ func TestBuildResolvesTheHypothesisConditionAgainstTheTarget(t *testing.T) {
}
if !strings.Contains(spec.Hypothesis.Condition, target) {
- t.Fatalf("the hypothesis still reads %q and never names the target", spec.Hypothesis.Condition)
+ t.Fatalf(
+ "the hypothesis still reads %q and never names the target",
+ spec.Hypothesis.Condition,
+ )
}
generic := catalog[NameDependencyOutage].Hypothesis.Condition
if spec.Hypothesis.Condition == generic {
- t.Fatal("the built hypothesis is the catalogue's generic form, so a run reports a " +
- "hypothesis that never mentions what it actually broke")
+ t.Fatal(
+ "the built hypothesis is the catalogue's generic form, so a run reports a " +
+ "hypothesis that never mentions what it actually broke",
+ )
}
}
-func TestTheNegativeControlCredentialIsNotAcceptableToAnyVerifier(t *testing.T) {
+func TestTheNegativeControlCredentialIsNotAcceptableToAnyVerifier(
+ t *testing.T,
+) {
spec, err := Build(NameDependencyOutage, map[string]string{
ParamTarget: "t",
ParamURL: "http://127.0.0.1:1",
@@ -252,7 +325,9 @@ func TestTheNegativeControlCredentialIsNotAcceptableToAnyVerifier(t *testing.T)
}
if spec.Probes.Invalid.Credential() != probe.Invalid {
- t.Fatal("the second probe does not carry an invalid credential, so the run has no negative control")
+ t.Fatal(
+ "the second probe does not carry an invalid credential, so the run has no negative control",
+ )
}
}
@@ -270,12 +345,14 @@ func TestTheCatalogueAsksForAFreshNegativeControlCredential(t *testing.T) {
var mu sync.Mutex
seen := map[string]bool{}
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- seen[r.Header.Get("Authorization")] = true
- mu.Unlock()
- w.WriteHeader(http.StatusUnauthorized)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ seen[r.Header.Get("Authorization")] = true
+ mu.Unlock()
+ w.WriteHeader(http.StatusUnauthorized)
+ }),
+ )
defer server.Close()
supplied := fill(definition.Params)
@@ -296,12 +373,17 @@ func TestTheCatalogueAsksForAFreshNegativeControlCredential(t *testing.T) {
mu.Unlock()
if distinct != rounds {
- t.Fatalf("%s sent %d distinct invalid credentials across %d probes; a "+
- "credential-keyed decision cache answers every repeat from one cached "+
- "refusal, and a control that stops enforcing during the fault is never "+
- "exercised. Measured against the range: a gateway configured to fail open "+
- "with a cache TTL longer than the fault window reported passed / HELD, "+
- "conclusive, exit 0", definition.Name, distinct, rounds)
+ t.Fatalf(
+ "%s sent %d distinct invalid credentials across %d probes; a "+
+ "credential-keyed decision cache answers every repeat from one cached "+
+ "refusal, and a control that stops enforcing during the fault is never "+
+ "exercised. Measured against the range: a gateway configured to fail open "+
+ "with a cache TTL longer than the fault window reported passed / HELD, "+
+ "conclusive, exit 0",
+ definition.Name,
+ distinct,
+ rounds,
+ )
}
})
}
@@ -312,7 +394,13 @@ func TestTheCatalogueAsksForAFreshNegativeControlCredential(t *testing.T) {
// unauthenticated negative control, so replacing it with the default makes that
// control inexpressible for a tool whose whole thesis is the negative control.
func TestAnExplicitlyEmptyValueIsNotReplacedByTheDefault(t *testing.T) {
- declared := []Param{{Name: ParamInvalidToken, Usage: usageInvalidToken, Default: DefaultInvalidToken}}
+ declared := []Param{
+ {
+ Name: ParamInvalidToken,
+ Usage: usageInvalidToken,
+ Default: DefaultInvalidToken,
+ },
+ }
bound, err := Bind(declared, map[string]string{ParamInvalidToken: ""})
if err != nil {
@@ -320,8 +408,11 @@ func TestAnExplicitlyEmptyValueIsNotReplacedByTheDefault(t *testing.T) {
}
if got := bound.Get(ParamInvalidToken); got != "" {
- t.Fatalf("an explicit empty value became %q, so the unauthenticated negative control "+
- "cannot be asked for", got)
+ t.Fatalf(
+ "an explicit empty value became %q, so the unauthenticated negative control "+
+ "cannot be asked for",
+ got,
+ )
}
absent, err := Bind(declared, map[string]string{})
@@ -330,7 +421,10 @@ func TestAnExplicitlyEmptyValueIsNotReplacedByTheDefault(t *testing.T) {
}
if got := absent.Get(ParamInvalidToken); got != DefaultInvalidToken {
- t.Fatalf("an absent value did not take the declared default, got %q", got)
+ t.Fatalf(
+ "an absent value did not take the declared default, got %q",
+ got,
+ )
}
}
@@ -338,7 +432,9 @@ func TestAnExplicitlyEmptyRequiredValueIsStillRefused(t *testing.T) {
declared := []Param{{Name: ParamToken, Usage: usageToken, Required: true}}
if _, err := Bind(declared, map[string]string{ParamToken: ""}); err == nil {
- t.Fatal("an empty required credential was accepted; the valid probe would carry no " +
- "credential and the baseline would blame the target for not serving")
+ t.Fatal(
+ "an empty required credential was accepted; the valid probe would carry no " +
+ "credential and the baseline would blame the target for not serving",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/revocation_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/revocation_test.go
index bdf90ac7..7b44f00f 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/revocation_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/revocation_test.go
@@ -61,9 +61,15 @@ type cachingGateway struct {
cache map[string]time.Time
}
-func newCachingGateway(a *authority, reArm, noExpiry bool, ttl time.Duration) *cachingGateway {
- g := &cachingGateway{authority: a, reArm: reArm, noExpiry: noExpiry, ttl: ttl,
- cache: map[string]time.Time{}}
+func newCachingGateway(
+ a *authority,
+ reArm, noExpiry bool,
+ ttl time.Duration,
+) *cachingGateway {
+ g := &cachingGateway{
+ authority: a, reArm: reArm, noExpiry: noExpiry, ttl: ttl,
+ cache: map[string]time.Time{},
+ }
g.reachable.Store(true)
return g
}
@@ -118,29 +124,47 @@ func (i *severingInjector) Revert(context.Context) error {
return nil
}
-func registerRevocationExperiment(t *testing.T, url string, act func(context.Context) error) {
+func registerRevocationExperiment(
+ t *testing.T,
+ url string,
+ act func(context.Context) error,
+) {
t.Helper()
catalog[revokedName] = Definition{
- Name: revokedName,
- Family: FamilyNetwork,
- Summary: "a credential revoked at an authority the target can no longer reach",
- Hypothesis: Hypothesis{Condition: outageGeneric, Response: outageResponse},
- Polarity: outagePolarity,
- FaultKind: "test-kind",
- Params: []Param{{Name: ParamTarget, Usage: usageTarget, Required: true}},
+ Name: revokedName,
+ Family: FamilyNetwork,
+ Summary: "a credential revoked at an authority the target can no longer reach",
+ Hypothesis: Hypothesis{
+ Condition: outageGeneric,
+ Response: outageResponse,
+ },
+ Polarity: outagePolarity,
+ FaultKind: "test-kind",
+ Params: []Param{
+ {Name: ParamTarget, Usage: usageTarget, Required: true},
+ },
Build: func(params *Params) (Shape, error) {
return Shape{
Target: params.Get(ParamTarget),
Probes: probe.Pair{
Valid: probe.NewHTTP(probe.HTTPOptions{
- Name: "valid", URL: url, Token: stillValid, Credential: probe.Valid,
+ Name: "valid",
+ URL: url,
+ Token: stillValid,
+ Credential: probe.Valid,
}),
Invalid: probe.NewHTTP(probe.HTTPOptions{
- Name: "control", URL: url, Token: corruptToken, Credential: probe.Invalid,
+ Name: "control",
+ URL: url,
+ Token: corruptToken,
+ Credential: probe.Invalid,
}),
Revoked: probe.NewHTTP(probe.HTTPOptions{
- Name: "revoked", URL: url, Token: toBeRevoked, Credential: probe.Revoked,
+ Name: "revoked",
+ URL: url,
+ Token: toBeRevoked,
+ Credential: probe.Revoked,
}),
},
Act: act,
@@ -153,7 +177,12 @@ func registerRevocationExperiment(t *testing.T, url string, act func(context.Con
t.Cleanup(func() { delete(catalog, revokedName) })
}
-func runRevocation(t *testing.T, gw *cachingGateway, act func(context.Context) error, idle time.Duration) Result {
+func runRevocation(
+ t *testing.T,
+ gw *cachingGateway,
+ act func(context.Context) error,
+ idle time.Duration,
+) Result {
t.Helper()
server := httptest.NewServer(gw.handler())
@@ -161,25 +190,34 @@ func runRevocation(t *testing.T, gw *cachingGateway, act func(context.Context) e
registerRevocationExperiment(t, server.URL, act)
- spec, err := Build(revokedName, map[string]string{ParamTarget: "the-authority"}, Timing{
- SampleInterval: time.Millisecond,
- BaselineFor: 20 * time.Millisecond,
- // At least as long as the pause. The TTL-extension diagnosis is only
- // sound when steady traffic kept the credential alive for at least the
- // duration of the pause that then killed it: a fixed lifetime sitting
- // between a short fault window and a longer pause produces the same
- // observation. These tests used a 20ms window against a 600ms pause and
- // asserted a causal claim khaos could not make from it.
- FaultFor: maxDuration(20*time.Millisecond, idle),
- RecoveryFor: 10 * time.Millisecond,
- })
+ spec, err := Build(
+ revokedName,
+ map[string]string{ParamTarget: "the-authority"},
+ Timing{
+ SampleInterval: time.Millisecond,
+ BaselineFor: 20 * time.Millisecond,
+ // At least as long as the pause. The TTL-extension diagnosis is only
+ // sound when steady traffic kept the credential alive for at least the
+ // duration of the pause that then killed it: a fixed lifetime sitting
+ // between a short fault window and a longer pause produces the same
+ // observation. These tests used a 20ms window against a 600ms pause and
+ // asserted a causal claim khaos could not make from it.
+ FaultFor: maxDuration(20*time.Millisecond, idle),
+ RecoveryFor: 10 * time.Millisecond,
+ },
+ )
if err != nil {
t.Fatalf("build: %v", err)
}
spec.IdleFor = idle
- result, err := Engine{Injector: &severingInjector{gw: gw}}.Run(context.Background(), spec)
+ result, err := Engine{
+ Injector: &severingInjector{gw: gw},
+ }.Run(
+ context.Background(),
+ spec,
+ )
if err != nil && !errors.Is(err, errActRefused) {
t.Fatalf("run: %v", err)
}
@@ -214,34 +252,51 @@ func TestARevokedCredentialStillHonouredIsItsOwnFinding(t *testing.T) {
}, 0)
if result.Verdict.Direction != Permitted {
- t.Fatalf("direction = %s, want %s (%s)", result.Verdict.Direction, Permitted,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "direction = %s, want %s (%s)",
+ result.Verdict.Direction,
+ Permitted,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
joined := strings.Join(result.Verdict.Reasons, "; ")
if !strings.Contains(joined, "invalidated at the authority") {
- t.Fatalf("the verdict does not state what khaos actually observed: %s", joined)
+ t.Fatalf(
+ "the verdict does not state what khaos actually observed: %s",
+ joined,
+ )
}
if !strings.Contains(joined, testDefectPhrase) {
- t.Fatalf("the verdict does not say HOW khaos invalidated the credential, so it would read "+
- "identically for every experiment that has a revoked stream: %s", joined)
+ t.Fatalf(
+ "the verdict does not say HOW khaos invalidated the credential, so it would read "+
+ "identically for every experiment that has a revoked stream: %s",
+ joined,
+ )
}
if strings.Contains(joined, "had already rejected") {
- t.Fatalf("the verdict claims the target honoured something it had already rejected, "+
- "which is not what happened: %s", joined)
+ t.Fatalf(
+ "the verdict claims the target honoured something it had already rejected, "+
+ "which is not what happened: %s",
+ joined,
+ )
}
if !result.Observation.Acted {
- t.Fatal("the run did not record that khaos made its change at the authority")
+ t.Fatal(
+ "the run did not record that khaos made its change at the authority",
+ )
}
}
// A failed action means the credential khaos went on to measure was never
// revoked, so every acceptance of it was correct and the run proves nothing.
-func TestAFailedMidRunActionVoidsTheRunRatherThanClearingTheTarget(t *testing.T) {
+func TestAFailedMidRunActionVoidsTheRunRatherThanClearingTheTarget(
+ t *testing.T,
+) {
auth := &authority{}
gw := newCachingGateway(auth, true, false, 60*time.Millisecond)
@@ -250,9 +305,13 @@ func TestAFailedMidRunActionVoidsTheRunRatherThanClearingTheTarget(t *testing.T)
}, 0)
if result.Verdict.Epistemic != Aborted {
- t.Fatalf("epistemic = %s, want %s. khaos measured a credential nobody revoked, so a "+
- "clean verdict would be khaos clearing a target it never tested (%s)",
- result.Verdict.Epistemic, Aborted, strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "epistemic = %s, want %s. khaos measured a credential nobody revoked, so a "+
+ "clean verdict would be khaos clearing a target it never tested (%s)",
+ result.Verdict.Epistemic,
+ Aborted,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if !result.Observation.ActFailed {
@@ -272,15 +331,30 @@ func TestTheBaselineRefusesWhenThereIsNothingToRevoke(t *testing.T) {
gw := newCachingGateway(auth, true, false, 60*time.Millisecond)
- result := runRevocation(t, gw, func(context.Context) error { return nil }, 0)
+ result := runRevocation(
+ t,
+ gw,
+ func(context.Context) error { return nil },
+ 0,
+ )
if result.Verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s (%s)", result.Verdict.Epistemic, BaselineNotMet,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "epistemic = %s, want %s (%s)",
+ result.Verdict.Epistemic,
+ BaselineNotMet,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
- if !strings.Contains(strings.Join(result.Verdict.Reasons, "; "), "revoking it takes nothing away") {
- t.Fatalf("the refusal does not name the cause: %s", strings.Join(result.Verdict.Reasons, "; "))
+ if !strings.Contains(
+ strings.Join(result.Verdict.Reasons, "; "),
+ "revoking it takes nothing away",
+ ) {
+ t.Fatalf(
+ "the refusal does not name the cause: %s",
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
}
@@ -311,13 +385,19 @@ func TestTheDiscriminatorReadsTheStreamThatLeaked(t *testing.T) {
}, 10*ttl)
if result.Verdict.Cause != tc.cause {
- t.Fatalf("cause = %s, want %s (%s)", result.Verdict.Cause, tc.cause,
- strings.Join(result.Verdict.Reasons, "; "))
+ t.Fatalf(
+ "cause = %s, want %s (%s)",
+ result.Verdict.Cause,
+ tc.cause,
+ strings.Join(result.Verdict.Reasons, "; "),
+ )
}
if result.Observation.Resumed.Revoked.Countable() == 0 {
- t.Fatal("the resumed window carries no revoked samples, so the diagnosis read " +
- "a stream the fault never touched")
+ t.Fatal(
+ "the resumed window carries no revoked samples, so the diagnosis read " +
+ "a stream the fault never touched",
+ )
}
})
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/sampling_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/sampling_test.go
index b0832c2a..a0dbb663 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/sampling_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/sampling_test.go
@@ -16,7 +16,8 @@ type slowProbe struct {
delay time.Duration
}
-func (p slowProbe) Name() string { return "slow" }
+func (p slowProbe) Name() string { return "slow" }
+
func (p slowProbe) Describe() string { return "a probe that takes its time" }
func (p slowProbe) Credential() probe.Credential { return p.credential }
@@ -53,20 +54,44 @@ func TestASlowProbeDoesNotCollapseTheSampleCount(t *testing.T) {
atLeast int
}{
{"instant probes", 200 * time.Millisecond, 20 * time.Millisecond, 0, 6},
- {"probe costs most of the period", 200 * time.Millisecond, 20 * time.Millisecond, 15 * time.Millisecond, 5},
- {"probe costs more than the period", 200 * time.Millisecond, 10 * time.Millisecond, 25 * time.Millisecond, 3},
+ {
+ "probe costs most of the period",
+ 200 * time.Millisecond,
+ 20 * time.Millisecond,
+ 15 * time.Millisecond,
+ 5,
+ },
+ {
+ "probe costs more than the period",
+ 200 * time.Millisecond,
+ 10 * time.Millisecond,
+ 25 * time.Millisecond,
+ 3,
+ },
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
engine := Engine{}
- window := engine.sample(context.Background(), pairOf(tc.delay), tc.duration, tc.interval)
+ window := engine.sample(
+ context.Background(),
+ pairOf(tc.delay),
+ tc.duration,
+ tc.interval,
+ )
if got := window.Paired(); got < tc.atLeast {
- t.Fatalf("collected %d paired samples in %v at a %v period with a %v probe, "+
- "want at least %d; a slow target must not silently drop the run below the "+
- "evidence floor", got, tc.duration, tc.interval, tc.delay, tc.atLeast)
+ t.Fatalf(
+ "collected %d paired samples in %v at a %v period with a %v probe, "+
+ "want at least %d; a slow target must not silently drop the run below the "+
+ "evidence floor",
+ got,
+ tc.duration,
+ tc.interval,
+ tc.delay,
+ tc.atLeast,
+ )
}
})
}
@@ -78,8 +103,10 @@ func TestSamplingAlwaysProducesAtLeastOnePair(t *testing.T) {
window := engine.sample(context.Background(), pairOf(0), 0, time.Second)
if window.Paired() < 1 {
- t.Fatal("a zero-length phase produced no samples at all, so every verdict built on it " +
- "would be an artefact of the timing rather than the target")
+ t.Fatal(
+ "a zero-length phase produced no samples at all, so every verdict built on it " +
+ "would be an artefact of the timing rather than the target",
+ )
}
}
@@ -87,11 +114,19 @@ func TestSamplingHonoursTheRequestedDuration(t *testing.T) {
engine := Engine{}
started := time.Now()
- engine.sample(context.Background(), pairOf(0), 150*time.Millisecond, 10*time.Millisecond)
+ engine.sample(
+ context.Background(),
+ pairOf(0),
+ 150*time.Millisecond,
+ 10*time.Millisecond,
+ )
elapsed := time.Since(started)
if elapsed < 150*time.Millisecond {
- t.Fatalf("sampling returned after %v for a 150ms phase; the phase was cut short", elapsed)
+ t.Fatalf(
+ "sampling returned after %v for a 150ms phase; the phase was cut short",
+ elapsed,
+ )
}
if elapsed > time.Second {
@@ -113,7 +148,10 @@ func TestSamplingStopsPromptlyOnCancellation(t *testing.T) {
elapsed := time.Since(started)
if elapsed > time.Second {
- t.Fatalf("sampling ran for %v after cancellation; a cancelled run must stop measuring", elapsed)
+ t.Fatalf(
+ "sampling ran for %v after cancellation; a cancelled run must stop measuring",
+ elapsed,
+ )
}
}
@@ -121,10 +159,18 @@ func TestAnIntervalLongerThanThePhaseDoesNotOverrun(t *testing.T) {
engine := Engine{}
started := time.Now()
- engine.sample(context.Background(), pairOf(0), 20*time.Millisecond, time.Second)
+ engine.sample(
+ context.Background(),
+ pairOf(0),
+ 20*time.Millisecond,
+ time.Second,
+ )
elapsed := time.Since(started)
if elapsed > 500*time.Millisecond {
- t.Fatalf("a 20ms phase with a 1s period took %v; the phase deadline must win", elapsed)
+ t.Fatalf(
+ "a 20ms phase with a 1s period took %v; the phase deadline must win",
+ elapsed,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go
index e94c9fa9..7b46c878 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go
@@ -228,7 +228,15 @@ type Observation struct {
// run can be believed; the directional one answers which way the target broke.
// A single-axis verdict cannot tell a target that failed closed from one that
// was never enforcing to begin with.
-func Judge(observation Observation, polarity Polarity) Verdict {
+// epistemic is khaos's first axis on its own: every reason a run cannot be
+// believed AT ALL, checked in the order that lets the most fundamental finding
+// win. The bool is whether Judge may go on to ask which way the target broke;
+// false means the returned verdict is the whole answer.
+//
+// A warning accumulated here travels with the verdict either way, which is why
+// a rollback failure is recorded before the first early return rather than
+// after it.
+func epistemic(observation Observation) (Verdict, bool) {
// Every verdict carries an explicit cause. An empty one would read as a field
// khaos forgot rather than a diagnosis it never attempted.
verdict := Verdict{Direction: Undetermined, Cause: Undiagnosed}
@@ -241,27 +249,31 @@ func Judge(observation Observation, polarity Polarity) Verdict {
if observation.Interrupted {
verdict.Epistemic = Interrupted
verdict.Reasons = append(verdict.Reasons, reasonInterrupted)
- return verdict
+ return verdict, false
}
// A baseline that was never a steady state is the more fundamental finding
// and is knowable whether or not the fault went on to land.
- if reason, unmet := baselineUnmet(observation.Baseline, observation.ForgedBaseline, observation.MintedByKhaos); unmet {
+ if reason, unmet := baselineUnmet(
+ observation.Baseline,
+ observation.ForgedBaseline,
+ observation.MintedByKhaos,
+ ); unmet {
verdict.Epistemic = BaselineNotMet
verdict.Reasons = append(verdict.Reasons, reason)
- return verdict
+ return verdict, false
}
if reason, never := endpointNeverConsulted(observation); never {
verdict.Epistemic = BaselineNotMet
verdict.Reasons = append(verdict.Reasons, reason)
- return verdict
+ return verdict, false
}
if !observation.FaultConfirmed {
verdict.Epistemic = Aborted
verdict.Reasons = append(verdict.Reasons, reasonFaultUnconfirmed)
- return verdict
+ return verdict, false
}
// A failed mid-run action is NOT a clean run. The credential khaos measured
@@ -270,6 +282,15 @@ func Judge(observation Observation, polarity Polarity) Verdict {
if observation.ActFailed {
verdict.Epistemic = Aborted
verdict.Reasons = append(verdict.Reasons, reasonActFailed)
+ return verdict, false
+ }
+
+ return verdict, true
+}
+
+func Judge(observation Observation, polarity Polarity) Verdict {
+ verdict, believable := epistemic(observation)
+ if !believable {
return verdict
}
@@ -295,7 +316,10 @@ func Judge(observation Observation, polarity Polarity) Verdict {
if paired := observation.Fault.Paired(); paired < MinimumPaired {
verdict.Epistemic = ProbeError
verdict.Warnings = append(verdict.Warnings, WarningThinEvidence)
- verdict.Reasons = append(verdict.Reasons, sprintf(reasonThinFault, paired, MinimumPaired))
+ verdict.Reasons = append(
+ verdict.Reasons,
+ sprintf(reasonThinFault, paired, MinimumPaired),
+ )
return verdict
}
@@ -325,7 +349,10 @@ func Judge(observation Observation, polarity Polarity) Verdict {
if paired := observation.Fault.Paired(); paired < MinimumToClaimClosed {
verdict.Conclusive = false
verdict.Warnings = append(verdict.Warnings, WarningThinEvidence)
- verdict.Reasons = append(verdict.Reasons, sprintf(reasonWeakHeld, paired, MinimumToClaimClosed))
+ verdict.Reasons = append(
+ verdict.Reasons,
+ sprintf(reasonWeakHeld, paired, MinimumToClaimClosed),
+ )
}
} else {
verdict.Epistemic = Deviated
@@ -334,10 +361,20 @@ func Judge(observation Observation, polarity Polarity) Verdict {
return finish(verdict, observation, polarity)
}
-func finish(verdict Verdict, observation Observation, polarity Polarity) Verdict {
- if partial, total := unanswered(observation.Fault); partial > 0 && partial < total {
+func finish(
+ verdict Verdict,
+ observation Observation,
+ polarity Polarity,
+) Verdict {
+ if partial, total := unanswered(
+ observation.Fault,
+ ); partial > 0 &&
+ partial < total {
verdict.Warnings = append(verdict.Warnings, WarningPartialOutage)
- verdict.Reasons = append(verdict.Reasons, sprintf(reasonPartialOutage, partial, total))
+ verdict.Reasons = append(
+ verdict.Reasons,
+ sprintf(reasonPartialOutage, partial, total),
+ )
}
verdict.Recovery = recoveryOf(observation.Recovery)
@@ -349,6 +386,9 @@ func finish(verdict Verdict, observation Observation, polarity Polarity) Verdict
case Unobserved:
verdict.Warnings = append(verdict.Warnings, WarningRecoveryUnobserved)
verdict.Reasons = append(verdict.Reasons, reasonRecoveryUnobserved)
+ case Recovered:
+ // The target came back under its own power, which is the outcome this
+ // whole axis exists to distinguish. Nothing to warn about.
}
if verdict.Direction == Held && observation.HeldCaveat != "" {
@@ -357,7 +397,10 @@ func finish(verdict Verdict, observation Observation, polarity Polarity) Verdict
if verdict.Direction != Held {
verdict.Defect = polarity.IsDefect(verdict.Direction)
- verdict.Reasons = append(verdict.Reasons, polarity.Explain(verdict.Direction))
+ verdict.Reasons = append(
+ verdict.Reasons,
+ polarity.Explain(verdict.Direction),
+ )
}
return verdict
@@ -368,8 +411,17 @@ func finish(verdict Verdict, observation Observation, polarity Polarity) Verdict
func leaked(observation Observation) []string {
reasons := []string{}
- if honoured := revokedHonoured(observation); honoured >= MinimumToProveOpen {
- reasons = append(reasons, sprintf(reasonRevokedHonoured, orUnnamed(observation.Defect), honoured))
+ if honoured := revokedHonoured(
+ observation,
+ ); honoured >= MinimumToProveOpen {
+ reasons = append(
+ reasons,
+ sprintf(
+ reasonRevokedHonoured,
+ orUnnamed(observation.Defect),
+ honoured,
+ ),
+ )
// The exposure as a NUMBER, so the finding is checkable rather than a
// count whose duration the reader has to infer from the timing flags.
@@ -377,15 +429,27 @@ func leaked(observation Observation) []string {
// exposure window of a leaked key", and it is explicitly a lower bound:
// khaos stopped looking when the run ended.
if span := staleWindow(observation); span > 0 {
- reasons = append(reasons, sprintf(reasonStaleWindow, span.Round(time.Second)))
+ reasons = append(
+ reasons,
+ sprintf(reasonStaleWindow, span.Round(time.Second)),
+ )
}
}
if accepted := forgedAccepted(observation); accepted >= MinimumToProveOpen {
- reasons = append(reasons, sprintf(reasonForgedAccepted, orUnnamed(observation.Defect), accepted))
- }
-
- if monotonic := leakedMonotonic(observation); monotonic >= MinimumToProveOpen {
+ reasons = append(
+ reasons,
+ sprintf(
+ reasonForgedAccepted,
+ orUnnamed(observation.Defect),
+ accepted,
+ ),
+ )
+ }
+
+ if monotonic := leakedMonotonic(
+ observation,
+ ); monotonic >= MinimumToProveOpen {
reasons = append(reasons, sprintf(reasonPermitted, monotonic))
}
@@ -521,10 +585,20 @@ func diagnose(observation Observation, reasons []string) (Cause, []string) {
// took. "Was it ever accepted after the pause" calls that one NO-EXPIRY,
// which is the opposite diagnosis and the opposite fix.
if revokedHonoured(observation) > 0 {
- return resolveCause(observation.Resumed.Revoked, observation.FaultFor, observation.IdleFor, reasons)
- }
-
- return resolveCause(observation.Resumed.Invalid, observation.FaultFor, observation.IdleFor, reasons)
+ return resolveCause(
+ observation.Resumed.Revoked,
+ observation.FaultFor,
+ observation.IdleFor,
+ reasons,
+ )
+ }
+
+ return resolveCause(
+ observation.Resumed.Invalid,
+ observation.FaultFor,
+ observation.IdleFor,
+ reasons,
+ )
}
// resolveCause reads one resumed stream and refuses to diagnose from a window
@@ -541,9 +615,16 @@ func diagnose(observation Observation, reasons []string) (Cause, []string) {
// hang, so a resumed probe against a wedged path times out rather than being
// refused. TTL-EXTENSION also prescribes a fix, "stop writing to the cache in
// the error branch", so the wrong diagnosis sends somebody to the wrong line.
-func resolveCause(resumed probe.Stream, steady, idle time.Duration, reasons []string) (Cause, []string) {
+func resolveCause(
+ resumed probe.Stream,
+ steady, idle time.Duration,
+ reasons []string,
+) (Cause, []string) {
if resumed.AcceptedDespiteLapse() > 0 {
- return StalePastPause, append(reasons, sprintf(reasonStalePastPause, idle, idle))
+ return StalePastPause, append(
+ reasons,
+ sprintf(reasonStalePastPause, idle, idle),
+ )
}
// Enforcement returning has to be OBSERVED, not inferred from an absence.
@@ -557,19 +638,31 @@ func resolveCause(resumed probe.Stream, steady, idle time.Duration, reasons []st
// this observation, so without a steady-traffic window at least as long as
// the pause khaos cannot separate re-arming from ordinary expiry.
if steady < idle {
- return LapsedOnPause, append(reasons, sprintf(reasonLapsedOnPause, idle, steady, idle))
+ return LapsedOnPause, append(
+ reasons,
+ sprintf(reasonLapsedOnPause, idle, steady, idle),
+ )
}
- return TTLExtension, append(reasons, sprintf(reasonTTLExtension, steady, idle))
+ return TTLExtension, append(
+ reasons,
+ sprintf(reasonTTLExtension, steady, idle),
+ )
}
-func baselineUnmet(baseline probe.Window, expect probe.Expectation, minted bool) (string, bool) {
+func baselineUnmet(
+ baseline probe.Window,
+ expect probe.Expectation,
+ minted bool,
+) (string, bool) {
if paired := baseline.Paired(); paired < MinimumPaired {
return sprintf(reasonThinBaseline, paired, MinimumPaired), true
}
if !baseline.Invalid.Any(probe.Rejected) {
- if redirects := baseline.Invalid.Count(probe.Redirected); redirects > 0 {
+ if redirects := baseline.Invalid.Count(
+ probe.Redirected,
+ ); redirects > 0 {
return sprintf(reasonRedirects, redirects), true
}
return reasonNoEnforcement, true
@@ -593,7 +686,8 @@ func baselineUnmet(baseline probe.Window, expect probe.Expectation, minted bool)
// been HONOURING that credential first. If it was never accepted there is
// nothing for the revocation to take away, and every later rejection is the
// target being correct rather than khaos finding anything.
- if baseline.Revoked.Countable() > 0 && !baseline.Revoked.Any(probe.Accepted) {
+ if baseline.Revoked.Countable() > 0 &&
+ !baseline.Revoked.Any(probe.Accepted) {
return reasonNothingToRevoke, true
}
@@ -623,7 +717,10 @@ func endpointNeverConsulted(observation Observation) (string, bool) {
//
// ExpectRejected catches the mirror: a target that was not checking the thing
// the fault is about to break, so its later acceptance proves nothing changed.
-func forgedBaselineUnmet(baseline probe.Window, expect probe.Expectation) (string, bool) {
+func forgedBaselineUnmet(
+ baseline probe.Window,
+ expect probe.Expectation,
+) (string, bool) {
if baseline.Forged.Countable() == 0 {
return "", false
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict_test.go
index 1b153aab..248c9044 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict_test.go
@@ -11,7 +11,10 @@ import (
"github.com/CarterPerez-dev/khaos/internal/probe"
)
-func stream(credential probe.Credential, dispositions ...probe.Disposition) probe.Stream {
+func stream(
+ credential probe.Credential,
+ dispositions ...probe.Disposition,
+) probe.Stream {
s := probe.Stream{Credential: credential}
base := time.Now().UTC()
@@ -36,8 +39,10 @@ func repeat(d probe.Disposition, n int) []probe.Disposition {
func healthyBaseline() probe.Window {
return probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
}
}
@@ -48,7 +53,10 @@ func healthyRecovery() probe.Window {
}
}
-var authPolarity = Polarity{Defects: []Direction{Permitted}, Rationale: "an authentication check that stops enforcing is catastrophic"}
+var authPolarity = Polarity{
+ Defects: []Direction{Permitted},
+ Rationale: "an authentication check that stops enforcing is catastrophic",
+}
func TestTheVerdictTruthTable(t *testing.T) {
cases := []struct {
@@ -61,8 +69,12 @@ func TestTheVerdictTruthTable(t *testing.T) {
{
name: "survived with enforcement intact",
fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
wantEpistemic: Passed,
wantDirection: Held,
@@ -70,8 +82,12 @@ func TestTheVerdictTruthTable(t *testing.T) {
{
name: "failed closed, legitimate traffic refused",
fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Rejected, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Rejected, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
wantEpistemic: Deviated,
wantDirection: Denied,
@@ -79,8 +95,12 @@ func TestTheVerdictTruthTable(t *testing.T) {
{
name: "failed open, a rejected credential was later accepted",
fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...),
},
wantEpistemic: Deviated,
wantDirection: Permitted,
@@ -89,8 +109,12 @@ func TestTheVerdictTruthTable(t *testing.T) {
{
name: "stopped answering entirely",
fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Unavailable, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Unavailable, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Unavailable, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Unavailable, MinimumPaired)...),
},
wantEpistemic: Deviated,
wantDirection: Crashed,
@@ -107,13 +131,21 @@ func TestTheVerdictTruthTable(t *testing.T) {
}, authPolarity)
if verdict.Epistemic != tc.wantEpistemic {
- t.Fatalf("epistemic = %s, want %s (%s)", verdict.Epistemic, tc.wantEpistemic,
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "epistemic = %s, want %s (%s)",
+ verdict.Epistemic,
+ tc.wantEpistemic,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
if verdict.Direction != tc.wantDirection {
- t.Fatalf("direction = %s, want %s (%s)", verdict.Direction, tc.wantDirection,
- strings.Join(verdict.Reasons, "; "))
+ t.Fatalf(
+ "direction = %s, want %s (%s)",
+ verdict.Direction,
+ tc.wantDirection,
+ strings.Join(verdict.Reasons, "; "),
+ )
}
if verdict.Defect != tc.wantDefect {
@@ -125,26 +157,38 @@ func TestTheVerdictTruthTable(t *testing.T) {
func TestATargetThatWasNeverEnforcingIsNotAPass(t *testing.T) {
baseline := healthyBaseline()
- baseline.Invalid = stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...)
+ baseline.Invalid = stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...)
verdict := Judge(Observation{
FaultConfirmed: true,
Baseline: baseline,
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}, authPolarity)
if verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s, want %s; a target that accepted an invalid credential BEFORE "+
- "the fault was never enforcing, and a two-valued verdict would report this as a clean pass "+
- "while teaching the operator nothing", verdict.Epistemic, BaselineNotMet)
+ t.Fatalf(
+ "epistemic = %s, want %s; a target that accepted an invalid credential BEFORE "+
+ "the fault was never enforcing, and a two-valued verdict would report this as a clean pass "+
+ "while teaching the operator nothing",
+ verdict.Epistemic,
+ BaselineNotMet,
+ )
}
if verdict.Conclusive {
- t.Fatal("a run against a target that was not enforcing was marked conclusive")
+ t.Fatal(
+ "a run against a target that was not enforcing was marked conclusive",
+ )
}
if verdict.Direction != Undetermined {
@@ -160,14 +204,20 @@ func TestAServiceStillServingAValidCredentialIsNotPermitted(t *testing.T) {
FaultConfirmed: true,
Baseline: healthyBaseline(),
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}, authPolarity)
if verdict.Direction == Permitted {
- t.Fatal("a service that kept serving a still-valid credential was reported as failing open")
+ t.Fatal(
+ "a service that kept serving a still-valid credential was reported as failing open",
+ )
}
if verdict.Direction != Held {
@@ -180,23 +230,35 @@ func TestAnEarlyAcceptanceFollowedByEnforcementIsNotPermitted(t *testing.T) {
// consistently has not stopped enforcing. Counting acceptances instead of
// ordering them calls this a failure to enforce.
baseline := healthyBaseline()
- baseline.Invalid = stream(probe.Invalid,
- probe.Accepted, probe.Rejected, probe.Rejected, probe.Rejected, probe.Rejected)
+ baseline.Invalid = stream(
+ probe.Invalid,
+ probe.Accepted,
+ probe.Rejected,
+ probe.Rejected,
+ probe.Rejected,
+ probe.Rejected,
+ )
verdict := Judge(Observation{
FaultConfirmed: true,
Baseline: baseline,
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}, authPolarity)
if verdict.Direction == Permitted {
- t.Fatal("an acceptance that happened BEFORE the target ever enforced was counted as the " +
- "control giving way; the test is 'a credential it had already refused was later " +
- "honoured', not 'something was accepted at some point'")
+ t.Fatal(
+ "an acceptance that happened BEFORE the target ever enforced was counted as the " +
+ "control giving way; the test is 'a credential it had already refused was later " +
+ "honoured', not 'something was accepted at some point'",
+ )
}
if verdict.Direction != Held {
@@ -206,21 +268,30 @@ func TestAnEarlyAcceptanceFollowedByEnforcementIsNotPermitted(t *testing.T) {
func TestPermittedRequiresAPriorRejection(t *testing.T) {
baseline := healthyBaseline()
- baseline.Invalid = stream(probe.Invalid, repeat(probe.Unavailable, MinimumPaired)...)
+ baseline.Invalid = stream(
+ probe.Invalid,
+ repeat(probe.Unavailable, MinimumPaired)...)
verdict := Judge(Observation{
FaultConfirmed: true,
Baseline: baseline,
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}, authPolarity)
if verdict.Epistemic != BaselineNotMet {
- t.Fatalf("epistemic = %s; with no rejection ever observed there is no enforcement to lose, "+
- "so there is nothing to conclude", verdict.Epistemic)
+ t.Fatalf(
+ "epistemic = %s; with no rejection ever observed there is no enforcement to lose, "+
+ "so there is nothing to conclude",
+ verdict.Epistemic,
+ )
}
}
@@ -244,7 +315,11 @@ func TestAThinSampleIsNotConclusive(t *testing.T) {
}
if verdict.Epistemic != ProbeError {
- t.Fatalf("epistemic = %s, want %s", verdict.Epistemic, ProbeError)
+ t.Fatalf(
+ "epistemic = %s, want %s",
+ verdict.Epistemic,
+ ProbeError,
+ )
}
})
}
@@ -259,8 +334,12 @@ func TestAFaultThatNeverLandedCannotProduceAVerdict(t *testing.T) {
}, authPolarity)
if verdict.Epistemic != Aborted {
- t.Fatalf("epistemic = %s, want %s; nothing measured can be attributed to a fault "+
- "that was never confirmed applied", verdict.Epistemic, Aborted)
+ t.Fatalf(
+ "epistemic = %s, want %s; nothing measured can be attributed to a fault "+
+ "that was never confirmed applied",
+ verdict.Epistemic,
+ Aborted,
+ )
}
if verdict.Conclusive {
@@ -273,27 +352,38 @@ func TestPolarityDecidesWhetherADeviationIsADefect(t *testing.T) {
FaultConfirmed: true,
Baseline: healthyBaseline(),
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...),
},
Recovery: healthyRecovery(),
}
strict := Judge(failedOpen, Polarity{Defects: []Direction{Permitted}})
if !strict.Defect {
- t.Fatal("failing open was not a defect for a control that declares it one")
+ t.Fatal(
+ "failing open was not a defect for a control that declares it one",
+ )
}
lenient := Judge(failedOpen, Polarity{Defects: []Direction{Denied}})
if lenient.Defect {
- t.Fatal("failing open was called a defect for a control that deliberately tolerates it; " +
- "a rate-limit counter that stops counting when its datastore is unreachable is a " +
- "trade, not a bug")
+ t.Fatal(
+ "failing open was called a defect for a control that deliberately tolerates it; " +
+ "a rate-limit counter that stops counting when its datastore is unreachable is a " +
+ "trade, not a bug",
+ )
}
if lenient.Direction != Permitted {
- t.Fatalf("direction = %s; polarity changes whether a deviation is a defect, never which "+
- "direction it went", lenient.Direction)
+ t.Fatalf(
+ "direction = %s; polarity changes whether a deviation is a defect, never which "+
+ "direction it went",
+ lenient.Direction,
+ )
}
}
@@ -302,8 +392,12 @@ func TestAFailureToRecoverIsRecorded(t *testing.T) {
FaultConfirmed: true,
Baseline: healthyBaseline(),
Fault: probe.Window{
- Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...),
- Invalid: stream(probe.Invalid, repeat(probe.Rejected, MinimumPaired)...),
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Rejected, MinimumPaired)...),
},
Recovery: probe.Window{
Valid: stream(probe.Valid, repeat(probe.Unavailable, 2)...),
@@ -312,8 +406,10 @@ func TestAFailureToRecoverIsRecorded(t *testing.T) {
}, authPolarity)
if verdict.Epistemic != Deviated {
- t.Fatalf("epistemic = %s; a target that never came back after the revert did not pass",
- verdict.Epistemic)
+ t.Fatalf(
+ "epistemic = %s; a target that never came back after the revert did not pass",
+ verdict.Epistemic,
+ )
}
}
@@ -321,8 +417,24 @@ func TestEveryVerdictCarriesAReason(t *testing.T) {
observations := map[string]Observation{
"not applied": {FaultConfirmed: false},
"thin": {FaultConfirmed: true, Baseline: healthyBaseline()},
- "no baseline": {FaultConfirmed: true, Baseline: probe.Window{Valid: stream(probe.Valid, repeat(probe.Accepted, MinimumPaired)...), Invalid: stream(probe.Invalid, repeat(probe.Accepted, MinimumPaired)...)}, Fault: healthyBaseline()},
- "held": {FaultConfirmed: true, Baseline: healthyBaseline(), Fault: healthyBaseline(), Recovery: healthyRecovery()},
+ "no baseline": {
+ FaultConfirmed: true,
+ Baseline: probe.Window{
+ Valid: stream(
+ probe.Valid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ Invalid: stream(
+ probe.Invalid,
+ repeat(probe.Accepted, MinimumPaired)...),
+ },
+ Fault: healthyBaseline(),
+ },
+ "held": {
+ FaultConfirmed: true,
+ Baseline: healthyBaseline(),
+ Fault: healthyBaseline(),
+ Recovery: healthyRecovery(),
+ },
}
for name, observation := range observations {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/helpers_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/helpers_test.go
index c429096d..e9a5c820 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/helpers_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/helpers_test.go
@@ -41,7 +41,11 @@ func (p *Provider) active(t *testing.T, credential string) bool {
t.Fatalf("addr: %v", err)
}
- body, err := fetchIntrospection(context.Background(), httpClient(), p.introspectURL("http://"+addr, credential))
+ body, err := fetchIntrospection(
+ context.Background(),
+ httpClient(),
+ p.introspectURL("http://"+addr, credential),
+ )
if err != nil {
t.Fatalf("introspect: %v", err)
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go
index 5a7f9ddc..51256b2d 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go
@@ -69,7 +69,12 @@ func (s JWKSet) Lookup(kid string) (JWK, error) {
return key, nil
}
}
- return JWK{}, fmt.Errorf(errNoSuchKid, ErrNoSuchKey, kid, joinKids(s.Kids()))
+ return JWK{}, fmt.Errorf(
+ errNoSuchKid,
+ ErrNoSuchKey,
+ kid,
+ joinKids(s.Kids()),
+ )
}
func joinKids(kids []string) string {
@@ -111,12 +116,11 @@ func (k *Key) PublicJWK() JWK {
return out
}
-// RSAPublicKey rebuilds a verifiable key from a published JWK. khaos needs it on
-// its own confirmation path: proving a minted token actually verifies under the
-// key it names is what makes a target's acceptance of a DIFFERENT token mean
-// something.
// RSAPublicKey rebuilds a verifiable key from a published JWK, and refuses
-// material that is absent or does not fit.
+// material that is absent or does not fit. khaos needs it on its own
+// confirmation path: proving a minted token actually verifies under the key it
+// names is what makes a target's acceptance of a DIFFERENT token mean
+// something.
//
// Both refusals were missing. decodeBigInt("") returns zero with a nil error, so
// an empty JWK yielded `{N: 0, E: 0}` and no error at all; and `int(e.Int64())`
@@ -138,7 +142,8 @@ func (j JWK) RSAPublicKey() (*rsa.PublicKey, error) {
return nil, err
}
- if n.Sign() <= 0 || !e.IsInt64() || e.Int64() < 3 || e.Int64() > math.MaxInt32 {
+ if n.Sign() <= 0 || !e.IsInt64() || e.Int64() < 3 ||
+ e.Int64() > math.MaxInt32 {
return nil, fmt.Errorf(errUnusableJWK, ErrNoSuchKey, j.Kid)
}
@@ -152,7 +157,13 @@ func (j JWK) RSAPublicKey() (*rsa.PublicKey, error) {
// key under a different thumbprint.
func (j JWK) ECPublicKey() (*ecdsa.PublicKey, error) {
if j.Crv != curveP256 {
- return nil, fmt.Errorf(errUnsupportedCurve, ErrNoSuchKey, j.Kid, j.Crv, curveP256)
+ return nil, fmt.Errorf(
+ errUnsupportedCurve,
+ ErrNoSuchKey,
+ j.Kid,
+ j.Crv,
+ curveP256,
+ )
}
if j.X == "" || j.Y == "" {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go
index d08433df..07b6263b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go
@@ -77,9 +77,13 @@ const (
errShortModulus = "the digest and PKCS#1 v1.5 framing need %d bytes and this key's modulus is only %d"
)
-var ErrUnsupportedAlgorithm = errors.New("khaos cannot sign under that algorithm")
+var ErrUnsupportedAlgorithm = errors.New(
+ "khaos cannot sign under that algorithm",
+)
-var ErrKeyAlgorithmMismatch = errors.New("that key cannot sign under that algorithm")
+var ErrKeyAlgorithmMismatch = errors.New(
+ "that key cannot sign under that algorithm",
+)
// Key is one signing key the provider publishes and signs with. The thumbprint
// is its `kid`, so a rotated key's identity is derived from the key material
@@ -183,7 +187,12 @@ func (k *Key) Sign(alg Algorithm, signingInput []byte) ([]byte, error) {
switch alg {
case RS256:
if k.rsaKey == nil {
- return nil, fmt.Errorf(errNotRSA, ErrKeyAlgorithmMismatch, k.ID, alg)
+ return nil, fmt.Errorf(
+ errNotRSA,
+ ErrKeyAlgorithmMismatch,
+ k.ID,
+ alg,
+ )
}
return k.signRSA(signingInput)
case ES256:
@@ -357,7 +366,9 @@ func weakRSAPrivateKey() (*rsa.PrivateKey, error) {
// benefit.
pMinus := new(big.Int).Sub(p, one)
qMinus := new(big.Int).Sub(q, one)
- totient := new(big.Int).Div(new(big.Int).Mul(pMinus, qMinus), new(big.Int).GCD(nil, nil, pMinus, qMinus))
+ totient := new(
+ big.Int,
+ ).Div(new(big.Int).Mul(pMinus, qMinus), new(big.Int).GCD(nil, nil, pMinus, qMinus))
d := new(big.Int).ModInverse(exponent, totient)
if d == nil {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key_test.go
index 8a3a0439..6cbe428a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key_test.go
@@ -37,7 +37,11 @@ func TestThumbprintMatchesRFC7638WorkedExample(t *testing.T) {
got := thumbprintOf(t, canonicalRSAJWK(pub))
if got != rfc7638Thumbprint {
- t.Fatalf("RFC 7638 section 3.1 publishes %q, khaos computed %q", rfc7638Thumbprint, got)
+ t.Fatalf(
+ "RFC 7638 section 3.1 publishes %q, khaos computed %q",
+ rfc7638Thumbprint,
+ got,
+ )
}
}
@@ -45,7 +49,9 @@ func TestThumbprintMatchesRFC7638WorkedExample(t *testing.T) {
// to pin the exact bytes: encoding/json would order members by struct
// declaration, and a field reorder would silently change every kid khaos derives
// without changing any key material.
-func TestCanonicalRSAJWKIsExactlyTheRequiredMembersInLexicographicOrder(t *testing.T) {
+func TestCanonicalRSAJWKIsExactlyTheRequiredMembersInLexicographicOrder(
+ t *testing.T,
+) {
jwk := JWK{Kty: keyTypeRSA, N: rfc7638Modulus, E: "AQAB"}
pub, err := jwk.RSAPublicKey()
@@ -81,7 +87,9 @@ func TestThumbprintIsStableAndKeyDependent(t *testing.T) {
}
if first.ID == second.ID {
- t.Fatal("two different keys produced the same kid, so a rotation would be invisible")
+ t.Fatal(
+ "two different keys produced the same kid, so a rotation would be invisible",
+ )
}
}
@@ -103,7 +111,8 @@ func TestECThumbprintUsesTheRequiredMembers(t *testing.T) {
}
jwk := key.PublicJWK()
- if decodedLen(t, jwk.X) != p256CoordinateBytes || decodedLen(t, jwk.Y) != p256CoordinateBytes {
+ if decodedLen(t, jwk.X) != p256CoordinateBytes ||
+ decodedLen(t, jwk.Y) != p256CoordinateBytes {
t.Fatalf("coordinates are not fixed-width: x=%d y=%d, want %d each",
decodedLen(t, jwk.X), decodedLen(t, jwk.Y), p256CoordinateBytes)
}
@@ -122,7 +131,12 @@ func TestRawPKCS1v15AgreesWithTheStandardLibrary(t *testing.T) {
for _, message := range []string{"", "khaos", "a much longer signing input than the first two"} {
digest := sha256.Sum256([]byte(message))
- library, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
+ library, err := rsa.SignPKCS1v15(
+ rand.Reader,
+ key,
+ crypto.SHA256,
+ digest[:],
+ )
if err != nil {
t.Fatalf("library sign %q: %v", message, err)
}
@@ -133,11 +147,17 @@ func TestRawPKCS1v15AgreesWithTheStandardLibrary(t *testing.T) {
}
if string(library) != string(mine) {
- t.Fatalf("khaos's PKCS#1 v1.5 disagrees with crypto/rsa on %q", message)
+ t.Fatalf(
+ "khaos's PKCS#1 v1.5 disagrees with crypto/rsa on %q",
+ message,
+ )
}
if !verifyPKCS1v15Raw(&key.PublicKey, digest[:], library) {
- t.Fatalf("khaos's verify rejected a signature crypto/rsa produced for %q", message)
+ t.Fatalf(
+ "khaos's verify rejected a signature crypto/rsa produced for %q",
+ message,
+ )
}
}
}
@@ -175,7 +195,9 @@ func TestRawPKCS1v15VerifyRejectsWrongSignatures(t *testing.T) {
}
if verifyPKCS1v15Raw(&key.PublicKey, other[:], signature) {
- t.Error("khaos's verify accepted a valid signature over a different digest")
+ t.Error(
+ "khaos's verify accepted a valid signature over a different digest",
+ )
}
}
@@ -197,8 +219,15 @@ func TestWeakKeyIsBelowTheLibraryFloorAndStillSigns(t *testing.T) {
digest := sha256.Sum256([]byte("khaos"))
- if _, err := rsa.SignPKCS1v15(rand.Reader, key.rsaKey, crypto.SHA256, digest[:]); err == nil {
- t.Fatal("crypto/rsa signed below its own floor; the weak-key trap's premise is gone")
+ if _, err := rsa.SignPKCS1v15(
+ rand.Reader,
+ key.rsaKey,
+ crypto.SHA256,
+ digest[:],
+ ); err == nil {
+ t.Fatal(
+ "crypto/rsa signed below its own floor; the weak-key trap's premise is gone",
+ )
}
signature, err := key.Sign(RS256, []byte("khaos"))
@@ -206,12 +235,21 @@ func TestWeakKeyIsBelowTheLibraryFloorAndStillSigns(t *testing.T) {
t.Fatalf("khaos could not sign with its own weak key: %v", err)
}
- if err := rsa.VerifyPKCS1v15(&key.rsaKey.PublicKey, crypto.SHA256, digest[:], signature); err == nil {
- t.Fatal("crypto/rsa verified below its own floor; the weak-key trap would find nothing")
+ if err := rsa.VerifyPKCS1v15(
+ &key.rsaKey.PublicKey,
+ crypto.SHA256,
+ digest[:],
+ signature,
+ ); err == nil {
+ t.Fatal(
+ "crypto/rsa verified below its own floor; the weak-key trap would find nothing",
+ )
}
if !verifyPKCS1v15Raw(&key.rsaKey.PublicKey, digest[:], signature) {
- t.Fatal("khaos's own weak signature does not verify under khaos's own arithmetic")
+ t.Fatal(
+ "khaos's own weak signature does not verify under khaos's own arithmetic",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go
index 3a9bacc0..44411405 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go
@@ -45,12 +45,21 @@ const (
errNothingToCorrupt = "%w: that token has no signature to corrupt"
)
-var ErrUnknownKeyForm = errors.New("khaos cannot serialize a public key that way")
+var ErrUnknownKeyForm = errors.New(
+ "khaos cannot serialize a public key that way",
+)
-var ErrNoSigningKey = errors.New("khaos's identity provider is missing a key a trap needs")
+var ErrNoSigningKey = errors.New(
+ "khaos's identity provider is missing a key a trap needs",
+)
func KeyForms() []string {
- return []string{string(SPKIPEM), string(SPKIDER), string(PKCS1PEM), string(Modulus)}
+ return []string{
+ string(SPKIPEM),
+ string(SPKIDER),
+ string(PKCS1PEM),
+ string(Modulus),
+ }
}
// grantRequest is what a token is minted for. The provider fills it from its own
@@ -96,6 +105,38 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {
ID: rand.Text(),
}
+ // The same three groups the confirmations in observe.go use, so a reader can
+ // put the mint and the observe for one group side by side. Each corrupts
+ // exactly ONE property and leaves the rest internally consistent, because a
+ // token that trips two checks isolates neither.
+ switch trap.Kind {
+ case AlgNone, AlgConfusion, EmbeddedJWK:
+ return p.mintHeaderTrap(trap, header, claims)
+
+ case ClaimExpired, ClaimNotYetValid, ClaimWrongAudience,
+ ClaimForeignIssuer:
+ return p.mintClaimTrap(trap, header, claims, now, request.lifetime)
+
+ case SignatureTruncated, SignatureZero, SignatureWeakKey:
+ return p.mintSignatureTrap(trap, header, claims)
+
+ default:
+ // The endpoint and key-state traps are expressed by the provider's own
+ // behaviour rather than by the token, so an HONEST token is the correct
+ // output for every one of them.
+ return p.serialize(header, claims, nil, nil)
+ }
+}
+
+// mintHeaderTrap corrupts the JOSE header and nothing else.
+//
+// This and its two siblings run under the read lock mintToken already holds, so
+// none of them may take it again.
+func (p *Provider) mintHeaderTrap(
+ trap Trap,
+ header Header,
+ claims Claims,
+) (string, error) {
switch trap.Kind {
case AlgNone:
header.Alg = string(None)
@@ -107,11 +148,16 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {
if err != nil {
return "", err
}
- return p.serialize(header, claims, nil, func(input []byte) ([]byte, error) {
- mac := hmac.New(sha256.New, secret)
- mac.Write(input)
- return mac.Sum(nil), nil
- })
+ return p.serialize(
+ header,
+ claims,
+ nil,
+ func(input []byte) ([]byte, error) {
+ mac := hmac.New(sha256.New, secret)
+ mac.Write(input)
+ return mac.Sum(nil), nil
+ },
+ )
case EmbeddedJWK:
if p.attacker == nil {
@@ -122,18 +168,34 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {
header.JWK = &embedded
return p.serialize(header, claims, p.attacker, nil)
+ default:
+ // Unreachable: mintToken routes only the header group here.
+ return p.serialize(header, claims, nil, nil)
+ }
+}
+
+// mintClaimTrap moves exactly one registered claim and leaves the signature
+// valid, so a refusal can only have come from claim validation.
+func (p *Provider) mintClaimTrap(
+ trap Trap,
+ header Header,
+ claims Claims,
+ now time.Time,
+ lifetime time.Duration,
+) (string, error) {
+ switch trap.Kind {
case ClaimExpired:
// Internally consistent on purpose: the token is expired and nothing
// else. A token that was also not-yet-valid would trip two checks and
// isolate neither.
- claims.IssuedAt = unix(now.Add(-trap.Delay - request.lifetime))
- claims.NotBefore = unix(now.Add(-trap.Delay - request.lifetime))
+ claims.IssuedAt = unix(now.Add(-trap.Delay - lifetime))
+ claims.NotBefore = unix(now.Add(-trap.Delay - lifetime))
claims.Expires = unix(now.Add(-trap.Delay))
return p.serialize(header, claims, nil, nil)
case ClaimNotYetValid:
claims.NotBefore = unix(now.Add(trap.Delay))
- claims.Expires = unix(now.Add(trap.Delay + request.lifetime))
+ claims.Expires = unix(now.Add(trap.Delay + lifetime))
return p.serialize(header, claims, nil, nil)
case ClaimWrongAudience:
@@ -152,10 +214,29 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {
header.Kid = p.foreign.ID
return p.serialize(header, claims, p.foreign, nil)
+ default:
+ // Unreachable: mintToken routes only the claim group here.
+ return p.serialize(header, claims, nil, nil)
+ }
+}
+
+// mintSignatureTrap corrupts the signature and leaves the header and every
+// claim honest, so a refusal can only have come from signature verification.
+func (p *Provider) mintSignatureTrap(
+ trap Trap,
+ header Header,
+ claims Claims,
+) (string, error) {
+ switch trap.Kind {
case SignatureTruncated:
- return p.serializeThen(header, claims, nil, func(signature []byte) []byte {
- return signature[:truncatedLength]
- })
+ return p.serializeThen(
+ header,
+ claims,
+ nil,
+ func(signature []byte) []byte {
+ return signature[:truncatedLength]
+ },
+ )
case SignatureZero:
if p.ec == nil {
@@ -175,6 +256,7 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {
return p.serialize(header, claims, p.weak, nil)
default:
+ // Unreachable: mintToken routes only the signature group here.
return p.serialize(header, claims, nil, nil)
}
}
@@ -218,7 +300,12 @@ func (p *Provider) serializeWith(
input := signingInput(headerJSON, claimsJSON)
- signature, err := p.produceSignature(Algorithm(header.Alg), input, key, signer)
+ signature, err := p.produceSignature(
+ Algorithm(header.Alg),
+ input,
+ key,
+ signer,
+ )
if err != nil {
return "", err
}
@@ -266,14 +353,18 @@ func publicKeyBytes(key *Key, form KeyForm) ([]byte, error) {
return der, nil
case SPKIPEM:
- return pem.EncodeToMemory(&pem.Block{Type: pemTypePublic, Bytes: der}), nil
+ return pem.EncodeToMemory(
+ &pem.Block{Type: pemTypePublic, Bytes: der},
+ ), nil
case PKCS1PEM:
if key.rsaKey == nil {
return nil, fmt.Errorf(errNoKey, ErrNoSigningKey, "RSA")
}
pkcs1 := x509.MarshalPKCS1PublicKey(&key.rsaKey.PublicKey)
- return pem.EncodeToMemory(&pem.Block{Type: pemTypeRSAPublic, Bytes: pkcs1}), nil
+ return pem.EncodeToMemory(
+ &pem.Block{Type: pemTypeRSAPublic, Bytes: pkcs1},
+ ), nil
case Modulus:
if key.rsaKey == nil {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go
index 218b95eb..085caa0b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go
@@ -62,7 +62,10 @@ const (
// the fix was a way to arm a fault that does not happen. Every branch below
// therefore has a control that must disagree with the fault, and `Inert` makes
// the fault not happen so a test can prove the branch says NO.
-func (p *Provider) Observe(ctx context.Context, expected Kind) (string, bool, error) {
+func (p *Provider) Observe(
+ ctx context.Context,
+ expected Kind,
+) (string, bool, error) {
select {
case <-p.closed:
return "", false, ErrClosed
@@ -76,7 +79,12 @@ func (p *Provider) Observe(ctx context.Context, expected Kind) (string, bool, er
}
if expected != "" && trap.Kind != expected {
- return "", false, fmt.Errorf(errWrongExpected, ErrTrapNotObserved, trap.Kind, expected)
+ return "", false, fmt.Errorf(
+ errWrongExpected,
+ ErrTrapNotObserved,
+ trap.Kind,
+ expected,
+ )
}
if trap.Forgery() {
@@ -100,13 +108,47 @@ func (p *Provider) observeForgery(trap Trap) (string, bool, error) {
return "", false, err
}
- published := p.PublishedSet()
- now := p.clock()
+ // Grouped by WHAT the trap corrupts, which is the split the catalogue
+ // already uses: the JOSE header, a registered claim, or the signature. Each
+ // group is confirmed the same way within itself and differently from the
+ // others, so the three read as three questions rather than one long one.
+ switch trap.Kind {
+ case AlgNone, AlgConfusion, EmbeddedJWK:
+ return p.observeHeader(trap, honest, forged)
+
+ case ClaimExpired, ClaimNotYetValid, ClaimWrongAudience,
+ ClaimForeignIssuer:
+ return p.observeClaims(trap, honest, forged)
+
+ case SignatureTruncated, SignatureZero, SignatureWeakKey:
+ return p.observeSignature(trap, honest, forged)
+
+ default:
+ // The endpoint and key-state traps are confirmed by observeEndpoint,
+ // not from the token. Everything else is deliberately left unconfirmed,
+ // which is the fail-closed direction: khaos will not measure a fault it
+ // could not see land.
+ return "", false, nil
+ }
+}
+// observeHeader confirms the traps that corrupt the JOSE header. Each is two
+// assertions, not one: the forged token says the wrong thing AND the honest
+// control says the right thing, so a provider that was never armed cannot
+// confirm its own trap.
+func (p *Provider) observeHeader(
+ trap Trap,
+ honest, forged Token,
+) (string, bool, error) {
switch trap.Kind {
case AlgNone:
- if forged.Header.Alg == string(None) && len(forged.Signature) == 0 && honest.Header.Alg != string(None) {
- return sprintf(observedAlgNone, forged.Header.Alg, honest.Header.Alg), true, nil
+ if forged.Header.Alg == string(None) && len(forged.Signature) == 0 &&
+ honest.Header.Alg != string(None) {
+ return sprintf(
+ observedAlgNone,
+ forged.Header.Alg,
+ honest.Header.Alg,
+ ), true, nil
}
case AlgConfusion:
@@ -128,58 +170,121 @@ func (p *Provider) observeForgery(trap Trap) (string, bool, error) {
}
case EmbeddedJWK:
- if forged.Header.JWK == nil || published.Has(forged.Header.JWK.Kid) {
+ if forged.Header.JWK == nil ||
+ p.PublishedSet().Has(forged.Header.JWK.Kid) {
return "", false, nil
}
if verifiesUnder(*forged.Header.JWK, forged) {
- return sprintf(observedEmbeddedJWK, forged.Header.JWK.Kid), true, nil
+ return sprintf(
+ observedEmbeddedJWK,
+ forged.Header.JWK.Kid,
+ ), true, nil
}
+ default:
+ // Unreachable: observeForgery routes only the header group here.
+ }
+
+ return "", false, nil
+}
+
+// observeClaims confirms the traps that corrupt a registered claim. Every one
+// of them first asserts that the signature still VERIFIES, because a claim trap
+// whose token also failed its signature check would be confirmed by the wrong
+// evidence and would tell khaos nothing about claim validation.
+func (p *Provider) observeClaims(
+ trap Trap,
+ honest, forged Token,
+) (string, bool, error) {
+ // Hoisted out of all four cases, which each asserted it separately. It is
+ // the precondition the whole group shares: a claim trap whose token ALSO
+ // failed its signature check would be confirmed by the wrong evidence and
+ // would tell khaos nothing about whether the target validates claims.
+ if !verifiesUnderSet(p.PublishedSet(), forged) {
+ return "", false, nil
+ }
+
+ now := p.clock()
+
+ switch trap.Kind {
case ClaimExpired:
- if forged.Claims.Expires == nil || !verifiesUnderSet(published, forged) {
+ if forged.Claims.Expires == nil {
return "", false, nil
}
expiry := time.Unix(*forged.Claims.Expires, 0)
if expiry.Before(now) {
- return sprintf(observedExpired, now.Sub(expiry).Round(time.Second)), true, nil
+ return sprintf(
+ observedExpired,
+ now.Sub(expiry).Round(time.Second),
+ ), true, nil
}
case ClaimNotYetValid:
- if forged.Claims.NotBefore == nil || !verifiesUnderSet(published, forged) {
+ if forged.Claims.NotBefore == nil {
return "", false, nil
}
start := time.Unix(*forged.Claims.NotBefore, 0)
if start.After(now) {
- return sprintf(observedNotYetValid, start.Sub(now).Round(time.Second)), true, nil
+ return sprintf(
+ observedNotYetValid,
+ start.Sub(now).Round(time.Second),
+ ), true, nil
}
case ClaimWrongAudience:
- if !verifiesUnderSet(published, forged) {
- return "", false, nil
- }
- if !forged.Claims.Audience.Contains(p.audience) && len(forged.Claims.Audience) > 0 {
- return sprintf(observedWrongAud, forged.Claims.Audience, honest.Claims.Audience), true, nil
+ if !forged.Claims.Audience.Contains(p.audience) &&
+ len(forged.Claims.Audience) > 0 {
+ return sprintf(
+ observedWrongAud,
+ forged.Claims.Audience,
+ honest.Claims.Audience,
+ ), true, nil
}
case ClaimForeignIssuer:
// The key IS published, deliberately. That is the multi-tenant shape and
// the teaching point: the key set is not the trust boundary, so the
// signature verifies and only the `iss` check can refuse it.
- if !verifiesUnderSet(published, forged) {
- return "", false, nil
- }
- if forged.Claims.Issuer != honest.Claims.Issuer && forged.Claims.Issuer != "" {
- return sprintf(observedForeignIss, forged.Claims.Issuer, honest.Claims.Issuer), true, nil
+ if forged.Claims.Issuer != honest.Claims.Issuer &&
+ forged.Claims.Issuer != "" {
+ return sprintf(
+ observedForeignIss,
+ forged.Claims.Issuer,
+ honest.Claims.Issuer,
+ ), true, nil
}
+ default:
+ // Unreachable: observeForgery routes only the claim group here.
+ }
+
+ return "", false, nil
+}
+
+// observeSignature confirms the traps that corrupt the signature itself.
+func (p *Provider) observeSignature(
+ trap Trap,
+ honest, forged Token,
+) (string, bool, error) {
+ switch trap.Kind {
case SignatureTruncated:
- if len(forged.Signature) == truncatedLength && len(honest.Signature) > truncatedLength {
- return sprintf(observedTruncated, len(forged.Signature), len(honest.Signature)), true, nil
+ if len(forged.Signature) == truncatedLength &&
+ len(honest.Signature) > truncatedLength {
+ return sprintf(
+ observedTruncated,
+ len(forged.Signature),
+ len(honest.Signature),
+ ), true, nil
}
case SignatureZero:
- if forged.Header.Alg == string(ES256) && len(forged.Signature) > 0 && allZero(forged.Signature) {
- return sprintf(observedZero, forged.Header.Alg, len(forged.Signature)), true, nil
+ if forged.Header.Alg == string(ES256) && len(forged.Signature) > 0 &&
+ allZero(forged.Signature) {
+ return sprintf(
+ observedZero,
+ forged.Header.Alg,
+ len(forged.Signature),
+ ), true, nil
}
case SignatureWeakKey:
@@ -193,23 +298,37 @@ func (p *Provider) observeForgery(trap Trap) (string, bool, error) {
// claim that a correct verifier cannot accept this token would be false
// in that environment, and the trap declines to confirm rather than
// asserting it anyway.
- key, err := published.Lookup(forged.Header.Kid)
+ //
+ // A confirmation that cannot be MADE is not an error either. The returns
+ // below report "not confirmed" and let the engine refuse the run, which
+ // is the fail-closed answer. Returning the lookup error instead would
+ // make khaos abort with a key-management complaint when the honest
+ // reading is "khaos could not see this fault land".
+ key, err := p.PublishedSet().Lookup(forged.Header.Kid)
if err != nil {
- return "", false, nil
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
}
pub, err := key.RSAPublicKey()
if err != nil {
- return "", false, nil
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
}
if pub.N.BitLen() >= libraryFloorBits {
return "", false, nil
}
digest := sha256.Sum256(forged.SigningInput)
- libraryRefuses := rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], forged.Signature) != nil
+ libraryRefuses := rsa.VerifyPKCS1v15(
+ pub,
+ crypto.SHA256,
+ digest[:],
+ forged.Signature,
+ ) != nil
khaosAccepts := verifyPKCS1v15Raw(pub, digest[:], forged.Signature)
if libraryRefuses && khaosAccepts {
return sprintf(observedWeakKey, pub.N.BitLen()), true, nil
}
+
+ default:
+ // Unreachable: observeForgery routes only the signature group here.
}
return "", false, nil
@@ -231,7 +350,10 @@ func (p *Provider) mintTrappedForControl() (Token, error) {
}
func (p *Provider) parseMint(trap Trap) (Token, error) {
- raw, err := p.mintToken(trap, grantRequest{subject: DefaultSubject, lifetime: p.lifetime})
+ raw, err := p.mintToken(
+ trap,
+ grantRequest{subject: DefaultSubject, lifetime: p.lifetime},
+ )
if err != nil {
return Token{}, err
}
@@ -254,7 +376,10 @@ func (p *Provider) confusionSecret(form KeyForm) ([]byte, error) {
// surface, with the health route as the control: it is never faulted, so an
// unhealthy control means khaos's provider is broken rather than lying and
// nothing seen elsewhere can be attributed to the trap.
-func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool, error) {
+func (p *Provider) observeEndpoint(
+ ctx context.Context,
+ trap Trap,
+) (string, bool, error) {
base, err := p.Addr()
if err != nil {
return "", false, fmt.Errorf(errNoListener, ErrTrapNotObserved)
@@ -265,15 +390,60 @@ func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool
healthStatus, healthTook, err := probeRoute(ctx, client, root+RouteHealth)
if err != nil || healthStatus != http.StatusOK {
- return "", false, fmt.Errorf(errProviderDown, ErrTrapNotObserved, orStatus(err, healthStatus))
+ return "", false, fmt.Errorf(
+ errProviderDown,
+ ErrTrapNotObserved,
+ orStatus(err, healthStatus),
+ )
+ }
+
+ at := probeAt{
+ client: client,
+ root: root,
+ healthStatus: healthStatus,
+ healthTook: healthTook,
}
+ switch trap.Kind {
+ case JWKSUnreachable, KidRollover, KeyRotation:
+ return p.observeKeySet(ctx, trap, at)
+
+ case IntrospectionError, IntrospectionMalformed, IntrospectionSlow,
+ Revoke:
+ return p.observeIntrospection(ctx, trap, at)
+
+ default:
+ // The token traps are confirmed against the minted token, not against
+ // the endpoint. Leaving them unconfirmed here is the fail-closed answer.
+ return "", false, nil
+ }
+}
+
+// probeAt is the measurement context both endpoint groups need: where to reach
+// the provider, a client whose timeout already accounts for the trap's own
+// delay, and what the health route answered. The health route is never faulted,
+// which is what makes it the control every confirmation below measures against
+// rather than a threshold someone picked.
+type probeAt struct {
+ client *http.Client
+ root string
+ healthStatus int
+ healthTook time.Duration
+}
+
+// observeKeySet confirms the traps that act on the PUBLISHED KEY SET rather
+// than on a token: the set going away, and a key leaving or joining it.
+func (p *Provider) observeKeySet(
+ ctx context.Context,
+ trap Trap,
+ at probeAt,
+) (string, bool, error) {
switch trap.Kind {
case JWKSUnreachable:
p.ownFetches.Add(1)
- status, _, err := probeRoute(ctx, client, root+RouteJWKS)
+ status, _, err := probeRoute(ctx, at.client, at.root+RouteJWKS)
if err == nil && status != http.StatusOK {
- return sprintf(observedJWKSGone, healthStatus, status), true, nil
+ return sprintf(observedJWKSGone, at.healthStatus, status), true, nil
}
case KidRollover:
@@ -281,7 +451,7 @@ func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool
if !ok {
return "", false, nil
}
- set, err := p.fetchSet(ctx, client, root+RouteJWKS)
+ set, err := p.fetchSet(ctx, at.client, at.root+RouteJWKS)
if err != nil {
return "", false, err
}
@@ -304,11 +474,12 @@ func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool
if !ok {
return "", false, nil
}
- set, err := p.fetchSet(ctx, client, root+RouteJWKS)
+ set, err := p.fetchSet(ctx, at.client, at.root+RouteJWKS)
if err != nil {
return "", false, err
}
- if retired == p.SigningKid() || !set.Has(retired) || !set.Has(p.SigningKid()) {
+ if retired == p.SigningKid() || !set.Has(retired) ||
+ !set.Has(p.SigningKid()) {
return "", false, nil
}
// The three assertions above are the live ones, and the first carries the
@@ -325,16 +496,50 @@ func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool
return "", false, err
}
- return sprintf(observedRotation, retired, p.SigningKid(), minted.Header.Kid), true, nil
+ return sprintf(
+ observedRotation,
+ retired,
+ p.SigningKid(),
+ minted.Header.Kid,
+ ), true, nil
+ default:
+ // Unreachable: observeEndpoint routes only the key-set group here.
+ }
+
+ return "", false, nil
+}
+
+// observeIntrospection confirms the traps that act on the introspection
+// endpoint, which is how a target asks about a credential it cannot verify
+// locally. Each one needs its own control, because "inactive" and "no answer"
+// are also what a provider khaos had broken by accident would say.
+func (p *Provider) observeIntrospection(
+ ctx context.Context,
+ trap Trap,
+ at probeAt,
+) (string, bool, error) {
+ switch trap.Kind {
case IntrospectionError:
- status, _, err := probeRoute(ctx, client, p.introspectURL(root, p.Opaque()))
+ status, _, err := probeRoute(
+ ctx,
+ at.client,
+ p.introspectURL(at.root, p.Opaque()),
+ )
if err == nil && status != http.StatusOK {
- return sprintf(observedIntroError, healthStatus, status), true, nil
+ return sprintf(
+ observedIntroError,
+ at.healthStatus,
+ status,
+ ), true, nil
}
case IntrospectionMalformed:
- status, body, err := readRoute(ctx, client, p.introspectURL(root, p.Opaque()))
+ status, body, err := readRoute(
+ ctx,
+ at.client,
+ p.introspectURL(at.root, p.Opaque()),
+ )
if err != nil {
return "", false, err
}
@@ -343,45 +548,76 @@ func (p *Provider) observeEndpoint(ctx context.Context, trap Trap) (string, bool
}
case IntrospectionSlow:
- status, took, err := probeRoute(ctx, client, p.introspectURL(root, p.Opaque()))
+ status, took, err := probeRoute(
+ ctx,
+ at.client,
+ p.introspectURL(at.root, p.Opaque()),
+ )
if err != nil || status != http.StatusOK {
- return "", false, nil
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
}
// A differential, not a threshold. The health route is the control and it
// is never faulted, so the comparison separates khaos's own hold from a
// generally slow machine.
- if took-healthTook >= slack(trap.Delay) {
- return sprintf(observedIntroSlow, took.Round(time.Millisecond), healthTook.Round(time.Millisecond)), true, nil
+ if took-at.healthTook >= slack(trap.Delay) {
+ return sprintf(
+ observedIntroSlow,
+ took.Round(time.Millisecond),
+ at.healthTook.Round(time.Millisecond),
+ ), true, nil
}
case Revoke:
- // A control credential, issued now and never revoked. Without it,
- // "inactive" is also what a provider that lost every grant would say, and
- // the finding would be khaos's own bug reported as the target's.
- control := p.Opaque()
+ return p.observeRevocation(ctx, trap, at)
- revoked, err := fetchIntrospection(ctx, client, p.introspectURL(root, trap.Credential))
- if err != nil {
- return "", false, err
- }
+ default:
+ // Unreachable: observeEndpoint routes only the introspection group here.
+ }
- alive, err := fetchIntrospection(ctx, client, p.introspectURL(root, control))
- if err != nil {
- return "", false, err
- }
+ return "", false, nil
+}
- if !revoked.Active && alive.Active {
- return observedRevoked, true, nil
- }
+// observeRevocation is the only endpoint confirmation that needs TWO reads, so
+// it is the only one that can tell a revoked credential from a provider that
+// lost every grant it ever issued.
+func (p *Provider) observeRevocation(
+ ctx context.Context,
+ trap Trap,
+ at probeAt,
+) (string, bool, error) {
+ // A control credential, issued now and never revoked. Without it,
+ // "inactive" is also what a provider that lost every grant would say, and
+ // the finding would be khaos's own bug reported as the target's.
+ control := p.Opaque()
+
+ revoked, err := fetchIntrospection(
+ ctx,
+ at.client,
+ p.introspectURL(at.root, trap.Credential),
+ )
+ if err != nil {
+ return "", false, err
+ }
+
+ alive, err := fetchIntrospection(
+ ctx,
+ at.client,
+ p.introspectURL(at.root, control),
+ )
+ if err != nil {
+ return "", false, err
+ }
+
+ if !revoked.Active && alive.Active {
+ return observedRevoked, true, nil
}
return "", false, nil
}
// introspectURL records the call as khaos's own, so the exported count stays a
-// measurement of the TARGET's behaviour. Every caller of this is a confirmation
-// probe.
-// introspectURL is khaos's own read-back path. It keeps the query form on
+// measurement of the TARGET's behaviour: every caller of this is a confirmation
+// probe. It keeps the query form on
// purpose: these probes exist to observe the endpoint's BEHAVIOUR, and reading
// the token the same way a conforming client does is the fixture's job to prove,
// not the oracle's. The contract test covers the specified wire format directly.
@@ -390,7 +626,11 @@ func (p *Provider) introspectURL(root, credential string) string {
return root + RouteIntrospect + "?" + ParamToken + "=" + credential
}
-func probeRoute(ctx context.Context, client *http.Client, url string) (int, time.Duration, error) {
+func probeRoute(
+ ctx context.Context,
+ client *http.Client,
+ url string,
+) (int, time.Duration, error) {
started := time.Now()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
@@ -409,7 +649,11 @@ func probeRoute(ctx context.Context, client *http.Client, url string) (int, time
return response.StatusCode, time.Since(started), nil
}
-func readRoute(ctx context.Context, client *http.Client, url string) (int, []byte, error) {
+func readRoute(
+ ctx context.Context,
+ client *http.Client,
+ url string,
+) (int, []byte, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, nil, err
@@ -431,12 +675,20 @@ func readRoute(ctx context.Context, client *http.Client, url string) (int, []byt
// fetchSet is khaos's own read-back of the key set, so it records the fetch as
// khaos's and the exported count stays a measurement of the TARGET's behaviour.
-func (p *Provider) fetchSet(ctx context.Context, client *http.Client, url string) (JWKSet, error) {
+func (p *Provider) fetchSet(
+ ctx context.Context,
+ client *http.Client,
+ url string,
+) (JWKSet, error) {
p.ownFetches.Add(1)
return fetchSet(ctx, client, url)
}
-func fetchSet(ctx context.Context, client *http.Client, url string) (JWKSet, error) {
+func fetchSet(
+ ctx context.Context,
+ client *http.Client,
+ url string,
+) (JWKSet, error) {
status, body, err := readRoute(ctx, client, url)
if err != nil {
return JWKSet{}, err
@@ -449,14 +701,22 @@ func fetchSet(ctx context.Context, client *http.Client, url string) (JWKSet, err
return ParseJWKSet(body)
}
-func fetchIntrospection(ctx context.Context, client *http.Client, url string) (Introspection, error) {
+func fetchIntrospection(
+ ctx context.Context,
+ client *http.Client,
+ url string,
+) (Introspection, error) {
status, body, err := readRoute(ctx, client, url)
if err != nil {
return Introspection{}, err
}
if status != http.StatusOK {
- return Introspection{}, fmt.Errorf(errProviderDown, ErrTrapNotObserved, status)
+ return Introspection{}, fmt.Errorf(
+ errProviderDown,
+ ErrTrapNotObserved,
+ status,
+ )
}
var out Introspection
@@ -490,7 +750,12 @@ func verifiesUnder(key JWK, token Token) bool {
if pub.N.BitLen() < libraryFloorBits {
return verifyPKCS1v15Raw(pub, digest[:], token.Signature)
}
- return rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], token.Signature) == nil
+ return rsa.VerifyPKCS1v15(
+ pub,
+ crypto.SHA256,
+ digest[:],
+ token.Signature,
+ ) == nil
case ES256:
pub, err := key.ECPublicKey()
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe_test.go
index 23768470..5ca27ace 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe_test.go
@@ -71,8 +71,11 @@ func TestEveryTrapIsConfirmedByItsOwnObservable(t *testing.T) {
cases := everyTrap()
if len(cases) != len(Kinds()) {
- t.Fatalf("this test covers %d traps and khaos advertises %d; a new trap needs a case here",
- len(cases), len(Kinds()))
+ t.Fatalf(
+ "this test covers %d traps and khaos advertises %d; a new trap needs a case here",
+ len(cases),
+ len(Kinds()),
+ )
}
for _, each := range cases {
@@ -85,17 +88,26 @@ func TestEveryTrapIsConfirmedByItsOwnObservable(t *testing.T) {
t.Fatalf("arm %s: %v", each.kind, err)
}
- observable, confirmed, err := p.Observe(context.Background(), each.kind)
+ observable, confirmed, err := p.Observe(
+ context.Background(),
+ each.kind,
+ )
if err != nil {
t.Fatalf("observe %s: %v", each.kind, err)
}
if !confirmed {
- t.Fatalf("%s was armed and its own observable did not appear", each.kind)
+ t.Fatalf(
+ "%s was armed and its own observable did not appear",
+ each.kind,
+ )
}
if observable == "" {
- t.Fatalf("%s confirmed with no observable; the run record would carry no evidence", each.kind)
+ t.Fatalf(
+ "%s confirmed with no observable; the run record would carry no evidence",
+ each.kind,
+ )
}
})
}
@@ -123,7 +135,10 @@ func TestEveryTrapRefusesConfirmationWhenItDidNotHappen(t *testing.T) {
_, confirmed, _ := p.Observe(context.Background(), each.kind)
if confirmed {
- t.Fatalf("%s confirmed itself while inert, so its oracle cannot tell a landed trap from one that did nothing", each.kind)
+ t.Fatalf(
+ "%s confirmed itself while inert, so its oracle cannot tell a landed trap from one that did nothing",
+ each.kind,
+ )
}
})
}
@@ -132,8 +147,16 @@ func TestEveryTrapRefusesConfirmationWhenItDidNotHappen(t *testing.T) {
func TestObserveRefusesWhenNothingIsArmed(t *testing.T) {
p := listening(t)
- if _, confirmed, err := p.Observe(context.Background(), AlgNone); confirmed || err == nil {
- t.Fatalf("an unarmed provider confirmed a trap: confirmed=%v err=%v", confirmed, err)
+ if _, confirmed, err := p.Observe(
+ context.Background(),
+ AlgNone,
+ ); confirmed ||
+ err == nil {
+ t.Fatalf(
+ "an unarmed provider confirmed a trap: confirmed=%v err=%v",
+ confirmed,
+ err,
+ )
}
}
@@ -144,8 +167,16 @@ func TestObserveRefusesADifferentTrapThanTheOneArmed(t *testing.T) {
t.Fatalf("arm: %v", err)
}
- if _, confirmed, err := p.Observe(context.Background(), SignatureTruncated); confirmed || err == nil {
- t.Fatalf("the provider confirmed %s while holding %s", SignatureTruncated, AlgNone)
+ if _, confirmed, err := p.Observe(
+ context.Background(),
+ SignatureTruncated,
+ ); confirmed ||
+ err == nil {
+ t.Fatalf(
+ "the provider confirmed %s while holding %s",
+ SignatureTruncated,
+ AlgNone,
+ )
}
}
@@ -173,7 +204,11 @@ func TestDisarmRestoresTheSigningKeyARotationReplaced(t *testing.T) {
p.Disarm()
if p.SigningKid() != before {
- t.Fatalf("after disarm the signing key is %q, want the original %q", p.SigningKid(), before)
+ t.Fatalf(
+ "after disarm the signing key is %q, want the original %q",
+ p.SigningKid(),
+ before,
+ )
}
if !p.PublishedSet().Has(before) {
@@ -197,7 +232,9 @@ func TestDisarmRestoresARevokedGrant(t *testing.T) {
p.Disarm()
if active := p.active(t, credential); !active {
- t.Fatal("disarm did not restore the revoked grant, so recovery cannot be measured")
+ t.Fatal(
+ "disarm did not restore the revoked grant, so recovery cannot be measured",
+ )
}
}
@@ -234,7 +271,9 @@ func TestRotationWithOverlapKeepsBothKeysPublished(t *testing.T) {
func TestArmRefusesToRevokeACredentialItNeverIssued(t *testing.T) {
p := listening(t)
- if err := p.Arm(Trap{Kind: Revoke, Credential: "khaos-opaque-never-issued"}); err == nil {
+ if err := p.Arm(
+ Trap{Kind: Revoke, Credential: "khaos-opaque-never-issued"},
+ ); err == nil {
t.Fatal("the provider revoked a credential it never issued")
}
}
@@ -269,14 +308,21 @@ func TestAnUnarmedProviderMintsOnlyCorrectTokens(t *testing.T) {
}
if !token.Claims.Audience.Contains(DefaultAudience) {
- t.Errorf("aud is %q, want %q", token.Claims.Audience, DefaultAudience)
+ t.Errorf(
+ "aud is %q, want %q",
+ token.Claims.Audience,
+ DefaultAudience,
+ )
}
if !verifiesUnderSet(p.PublishedSet(), token) {
- t.Error("an unarmed provider minted a token that does not verify under its own published keys")
+ t.Error(
+ "an unarmed provider minted a token that does not verify under its own published keys",
+ )
}
- if token.Claims.Expires == nil || time.Unix(*token.Claims.Expires, 0).Before(time.Now()) {
+ if token.Claims.Expires == nil ||
+ time.Unix(*token.Claims.Expires, 0).Before(time.Now()) {
t.Error("an unarmed provider minted an already-expired token")
}
}
@@ -309,8 +355,14 @@ func TestHonestTokenIgnoresEveryArmedForgery(t *testing.T) {
t.Fatalf("parse under %s: %v", each.kind, err)
}
- if token.Header.Alg != string(RS256) || token.Claims.Issuer != testIssuer {
- t.Errorf("%s leaked into the honest token: alg=%q iss=%q", each.kind, token.Header.Alg, token.Claims.Issuer)
+ if token.Header.Alg != string(RS256) ||
+ token.Claims.Issuer != testIssuer {
+ t.Errorf(
+ "%s leaked into the honest token: alg=%q iss=%q",
+ each.kind,
+ token.Header.Alg,
+ token.Claims.Issuer,
+ )
}
if !verifiesUnderSet(p.PublishedSet(), token) {
@@ -346,11 +398,15 @@ func TestTheAttackerKeyIsNeverPublished(t *testing.T) {
}
if p.PublishedSet().Has(token.Header.JWK.Kid) {
- t.Fatal("khaos published the attacker key, so resolving it would be correct behaviour")
+ t.Fatal(
+ "khaos published the attacker key, so resolving it would be correct behaviour",
+ )
}
if !verifiesUnder(*token.Header.JWK, token) {
- t.Fatal("the embedded key does not verify the token it is embedded in, so no verifier could accept it for the reason the trap claims")
+ t.Fatal(
+ "the embedded key does not verify the token it is embedded in, so no verifier could accept it for the reason the trap claims",
+ )
}
}
@@ -365,7 +421,11 @@ func TestJWKSFetchesAreCounted(t *testing.T) {
before := p.JWKSFetches()
for range 3 {
- if _, _, err := probeRoute(context.Background(), httpClient(), "http://"+addr+RouteJWKS); err != nil {
+ if _, _, err := probeRoute(
+ context.Background(),
+ httpClient(),
+ "http://"+addr+RouteJWKS,
+ ); err != nil {
t.Fatalf("fetch: %v", err)
}
}
@@ -391,7 +451,11 @@ func TestHealthIsNeverFaulted(t *testing.T) {
t.Fatalf("addr: %v", err)
}
- status, _, err := probeRoute(context.Background(), httpClient(), "http://"+addr+RouteHealth)
+ status, _, err := probeRoute(
+ context.Background(),
+ httpClient(),
+ "http://"+addr+RouteHealth,
+ )
if err != nil || status != 200 {
t.Fatalf("health answered %d (%v) with %s armed", status, err, kind)
}
@@ -430,7 +494,12 @@ func TestListenDoesNotOverwriteAPinnedIssuer(t *testing.T) {
}
if p.Issuer() != testIssuer {
- t.Fatalf("after binding on %s the issuer is %q, want the pinned %q", addr, p.Issuer(), testIssuer)
+ t.Fatalf(
+ "after binding on %s the issuer is %q, want the pinned %q",
+ addr,
+ p.Issuer(),
+ testIssuer,
+ )
}
raw, err := p.HonestToken()
@@ -444,8 +513,12 @@ func TestListenDoesNotOverwriteAPinnedIssuer(t *testing.T) {
}
if token.Claims.Issuer != testIssuer {
- t.Fatalf("the minted token says iss %q, want the pinned %q; a target configured for "+
- "the pinned issuer refuses this and the run blames the target", token.Claims.Issuer, testIssuer)
+ t.Fatalf(
+ "the minted token says iss %q, want the pinned %q; a target configured for "+
+ "the pinned issuer refuses this and the run blames the target",
+ token.Claims.Issuer,
+ testIssuer,
+ )
}
}
@@ -459,7 +532,10 @@ func TestAnUnpinnedProviderNamesItselfAfterBinding(t *testing.T) {
t.Cleanup(func() { _ = p.Close() })
if p.Issuer() != "" {
- t.Fatalf("an unbound, unpinned provider claims the issuer %q", p.Issuer())
+ t.Fatalf(
+ "an unbound, unpinned provider claims the issuer %q",
+ p.Issuer(),
+ )
}
if err := p.Listen("127.0.0.1:0"); err != nil {
@@ -491,13 +567,22 @@ func TestKhaosOwnConfirmationDoesNotInflateTheFetchCount(t *testing.T) {
t.Fatalf("arm: %v", err)
}
- if _, confirmed, err := p.Observe(context.Background(), kind); err != nil || !confirmed {
+ if _, confirmed, err := p.Observe(
+ context.Background(),
+ kind,
+ ); err != nil ||
+ !confirmed {
t.Fatalf("confirm said %v (%v)", confirmed, err)
}
if after := p.JWKSFetches(); after != before {
- t.Fatalf("confirming %s moved the reported fetch count from %d to %d; the number has "+
- "to describe the TARGET's refetch behaviour, not khaos's own probing", kind, before, after)
+ t.Fatalf(
+ "confirming %s moved the reported fetch count from %d to %d; the number has "+
+ "to describe the TARGET's refetch behaviour, not khaos's own probing",
+ kind,
+ before,
+ after,
+ )
}
})
}
@@ -516,20 +601,31 @@ func TestATargetsFetchIsStillCounted(t *testing.T) {
t.Fatalf("arm: %v", err)
}
- if _, confirmed, err := p.Observe(context.Background(), KidRollover); err != nil || !confirmed {
+ if _, confirmed, err := p.Observe(
+ context.Background(),
+ KidRollover,
+ ); err != nil ||
+ !confirmed {
t.Fatalf("confirm said %v (%v)", confirmed, err)
}
before := p.JWKSFetches()
for range 4 {
- if _, _, err := probeRoute(context.Background(), httpClient(), "http://"+addr+RouteJWKS); err != nil {
+ if _, _, err := probeRoute(
+ context.Background(),
+ httpClient(),
+ "http://"+addr+RouteJWKS,
+ ); err != nil {
t.Fatalf("fetch: %v", err)
}
}
if got := p.JWKSFetches() - before; got != 4 {
- t.Fatalf("counted %d target fetches, want 4; the correction is swallowing real ones", got)
+ t.Fatalf(
+ "counted %d target fetches, want 4; the correction is swallowing real ones",
+ got,
+ )
}
}
@@ -574,8 +670,10 @@ func TestIntrospectionAnswersTheWireFormatTheRFCSpecifies(t *testing.T) {
}
if body := post(); !body.Active {
- t.Fatal("a form-encoded POST for an active credential reported it inactive; no conforming " +
- "client can establish a baseline against this provider")
+ t.Fatal(
+ "a form-encoded POST for an active credential reported it inactive; no conforming " +
+ "client can establish a baseline against this provider",
+ )
}
if err := p.Arm(Trap{Kind: Revoke, Credential: credential}); err != nil {
@@ -605,8 +703,10 @@ func TestRevocationAcceptsTheFormEncodedPost(t *testing.T) {
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
- t.Fatalf("a form-encoded revocation answered %d, so a conforming client cannot revoke",
- response.StatusCode)
+ t.Fatalf(
+ "a form-encoded revocation answered %d, so a conforming client cannot revoke",
+ response.StatusCode,
+ )
}
if p.active(t, credential) {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go
index 8d337eeb..b7e560ab 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go
@@ -66,7 +66,9 @@ var ErrClosed = errors.New("khaos's identity provider is closed")
var ErrNothingToRevoke = errors.New("khaos has no credential to revoke")
-var ErrTrapNotObserved = errors.New("the armed trap did not produce its own observable")
+var ErrTrapNotObserved = errors.New(
+ "the armed trap did not produce its own observable",
+)
var ErrNoSuchGrant = errors.New("that credential was never issued here")
@@ -264,7 +266,11 @@ func (p *Provider) Listen(addr string) error {
defer p.mu.Unlock()
if p.listener != nil {
- return fmt.Errorf(errAlreadyListening, ErrListening, p.listener.Addr().String())
+ return fmt.Errorf(
+ errAlreadyListening,
+ ErrListening,
+ p.listener.Addr().String(),
+ )
}
listener, err := net.Listen("tcp", addr)
@@ -395,6 +401,9 @@ func (p *Provider) Arm(trap Trap) error {
if err := p.revoke(trap.Credential); err != nil {
return err
}
+ default:
+ // The token traps hold no provider state. They are expressed when a
+ // token is minted, so arming them is just recording the trap.
}
}
@@ -406,7 +415,6 @@ func (p *Provider) Arm(trap Trap) error {
// snap records the key state as it stands now, once per arming cycle. Disarm
// restores it and clears it, so a second arming snapshots afresh.
-// snap records the key state as it stands now. Disarm restores it and clears it.
//
// It OVERWRITES rather than keeping the first snapshot. The previous version
// returned early when one existed, so a second Arm without an intervening
@@ -419,7 +427,10 @@ func (p *Provider) snap() {
p.mu.Lock()
defer p.mu.Unlock()
- p.snapshot = &keySnapshot{signing: p.signing, retired: append([]*Key{}, p.retired...)}
+ p.snapshot = &keySnapshot{
+ signing: p.signing,
+ retired: append([]*Key{}, p.retired...),
+ }
}
// RetiredKid is the key that was signing before the current arming cycle. The
@@ -536,7 +547,10 @@ func (p *Provider) restoreGrants() {
// carries it, and a stream that drifted into carrying forged tokens would make
// every verdict read as a crash.
func (p *Provider) HonestToken() (string, error) {
- return p.mintToken(Trap{}, grantRequest{subject: DefaultSubject, lifetime: p.lifetime})
+ return p.mintToken(
+ Trap{},
+ grantRequest{subject: DefaultSubject, lifetime: p.lifetime},
+ )
}
// TrappedToken honours whatever is armed. It is what the forged stream carries,
@@ -544,7 +558,10 @@ func (p *Provider) HonestToken() (string, error) {
// there the question is whether the target accepts a correctly signed token under
// the provider's new key.
func (p *Provider) TrappedToken() (string, error) {
- return p.mintToken(p.effective(), grantRequest{subject: DefaultSubject, lifetime: p.lifetime})
+ return p.mintToken(
+ p.effective(),
+ grantRequest{subject: DefaultSubject, lifetime: p.lifetime},
+ )
}
// StableToken is a correct JWT signed by a key that is always published and
@@ -622,8 +639,13 @@ func (p *Provider) PublishedSet() JWKSet {
set.Keys = append(set.Keys, key.PublicJWK())
}
- set.Keys = append(set.Keys,
- p.foreign.PublicJWK(), p.stable.PublicJWK(), p.weak.PublicJWK(), p.ec.PublicJWK())
+ set.Keys = append(
+ set.Keys,
+ p.foreign.PublicJWK(),
+ p.stable.PublicJWK(),
+ p.weak.PublicJWK(),
+ p.ec.PublicJWK(),
+ )
return set
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go
index ccfd7cec..ba739fda 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go
@@ -95,7 +95,11 @@ func (p *Provider) jwks(w http.ResponseWriter, _ *http.Request) {
func (p *Provider) token(w http.ResponseWriter, _ *http.Request) {
minted, err := p.TrappedToken()
if err != nil {
- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ writeJSON(
+ w,
+ http.StatusInternalServerError,
+ map[string]string{"error": err.Error()},
+ )
return
}
@@ -138,6 +142,12 @@ func (p *Provider) introspect(w http.ResponseWriter, r *http.Request) {
case <-p.closed:
return
}
+
+ default:
+ // Every other trap leaves introspection alone and the honest answer
+ // below is returned. A token trap that broke this endpoint too would
+ // give the target two reasons to refuse and khaos one it cannot
+ // attribute.
}
credential := credentialFrom(r)
@@ -167,7 +177,11 @@ func (p *Provider) revokeRoute(w http.ResponseWriter, r *http.Request) {
credential := credentialFrom(r)
if err := p.revoke(credential); err != nil {
- writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
+ writeJSON(
+ w,
+ http.StatusNotFound,
+ map[string]string{"error": err.Error()},
+ )
return
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go
index 8b934b7f..377a5434 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go
@@ -139,7 +139,13 @@ type Token struct {
// header and claims so a trap can corrupt either one before signing, and it
// takes the signature as bytes so a trap can replace it after signing.
func assemble(headerJSON, claimsJSON, signature []byte) string {
- return b64(headerJSON) + segmentSep + b64(claimsJSON) + segmentSep + b64(signature)
+ return b64(
+ headerJSON,
+ ) + segmentSep + b64(
+ claimsJSON,
+ ) + segmentSep + b64(
+ signature,
+ )
}
func signingInput(headerJSON, claimsJSON []byte) []byte {
@@ -152,7 +158,12 @@ func signingInput(headerJSON, claimsJSON []byte) []byte {
func Parse(raw string) (Token, error) {
parts := strings.Split(raw, segmentSep)
if len(parts) != jwsSegments {
- return Token{}, fmt.Errorf(errSegments, ErrNotAJWS, jwsSegments, len(parts))
+ return Token{}, fmt.Errorf(
+ errSegments,
+ ErrNotAJWS,
+ jwsSegments,
+ len(parts),
+ )
}
headerJSON, err := decodeSegment(parts[0])
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go
index 737bc9ed..8ccfa375 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go
@@ -161,6 +161,8 @@ func (t Trap) Validate() error {
return fmt.Errorf(errUnknownKeyForm, ErrUnknownKeyForm,
t.KeyForm, SPKIPEM, SPKIDER, PKCS1PEM, Modulus)
}
+ default:
+ // The remaining traps carry no parameter to validate.
}
if t.Kind != PassThrough && !slices.Contains(Kinds(), string(t.Kind)) {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go
index f3248ca3..9c0be650 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go
@@ -23,9 +23,13 @@ const (
describeIdP = "%s, at khaos's own identity provider, which holds no capabilities and serves nothing but the target under test"
)
-var ErrNoIdP = errors.New("this mutation needs khaos's identity provider, which is not running")
+var ErrNoIdP = errors.New(
+ "this mutation needs khaos's identity provider, which is not running",
+)
-var ErrTrapMismatch = errors.New("the armed trap does not match the mutation being applied")
+var ErrTrapMismatch = errors.New(
+ "the armed trap does not match the mutation being applied",
+)
// IdPKind names the mutation that arms one trap on khaos's identity provider.
// The trap kinds and the mutation kinds are one-to-one, so `khaos catalog` names
@@ -69,13 +73,22 @@ func (m idpMutator) Describe(env Env, target dockerx.Target) string {
// the experiment is built, so the trap travels without it and picks it up here.
// Inject runs after the baseline, by which time the credential exists and the
// target has been honouring it, which is exactly the state the finding needs.
-func (m idpMutator) Plan(_ context.Context, env Env, _ dockerx.Target) (json.RawMessage, error) {
+func (m idpMutator) Plan(
+ _ context.Context,
+ env Env,
+ _ dockerx.Target,
+) (json.RawMessage, error) {
if env.IdP == nil {
return nil, fmt.Errorf(errNoIdP, ErrNoIdP, IdPKind(m.kind))
}
if env.IdPTrap.Kind != m.kind {
- return nil, fmt.Errorf(errWrongTrapKind, ErrTrapMismatch, env.IdPTrap.Kind, m.kind)
+ return nil, fmt.Errorf(
+ errWrongTrapKind,
+ ErrTrapMismatch,
+ env.IdPTrap.Kind,
+ m.kind,
+ )
}
trap := env.IdPTrap
@@ -95,7 +108,12 @@ func (m idpMutator) Plan(_ context.Context, env Env, _ dockerx.Target) (json.Raw
return journal.EncodePayload(trap)
}
-func (m idpMutator) Apply(_ context.Context, env Env, _ dockerx.Target, raw json.RawMessage) error {
+func (m idpMutator) Apply(
+ _ context.Context,
+ env Env,
+ _ dockerx.Target,
+ raw json.RawMessage,
+) error {
if env.IdP == nil {
return fmt.Errorf(errNoIdP, ErrNoIdP, IdPKind(m.kind))
}
@@ -130,7 +148,11 @@ func (m idpMutator) Revert(_ context.Context, env Env, _ journal.Record) error {
// set: a flag records which branch was chosen, not what a verifier would
// actually receive, and a provider whose minting broke would confirm a trap it
// is not producing.
-func (m idpMutator) Confirm(ctx context.Context, env Env, _ dockerx.Target) (string, bool, error) {
+func (m idpMutator) Confirm(
+ ctx context.Context,
+ env Env,
+ _ dockerx.Target,
+) (string, bool, error) {
if env.IdP == nil {
return "", false, fmt.Errorf(errNoIdP, ErrNoIdP, IdPKind(m.kind))
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault_test.go
index 071e54a3..7cb8882b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault_test.go
@@ -56,7 +56,11 @@ func TestEveryIdentityTrapAppliesConfirmsAndReverts(t *testing.T) {
}
if registered != len(all) {
- t.Fatalf("this test covers %d identity traps but %d are registered", len(all), registered)
+ t.Fatalf(
+ "this test covers %d identity traps but %d are registered",
+ len(all),
+ registered,
+ )
}
ctx := context.Background()
@@ -71,7 +75,13 @@ func TestEveryIdentityTrapAppliesConfirmsAndReverts(t *testing.T) {
t.Fatalf("lookup: %v", err)
}
- if describe := mutator.Describe(env, target); !strings.Contains(describe, target.Name) {
+ if describe := mutator.Describe(
+ env,
+ target,
+ ); !strings.Contains(
+ describe,
+ target.Name,
+ ) {
t.Errorf("the plan line does not name the target: %s", describe)
}
@@ -86,11 +96,18 @@ func TestEveryIdentityTrapAppliesConfirmsAndReverts(t *testing.T) {
observable, confirmed, err := mutator.Confirm(ctx, env, target)
if err != nil || !confirmed {
- t.Fatalf("confirm said %v (%v) with %s armed", confirmed, err, trap.Kind)
+ t.Fatalf(
+ "confirm said %v (%v) with %s armed",
+ confirmed,
+ err,
+ trap.Kind,
+ )
}
if observable == "" {
- t.Fatal("confirmed with no observable, so the run record would carry no evidence")
+ t.Fatal(
+ "confirmed with no observable, so the run record would carry no evidence",
+ )
}
if err := mutator.Revert(ctx, env, journal.Record{}); err != nil {
@@ -118,7 +135,11 @@ func TestTheJournalledTrapRoundTrips(t *testing.T) {
t.Fatalf("lookup %s: %v", trap.Kind, err)
}
- payload, err := mutator.Plan(context.Background(), env, dockerx.Target{})
+ payload, err := mutator.Plan(
+ context.Background(),
+ env,
+ dockerx.Target{},
+ )
if err != nil {
t.Fatalf("plan %s: %v", trap.Kind, err)
}
@@ -130,8 +151,14 @@ func TestTheJournalledTrapRoundTrips(t *testing.T) {
t.Fatalf("decode %s: %v", trap.Kind, err)
}
- if back.Kind != trap.Kind || back.Delay != trap.Delay || back.KeyForm != trap.KeyForm {
- t.Errorf("%s did not round-trip: got %+v want %+v", trap.Kind, back, trap)
+ if back.Kind != trap.Kind || back.Delay != trap.Delay ||
+ back.KeyForm != trap.KeyForm {
+ t.Errorf(
+ "%s did not round-trip: got %+v want %+v",
+ trap.Kind,
+ back,
+ trap,
+ )
}
}
}
@@ -144,15 +171,29 @@ func TestApplyingAnIdentityTrapWithNoProviderIsRefused(t *testing.T) {
t.Fatalf("lookup: %v", err)
}
- if _, err := mutator.Plan(context.Background(), Env{}, dockerx.Target{}); err == nil {
+ if _, err := mutator.Plan(
+ context.Background(),
+ Env{},
+ dockerx.Target{},
+ ); err == nil {
t.Fatal("planning an identity trap with no provider succeeded")
}
- if err := mutator.Apply(context.Background(), Env{}, dockerx.Target{}, nil); err == nil {
+ if err := mutator.Apply(
+ context.Background(),
+ Env{},
+ dockerx.Target{},
+ nil,
+ ); err == nil {
t.Fatal("applying an identity trap with no provider succeeded")
}
- if _, confirmed, err := mutator.Confirm(context.Background(), Env{}, dockerx.Target{}); confirmed || err == nil {
+ if _, confirmed, err := mutator.Confirm(
+ context.Background(),
+ Env{},
+ dockerx.Target{},
+ ); confirmed ||
+ err == nil {
t.Fatal("confirming an identity trap with no provider succeeded")
}
}
@@ -167,7 +208,11 @@ func TestRevertingWithoutAProviderIsResolvedRatherThanFailed(t *testing.T) {
t.Fatalf("lookup: %v", err)
}
- if err := mutator.Revert(context.Background(), Env{}, journal.Record{}); err != nil {
+ if err := mutator.Revert(
+ context.Background(),
+ Env{},
+ journal.Record{},
+ ); err != nil {
t.Fatalf("revert on a cold start returned %v; it must resolve", err)
}
}
@@ -185,8 +230,14 @@ func TestAMutationRefusesATrapTheRunDidNotArm(t *testing.T) {
env := Env{IdP: provider, IdPTrap: idp.Trap{Kind: idp.SignatureTruncated}}
- if _, err := mutator.Plan(context.Background(), Env(env), dockerx.Target{}); err == nil {
- t.Fatal("a run holding signature-truncated planned an alg-none mutation")
+ if _, err := mutator.Plan(
+ context.Background(),
+ env,
+ dockerx.Target{},
+ ); err == nil {
+ t.Fatal(
+ "a run holding signature-truncated planned an alg-none mutation",
+ )
}
}
@@ -206,8 +257,14 @@ func TestRevokeResolvesItsCredentialAtInjectTime(t *testing.T) {
bare := Env{IdP: fresh, IdPTrap: idp.Trap{Kind: idp.Revoke}}
- if _, err := mutator.Plan(context.Background(), bare, dockerx.Target{}); err == nil {
- t.Fatal("planning a revocation succeeded before any credential was issued")
+ if _, err := mutator.Plan(
+ context.Background(),
+ bare,
+ dockerx.Target{},
+ ); err == nil {
+ t.Fatal(
+ "planning a revocation succeeded before any credential was issued",
+ )
}
credential := fresh.Revocable()
@@ -218,13 +275,18 @@ func TestRevokeResolvesItsCredentialAtInjectTime(t *testing.T) {
}
var resolved idp.Trap
- if err := (journal.Record{Payload: payload}).DecodePayload(&resolved); err != nil {
+ if err := (journal.Record{Payload: payload}).DecodePayload(
+ &resolved,
+ ); err != nil {
t.Fatalf("decode: %v", err)
}
if resolved.Credential != credential {
- t.Fatalf("the journalled trap revokes %q, want the credential the probe issued, %q",
- resolved.Credential, credential)
+ t.Fatalf(
+ "the journalled trap revokes %q, want the credential the probe issued, %q",
+ resolved.Credential,
+ credential,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/deadlock_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/deadlock_test.go
index 575f93f2..3dfa5e15 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/deadlock_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/deadlock_test.go
@@ -47,8 +47,10 @@ func TestCloseDoesNotDeadlockAgainstAWedgedDependency(t *testing.T) {
select {
case <-done:
case <-time.After(5 * time.Second):
- t.Fatal("Close() did not return within 5s against a dependency that accepts and never " +
- "answers. khaos run defers this Close, so the whole command hangs with a fault's " +
- "listener still bound, and the operator reaches for kill -9")
+ t.Fatal(
+ "Close() did not return within 5s against a dependency that accepts and never " +
+ "answers. khaos run defers this Close, so the whole command hangs with a fault's " +
+ "listener still bound, and the operator reaches for kill -9",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go
index eef782f9..66b26149 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go
@@ -70,7 +70,9 @@ const (
var ErrUnknownKind = errors.New("no proxy fault is registered under that name")
-var ErrFaultIncomplete = errors.New("that proxy fault needs a parameter it was not given")
+var ErrFaultIncomplete = errors.New(
+ "that proxy fault needs a parameter it was not given",
+)
// Fault is the whole mutable state of an armed proxy. Reverting is assigning
// PassThrough over it, which is why the tier rolls back by freeing a struct
@@ -93,7 +95,12 @@ func Kinds() []string {
func ParseKind(name string) (Kind, error) {
kind := Kind(name)
if kind == PassThrough || !slices.Contains(Kinds(), name) {
- return "", fmt.Errorf(errUnknownKind, ErrUnknownKind, name, strings.Join(Kinds(), kindSep))
+ return "", fmt.Errorf(
+ errUnknownKind,
+ ErrUnknownKind,
+ name,
+ strings.Join(Kinds(), kindSep),
+ )
}
return kind, nil
}
@@ -118,7 +125,12 @@ func (f Fault) Validate() error {
// kinds accepts the zero Fault, a misspelling and a trailing space, all of
// which forward every byte untouched while reporting as armed. An
// unmarshalled journal payload reaches this with no other guard.
- return fmt.Errorf(errUnknownKind, ErrUnknownKind, f.Kind, strings.Join(Kinds(), kindSep))
+ return fmt.Errorf(
+ errUnknownKind,
+ ErrUnknownKind,
+ f.Kind,
+ strings.Join(Kinds(), kindSep),
+ )
}
return nil
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go
index 86d67328..c7567627 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go
@@ -30,11 +30,17 @@ const (
errNoControl = "%w: %v"
)
-var ErrNothingArmed = errors.New("nothing is armed on the fault proxy, so there is nothing to confirm")
+var ErrNothingArmed = errors.New(
+ "nothing is armed on the fault proxy, so there is nothing to confirm",
+)
-var ErrDependencyUnreachable = errors.New("khaos cannot reach the dependency directly, so it cannot attribute what it sees through the proxy to its own fault")
+var ErrDependencyUnreachable = errors.New(
+ "khaos cannot reach the dependency directly, so it cannot attribute what it sees through the proxy to its own fault",
+)
-var ErrFaultNotObserved = errors.New("the armed fault did not produce its own observable")
+var ErrFaultNotObserved = errors.New(
+ "the armed fault did not produce its own observable",
+)
// reading is what khaos's confirmation probe measured on one path.
type reading struct {
@@ -55,25 +61,45 @@ type reading struct {
// served in full, and a dependency taking one second confirmed a `latency` whose
// delay had been removed. The direct path is the control, and the design contract
// calls for read-back rather than an API return value.
-func (p *Proxy) Observe(ctx context.Context, expected Kind) (string, bool, error) {
- // Closed is checked FIRST. Close reverts to pass-through, so reading the fault
- // before this would report "nothing armed" for a proxy that is gone, and a
- // dial to a listener that no longer exists is ECONNREFUSED, which a reset
- // oracle must not accept as its own observable.
+// armedFor resolves the fault this call is allowed to confirm, or says why the
+// proxy cannot be asked at all.
+//
+// Closed is checked FIRST. Close reverts to pass-through, so reading the fault
+// before this would report "nothing armed" for a proxy that is gone, and a dial
+// to a listener that no longer exists is ECONNREFUSED, which a reset oracle
+// must not accept as its own observable.
+func (p *Proxy) armedFor(expected Kind) (Fault, error) {
select {
case <-p.closed:
- return "", false, ErrClosed
+ return Fault{}, ErrClosed
default:
}
fault := p.Fault()
if fault.Kind == PassThrough {
- return "", false, ErrNothingArmed
+ return Fault{}, ErrNothingArmed
}
if expected != "" && fault.Kind != expected {
- return "", false, fmt.Errorf(errWrongArmed, ErrFaultNotObserved, fault.Kind, expected)
+ return Fault{}, fmt.Errorf(
+ errWrongArmed,
+ ErrFaultNotObserved,
+ fault.Kind,
+ expected,
+ )
+ }
+
+ return fault, nil
+}
+
+func (p *Proxy) Observe(
+ ctx context.Context,
+ expected Kind,
+) (string, bool, error) {
+ fault, err := p.armedFor(expected)
+ if err != nil {
+ return "", false, err
}
p.probes.Add(1)
@@ -84,12 +110,17 @@ func (p *Proxy) Observe(ctx context.Context, expected Kind) (string, bool, error
// the way, nothing seen through the proxy can be attributed to khaos's fault,
// and saying so voids the run instead of crediting khaos for someone else's
// outage.
- // A complete answer always ends in an error, because that is what the peer
- // closing looks like to a reader. Only the absence of BYTES means khaos could
- // not reach the dependency.
+ //
+ // The test is the absence of BYTES, not the presence of an error: a complete
+ // answer always ends in one, because that is what the peer closing looks
+ // like to a reader.
direct, directErr := p.measure(ctx, p.upstream, observeGrace)
if direct.total == 0 {
- return "", false, fmt.Errorf(errNoControl, ErrDependencyUnreachable, directErr)
+ return "", false, fmt.Errorf(
+ errNoControl,
+ ErrDependencyUnreachable,
+ directErr,
+ )
}
through, throughErr := p.measure(ctx, p.Addr(), budget)
@@ -114,21 +145,35 @@ func (p *Proxy) Observe(ctx context.Context, expected Kind) (string, bool, error
case Latency:
added := through.firstByte - direct.firstByte
if added >= slack(fault.Delay) {
- return sprintf(observedLatency, added.Round(time.Millisecond)), true, nil
+ return sprintf(
+ observedLatency,
+ added.Round(time.Millisecond),
+ ), true, nil
}
case Partial:
// Both halves. A byte count that merely MATCHES the budget is also what
// pass-through delivers when the answer happens to be that long, so the
// control's answer has to be longer than what came through.
if through.total == int64(fault.Bytes) && direct.total > through.total {
- return sprintf(observedPartial, through.total, direct.total), true, nil
+ return sprintf(
+ observedPartial,
+ through.total,
+ direct.total,
+ ), true, nil
}
case SlowClose:
held := through.closed - through.firstByte
reference := direct.closed - direct.firstByte
if held-reference >= slack(fault.Delay) {
- return sprintf(observedSlowClose, held.Round(time.Millisecond)), true, nil
+ return sprintf(
+ observedSlowClose,
+ held.Round(time.Millisecond),
+ ), true, nil
}
+
+ default:
+ // PassThrough is the absence of a fault and has no observable to
+ // confirm, so it reaches the unconfirmed return below.
}
return "", false, nil
@@ -140,7 +185,11 @@ func slack(delay time.Duration) time.Duration {
// measure sends one probe to an address and records when the first byte arrived,
// how much arrived in total, and when the peer closed.
-func (p *Proxy) measure(ctx context.Context, addr string, budget time.Duration) (reading, error) {
+func (p *Proxy) measure(
+ ctx context.Context,
+ addr string,
+ budget time.Duration,
+) (reading, error) {
dialer := net.Dialer{Timeout: budget}
conn, err := dialer.DialContext(ctx, network, addr)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe_test.go
index 12a785d0..7010e9ff 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe_test.go
@@ -30,7 +30,7 @@ func armable() []Fault {
// reported a latency fault confirmed while the proxy was in pass-through and
// nothing was armed at all.
func TestObserveRefusesToConfirmWhenNothingIsArmed(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
method, confirmed, err := p.Observe(context.Background(), "")
@@ -45,32 +45,47 @@ func TestObserveRefusesToConfirmWhenNothingIsArmed(t *testing.T) {
func TestObserveConfirmsEveryFaultAndStopsAfterTheRevert(t *testing.T) {
if len(armable()) != len(Kinds()) {
- t.Fatalf("this test covers %d faults but %d are registered", len(armable()), len(Kinds()))
+ t.Fatalf(
+ "this test covers %d faults but %d are registered",
+ len(armable()),
+ len(Kinds()),
+ )
}
for _, fault := range armable() {
t.Run(string(fault.Kind), func(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(fault); err != nil {
t.Fatalf("arm: %v", err)
}
- method, confirmed, err := p.Observe(context.Background(), fault.Kind)
+ method, confirmed, err := p.Observe(
+ context.Background(),
+ fault.Kind,
+ )
if err != nil {
t.Fatalf("observe: %v", err)
}
if !confirmed {
- t.Fatalf("%s was armed and the proxy could not observe it; a fault khaos "+
- "cannot confirm voids the run", fault.Kind)
+ t.Fatalf(
+ "%s was armed and the proxy could not observe it; a fault khaos "+
+ "cannot confirm voids the run",
+ fault.Kind,
+ )
}
if method == "" {
- t.Fatal("the confirmation reported no method, so the run record cannot say how")
+ t.Fatal(
+ "the confirmation reported no method, so the run record cannot say how",
+ )
}
p.Disarm()
- if _, confirmed, _ := p.Observe(context.Background(), ""); confirmed {
+ if _, confirmed, _ := p.Observe(
+ context.Background(),
+ "",
+ ); confirmed {
t.Fatalf("%s still confirmed after the revert", fault.Kind)
}
})
@@ -85,7 +100,7 @@ func TestObserveConfirmsEveryFaultAndStopsAfterTheRevert(t *testing.T) {
func TestObserveRefusesAFaultThatIsArmedButDoesNotHappen(t *testing.T) {
for _, fault := range armable() {
t.Run(string(fault.Kind), func(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(fault); err != nil {
t.Fatalf("arm: %v", err)
@@ -96,10 +111,14 @@ func TestObserveRefusesAFaultThatIsArmedButDoesNotHappen(t *testing.T) {
method, confirmed, _ := p.Observe(context.Background(), fault.Kind)
if confirmed {
- t.Fatalf("%s was confirmed (%q) while the proxy forwarded normally. The oracle "+
- "cannot tell an applied fault from an unapplied one, so a run would record "+
- "that the fault landed, the probes would see a healthy dependency, and the "+
- "verdict would be a clean survival", fault.Kind, method)
+ t.Fatalf(
+ "%s was confirmed (%q) while the proxy forwarded normally. The oracle "+
+ "cannot tell an applied fault from an unapplied one, so a run would record "+
+ "that the fault landed, the probes would see a healthy dependency, and the "+
+ "verdict would be a clean survival",
+ fault.Kind,
+ method,
+ )
}
})
}
@@ -110,10 +129,12 @@ func TestObserveRefusesAFaultThatIsArmedButDoesNotHappen(t *testing.T) {
func TestASlowDependencyDoesNotConfirmAFaultThatIsNotHappening(t *testing.T) {
const dependencyDelay = 1200 * time.Millisecond
- slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- time.Sleep(dependencyDelay)
- _, _ = io.WriteString(w, body)
- }))
+ slow := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ time.Sleep(dependencyDelay)
+ _, _ = io.WriteString(w, body)
+ }),
+ )
defer slow.Close()
for _, fault := range []Fault{
@@ -136,9 +157,13 @@ func TestASlowDependencyDoesNotConfirmAFaultThatIsNotHappening(t *testing.T) {
_, confirmed, _ := p.Observe(context.Background(), fault.Kind)
if confirmed {
- t.Fatalf("a dependency that takes %s to answer confirmed %s while the proxy "+
- "forwarded it untouched; khaos would credit itself for someone else's "+
- "slowness", dependencyDelay, fault.Kind)
+ t.Fatalf(
+ "a dependency that takes %s to answer confirmed %s while the proxy "+
+ "forwarded it untouched; khaos would credit itself for someone else's "+
+ "slowness",
+ dependencyDelay,
+ fault.Kind,
+ )
}
})
}
@@ -163,12 +188,18 @@ func TestAnUnreachableDependencyCannotConfirmAnything(t *testing.T) {
_, confirmed, err := p.Observe(context.Background(), fault.Kind)
if confirmed {
- t.Fatalf("%s was confirmed against a dependency khaos cannot reach", fault.Kind)
+ t.Fatalf(
+ "%s was confirmed against a dependency khaos cannot reach",
+ fault.Kind,
+ )
}
if !errors.Is(err, ErrDependencyUnreachable) {
- t.Fatalf("err = %v, want ErrDependencyUnreachable so the operator learns why "+
- "the run is void", err)
+ t.Fatalf(
+ "err = %v, want ErrDependencyUnreachable so the operator learns why "+
+ "the run is void",
+ err,
+ )
}
})
}
@@ -178,7 +209,7 @@ func TestAnUnreachableDependencyCannotConfirmAnything(t *testing.T) {
// listener gives ECONNREFUSED, and accepting that as a reset let a dead proxy
// report the fault it was holding when it died.
func TestAClosedProxyDoesNotConfirmItsFault(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Reset}); err != nil {
t.Fatalf("arm: %v", err)
@@ -204,10 +235,12 @@ func TestAClosedProxyDoesNotConfirmItsFault(t *testing.T) {
func TestPartialDoesNotConfirmWhenNothingWasTruncated(t *testing.T) {
const answer = "exactly-this"
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Length", fmt.Sprint(len(answer)))
- _, _ = io.WriteString(w, answer)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", fmt.Sprint(len(answer)))
+ _, _ = io.WriteString(w, answer)
+ }),
+ )
defer server.Close()
p, err := Open(loopback, strings.TrimPrefix(server.URL, "http://"))
@@ -231,8 +264,12 @@ func TestPartialDoesNotConfirmWhenNothingWasTruncated(t *testing.T) {
_, confirmed, _ := p.Observe(context.Background(), Partial)
if confirmed {
- t.Fatalf("a budget of %d bytes against a %d byte answer confirmed truncation; the "+
- "target received the dependency's complete answer", full.total, full.total)
+ t.Fatalf(
+ "a budget of %d bytes against a %d byte answer confirmed truncation; the "+
+ "target received the dependency's complete answer",
+ full.total,
+ full.total,
+ )
}
}
@@ -240,7 +277,7 @@ func TestPartialDoesNotConfirmWhenNothingWasTruncated(t *testing.T) {
// uninterruptibly, and the design doc is explicit that a tool which LOOKS hung is
// what makes an operator reach for kill -9.
func TestObserveHonoursCancellation(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Hang}); err != nil {
t.Fatalf("arm: %v", err)
@@ -258,14 +295,17 @@ func TestObserveHonoursCancellation(t *testing.T) {
}
if took >= observeGrace {
- t.Fatalf("a cancelled confirmation took %s; it ignored the context", took)
+ t.Fatalf(
+ "a cancelled confirmation took %s; it ignored the context",
+ took,
+ )
}
}
// The oracle must also catch the wrong fault being armed, which is the other
// thing a confirmation step is for.
func TestObserveRefusesWhenADifferentFaultIsArmed(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Reset}); err != nil {
t.Fatalf("arm: %v", err)
@@ -284,7 +324,7 @@ func TestObserveRefusesWhenADifferentFaultIsArmed(t *testing.T) {
// Probe traffic is khaos's own and must not be reported as the target's.
func TestConfirmationTrafficIsCountedSeparately(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Hang}); err != nil {
t.Fatalf("arm: %v", err)
@@ -297,23 +337,30 @@ func TestConfirmationTrafficIsCountedSeparately(t *testing.T) {
}
if after := p.Counts(); after.Probes <= before.Probes {
- t.Fatal("a confirmation dial was not recorded as khaos's own probe, so the run record " +
- "reports it as the target's traffic")
+ t.Fatal(
+ "a confirmation dial was not recorded as khaos's own probe, so the run record " +
+ "reports it as the target's traffic",
+ )
}
}
func TestMeasureReadsBothPathsOfTheDifferential(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
direct, _ := p.measure(context.Background(), p.upstream, observeGrace)
if direct.total == 0 {
- t.Fatal("the control path measured nothing, so no differential is possible")
+ t.Fatal(
+ "the control path measured nothing, so no differential is possible",
+ )
}
proxied, _ := p.measure(context.Background(), p.Addr(), observeGrace)
if proxied.total != direct.total {
- t.Fatalf("pass-through delivered %d bytes where the dependency answers %d",
- proxied.total, direct.total)
+ t.Fatalf(
+ "pass-through delivered %d bytes where the dependency answers %d",
+ proxied.total,
+ direct.total,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go
index f8cfbc16..35a145ab 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go
@@ -34,6 +34,12 @@ const (
// be drained to the deadline rather than to the first short read.
drainWindow = 250 * time.Millisecond
+ // How long Reset waits for the target's first bytes before it resets. Unlike
+ // drainWindow this is not about the receive queue, and it ends at the first
+ // read rather than at the deadline, so a target that sends a request pays
+ // nothing for it.
+ settleWindow = 250 * time.Millisecond
+
errWildcard = "%w: %q binds every address on this host, and a fault proxy in front of a dependency under test must not be reachable off it; bind the Docker bridge gateway instead"
errPrivileged = "%w: %q is a privileged port"
errBadAddr = "%w: %q is not a host and port (%v)"
@@ -210,7 +216,9 @@ func bridgeHosts(ip net.IP) (bool, error) {
continue
}
- _, err := os.Stat(filepath.Join(sysClassNet, iface.Name, bridgeMarker))
+ _, err := os.Stat(
+ filepath.Join(sysClassNet, iface.Name, bridgeMarker),
+ )
return err == nil, nil
}
@@ -390,17 +398,24 @@ func (p *Proxy) handle(client net.Conn) {
func (p *Proxy) sever(client net.Conn, fault Fault, generation uint64) bool {
switch fault.Kind {
case Reset:
- // SO_LINGER 0 is necessary AND sufficient: it forces RST whatever the
- // receive queue holds, and the reset surfaces at the target's connect or
- // at its first read, which are the same observable.
+ // SO_LINGER 0 is necessary but NOT sufficient. It forces RST whatever the
+ // receive queue holds, and it is the only thing that produces a reset at
+ // all: deleting it turns both reset controls red immediately. What it does
+ // not decide is WHO sees the reset. The kernel delivers it to the peer
+ // once, through sk_err, and the first syscall to touch that socket clears
+ // it, so a target that writes its request before reading the answer hands
+ // the error to its write and its own read returns EOF. That is the EOF
+ // fault's observable, which would collapse two catalogue entries into one.
//
- // This used to also wait for the target's request, on the theory that a
- // non-empty receive queue was needed to force RST on an empty-queue close.
- // Measured: deleting that wait leaves both reset controls green over 20
- // runs, including a target that sends nothing, while deleting SO_LINGER 0
- // turns them red immediately. The wait was inert, and an inert arm alibis
- // the live one's control, so it is gone rather than kept for symmetry. It
- // also cost every reset a quarter second it should not have.
+ // An earlier pass deleted this wait as inert because both reset controls
+ // stayed green over 20 runs without it. Those controls run through
+ // net/http, which reports a reset at connect and a reset at read as the
+ // same error, so they could not see the difference and alibied the arm.
+ // Measured at the socket instead, 20 trials per arm: without the wait,
+ // `write=ECONNRESET read=EOF` 13 times and a reset at connect the other 7,
+ // never a reset at the read; with it, `write=nil read=ECONNRESET` 20 of 20.
+ settle(client)
+
if tcp, ok := client.(*net.TCPConn); ok {
_ = tcp.SetLinger(noLinger)
}
@@ -426,6 +441,21 @@ func (p *Proxy) sever(client net.Conn, fault Fault, generation uint64) bool {
// first short read is wrong: a short read means "that is what had arrived by
// now", not "the queue is empty", so bytes still in flight land on a closed
// socket and the kernel answers RST.
+// settle waits for the target to write something, or for the window, whichever
+// lands first. Reset does not need an empty receive queue the way EOF does, only
+// a peer that has already spent its first syscall, so this returns on the first
+// read instead of looping to the deadline.
+func settle(client net.Conn) {
+ if err := client.SetReadDeadline(
+ time.Now().Add(settleWindow),
+ ); err != nil {
+ return
+ }
+
+ buffer := make([]byte, copyBuffer)
+ _, _ = client.Read(buffer)
+}
+
func drain(client net.Conn) {
if err := client.SetReadDeadline(time.Now().Add(drainWindow)); err != nil {
return
@@ -558,7 +588,12 @@ func (p *Proxy) forward(client net.Conn, fault Fault, generation uint64) bool {
// source ends. The delay is per chunk rather than once at the start, because a
// one-off delay is a slow connection and a per-chunk delay is a slow dependency,
// and only the second survives a client that retries.
-func (p *Proxy) pump(dst, src net.Conn, delay time.Duration, limit int, halfClose bool) {
+func (p *Proxy) pump(
+ dst, src net.Conn,
+ delay time.Duration,
+ limit int,
+ halfClose bool,
+) {
if halfClose {
defer func() {
if tcp, ok := dst.(*net.TCPConn); ok {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy_test.go
index 6c8b74c4..d0793b1e 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy_test.go
@@ -27,16 +27,18 @@ const (
func upstreamServer(t *testing.T) *httptest.Server {
t.Helper()
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Length", fmt.Sprint(len(body)))
- _, _ = io.WriteString(w, body)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", fmt.Sprint(len(body)))
+ _, _ = io.WriteString(w, body)
+ }),
+ )
t.Cleanup(server.Close)
return server
}
-func through(t *testing.T) (*Proxy, *httptest.Server) {
+func through(t *testing.T) *Proxy {
t.Helper()
server := upstreamServer(t)
@@ -47,7 +49,7 @@ func through(t *testing.T) (*Proxy, *httptest.Server) {
}
t.Cleanup(func() { _ = p.Close() })
- return p, server
+ return p
}
// get returns the body, or a description of how the attempt failed. Both are
@@ -67,7 +69,7 @@ func get(p *Proxy) (string, error) {
}
func TestPassThroughDeliversTheDependencyUntouched(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
got, err := get(p)
if err != nil {
@@ -99,7 +101,7 @@ func TestEveryFaultIsDistinguishableFromPassThrough(t *testing.T) {
for _, fault := range faults {
t.Run(string(fault.Kind), func(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(fault); err != nil {
t.Fatalf("arm: %v", err)
@@ -122,8 +124,11 @@ func TestEveryFaultIsDistinguishableFromPassThrough(t *testing.T) {
// for the close.
if fault.Kind == SlowClose {
if got != body {
- t.Fatalf("slow-close delivered %q, want the answer intact; holding the "+
- "PAYLOAD back makes it indistinguishable from a latency fault", got)
+ t.Fatalf(
+ "slow-close delivered %q, want the answer intact; holding the "+
+ "PAYLOAD back makes it indistinguishable from a latency fault",
+ got,
+ )
}
// Measured at the SOCKET, not through this HTTP client. Go's
@@ -138,8 +143,12 @@ func TestEveryFaultIsDistinguishableFromPassThrough(t *testing.T) {
// clients it is not meant to break.
observable, confirmed, err := p.Observe(t.Context(), SlowClose)
if err != nil || !confirmed {
- t.Fatalf("slow-close is not observable at the socket either (%v), so nothing "+
- "distinguishes it from no fault at all: %s", err, observable)
+ t.Fatalf(
+ "slow-close is not observable at the socket either (%v), so nothing "+
+ "distinguishes it from no fault at all: %s",
+ err,
+ observable,
+ )
}
t.Logf("slow-close -> body intact after %s, and %s",
@@ -148,8 +157,11 @@ func TestEveryFaultIsDistinguishableFromPassThrough(t *testing.T) {
}
if err == nil && got == body {
- t.Fatalf("%s delivered the dependency's answer intact, so it is "+
- "indistinguishable from no fault at all", fault.Kind)
+ t.Fatalf(
+ "%s delivered the dependency's answer intact, so it is "+
+ "indistinguishable from no fault at all",
+ fault.Kind,
+ )
}
t.Logf("%s -> body=%q err=%v", fault.Kind, got, err)
@@ -158,7 +170,7 @@ func TestEveryFaultIsDistinguishableFromPassThrough(t *testing.T) {
}
func TestResetIsRefusedWhileHangIsSilence(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Reset}); err != nil {
t.Fatalf("arm reset: %v", err)
@@ -173,8 +185,11 @@ func TestResetIsRefusedWhileHangIsSilence(t *testing.T) {
}
if errors.Is(resetErr, http.ErrHandlerTimeout) || resetTook >= probeWait {
- t.Fatalf("reset took %s, which is a timeout rather than a refusal; a client "+
- "cannot tell it from a hang and the two hit different branches", resetTook)
+ t.Fatalf(
+ "reset took %s, which is a timeout rather than a refusal; a client "+
+ "cannot tell it from a hang and the two hit different branches",
+ resetTook,
+ )
}
if err := p.Arm(Fault{Kind: Hang}); err != nil {
@@ -190,8 +205,11 @@ func TestResetIsRefusedWhileHangIsSilence(t *testing.T) {
}
if hangTook < probeWait {
- t.Fatalf("hang failed after %s, before the client's own timeout; a hang the "+
- "client distinguishes from a refusal is the whole point of having both", hangTook)
+ t.Fatalf(
+ "hang failed after %s, before the client's own timeout; a hang the "+
+ "client distinguishes from a refusal is the whole point of having both",
+ hangTook,
+ )
}
}
@@ -211,7 +229,7 @@ func TestResetIsAnRSTAndEOFIsAFIN(t *testing.T) {
for _, tc := range cases {
t.Run(string(tc.fault), func(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: tc.fault}); err != nil {
t.Fatalf("arm: %v", err)
@@ -231,7 +249,9 @@ func TestResetIsAnRSTAndEOFIsAFIN(t *testing.T) {
_, _ = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: x\r\n\r\n")
- if err := conn.SetReadDeadline(time.Now().Add(probeWait)); err != nil {
+ if err := conn.SetReadDeadline(
+ time.Now().Add(probeWait),
+ ); err != nil {
t.Fatalf("deadline: %v", err)
}
@@ -243,9 +263,13 @@ func TestResetIsAnRSTAndEOFIsAFIN(t *testing.T) {
gotEOF := errors.Is(readErr, io.EOF)
if tc.wantReset && !gotReset {
- t.Fatalf("%s produced %v, not ECONNRESET; a client cannot tell it from an "+
- "orderly close, and the two hit different branches in almost every "+
- "HTTP client", tc.fault, readErr)
+ t.Fatalf(
+ "%s produced %v, not ECONNRESET; a client cannot tell it from an "+
+ "orderly close, and the two hit different branches in almost every "+
+ "HTTP client",
+ tc.fault,
+ readErr,
+ )
}
if !tc.wantReset && !gotEOF {
@@ -258,7 +282,7 @@ func TestResetIsAnRSTAndEOFIsAFIN(t *testing.T) {
func TestPartialDeliversAPrefixAndThenStops(t *testing.T) {
const budget = 12
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Partial, Bytes: budget}); err != nil {
t.Fatalf("arm: %v", err)
@@ -267,8 +291,11 @@ func TestPartialDeliversAPrefixAndThenStops(t *testing.T) {
got, _ := get(p)
if len(got) >= len(body) {
- t.Fatalf("partial delivered %d bytes of a %d byte body, so nothing was truncated",
- len(got), len(body))
+ t.Fatalf(
+ "partial delivered %d bytes of a %d byte body, so nothing was truncated",
+ len(got),
+ len(body),
+ )
}
if strings.Contains(got, body) {
@@ -279,7 +306,7 @@ func TestPartialDeliversAPrefixAndThenStops(t *testing.T) {
func TestLatencyDelaysRatherThanFails(t *testing.T) {
const delay = 300 * time.Millisecond
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Latency, Delay: delay}); err != nil {
t.Fatalf("arm: %v", err)
@@ -298,7 +325,11 @@ func TestLatencyDelaysRatherThanFails(t *testing.T) {
}
if took < delay {
- t.Fatalf("latency of %s took only %s, so the delay is not being applied", delay, took)
+ t.Fatalf(
+ "latency of %s took only %s, so the delay is not being applied",
+ delay,
+ took,
+ )
}
}
@@ -306,13 +337,15 @@ func TestLatencyDelaysRatherThanFails(t *testing.T) {
// recovery window reads as a target that never came back.
func TestDisarmRestoresPassThroughCompletely(t *testing.T) {
for _, fault := range []Fault{
- {Kind: Hang}, {Kind: Reset}, {Kind: EOF},
+ {Kind: Hang},
+ {Kind: Reset},
+ {Kind: EOF},
{Kind: Latency, Delay: 2 * time.Second},
{Kind: Partial, Bytes: 4},
{Kind: SlowClose, Delay: 2 * time.Second},
} {
t.Run(string(fault.Kind), func(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(fault); err != nil {
t.Fatalf("arm: %v", err)
@@ -327,10 +360,18 @@ func TestDisarmRestoresPassThroughCompletely(t *testing.T) {
got, err := get(p)
if err != nil {
- t.Fatalf("after disarming %s the proxy still fails: %v", fault.Kind, err)
+ t.Fatalf(
+ "after disarming %s the proxy still fails: %v",
+ fault.Kind,
+ err,
+ )
}
if got != body {
- t.Fatalf("after disarming %s the proxy delivered %q", fault.Kind, got)
+ t.Fatalf(
+ "after disarming %s the proxy delivered %q",
+ fault.Kind,
+ got,
+ )
}
})
}
@@ -340,7 +381,7 @@ func TestDisarmRestoresPassThroughCompletely(t *testing.T) {
// would otherwise keep sailing through it, and a fault nothing experiences reads
// as a clean survival.
func TestArmingDropsConnectionsOpenedBeforeTheFault(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
client, err := net.Dial("tcp", p.Addr())
if err != nil {
@@ -348,7 +389,10 @@ func TestArmingDropsConnectionsOpenedBeforeTheFault(t *testing.T) {
}
defer func() { _ = client.Close() }()
- if _, err := io.WriteString(client, "GET / HTTP/1.1\r\nHost: x\r\n\r\n"); err != nil {
+ if _, err := io.WriteString(
+ client,
+ "GET / HTTP/1.1\r\nHost: x\r\n\r\n",
+ ); err != nil {
t.Fatalf("write: %v", err)
}
@@ -358,7 +402,10 @@ func TestArmingDropsConnectionsOpenedBeforeTheFault(t *testing.T) {
buffer := make([]byte, 128)
if _, err := client.Read(buffer); err != nil {
- t.Fatalf("the established connection never answered before the fault: %v", err)
+ t.Fatalf(
+ "the established connection never answered before the fault: %v",
+ err,
+ )
}
if err := p.Arm(Fault{Kind: Hang}); err != nil {
@@ -382,9 +429,11 @@ func TestArmingDropsConnectionsOpenedBeforeTheFault(t *testing.T) {
var timeout net.Error
if errors.As(err, &timeout) && timeout.Timeout() {
- t.Fatalf("a connection established before the fault was neither dropped nor ended " +
- "after arming; a target on a pooled keepalive connection would sail straight " +
- "through the fault and the run would report a clean survival")
+ t.Fatalf(
+ "a connection established before the fault was neither dropped nor ended " +
+ "after arming; a target on a pooled keepalive connection would sail straight " +
+ "through the fault and the run would report a clean survival",
+ )
}
return
@@ -394,7 +443,7 @@ func TestArmingDropsConnectionsOpenedBeforeTheFault(t *testing.T) {
// Closing the proxy IS the rollback of last resort. The fault has to die with the
// process, because that is the tier's entire safety argument.
func TestClosingTheProxyRemovesTheFaultEntirely(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Hang}); err != nil {
t.Fatalf("arm: %v", err)
@@ -409,7 +458,9 @@ func TestClosingTheProxyRemovesTheFaultEntirely(t *testing.T) {
conn, err := net.DialTimeout("tcp", addr, probeWait)
if err == nil {
_ = conn.Close()
- t.Fatal("the proxy still accepts connections after Close, so the fault outlived it")
+ t.Fatal(
+ "the proxy still accepts connections after Close, so the fault outlived it",
+ )
}
if err := p.Arm(Fault{Kind: Reset}); !errors.Is(err, ErrClosed) {
@@ -420,7 +471,7 @@ func TestClosingTheProxyRemovesTheFaultEntirely(t *testing.T) {
// An incomplete fault is indistinguishable from pass-through at runtime, so it
// has to be refused at arm time rather than silently measured.
func TestAFaultThatCannotExpressItselfIsRefused(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
for _, fault := range []Fault{
{Kind: Latency},
@@ -429,12 +480,19 @@ func TestAFaultThatCannotExpressItselfIsRefused(t *testing.T) {
} {
t.Run(string(fault.Kind), func(t *testing.T) {
if err := p.Arm(fault); !errors.Is(err, ErrFaultIncomplete) {
- t.Fatalf("arm(%+v) = %v, want ErrFaultIncomplete; without a parameter this "+
- "fault forwards everything untouched and reports a clean survival", fault, err)
+ t.Fatalf(
+ "arm(%+v) = %v, want ErrFaultIncomplete; without a parameter this "+
+ "fault forwards everything untouched and reports a clean survival",
+ fault,
+ err,
+ )
}
if armed := p.Fault().Kind; armed != PassThrough {
- t.Fatalf("a refused fault still changed the armed state to %s", armed)
+ t.Fatalf(
+ "a refused fault still changed the armed state to %s",
+ armed,
+ )
}
})
}
@@ -448,11 +506,16 @@ func TestAnUnreachableDependencyIsNotMistakenForAFault(t *testing.T) {
defer func() { _ = p.Close() }()
if _, err := get(p); err == nil {
- t.Fatal("the proxy invented an answer for a dependency it could not reach")
+ t.Fatal(
+ "the proxy invented an answer for a dependency it could not reach",
+ )
}
if counts := p.Counts(); counts.Relayed != 0 {
- t.Fatalf("the proxy counted %d relayed chunks to a dead upstream", counts.Relayed)
+ t.Fatalf(
+ "the proxy counted %d relayed chunks to a dead upstream",
+ counts.Relayed,
+ )
}
}
@@ -478,9 +541,13 @@ func TestSeveringAndForwardingFaultsAreSeparated(t *testing.T) {
fault := Fault{Kind: kind, Delay: time.Second, Bytes: 1}
if fault.Severs() != severing[kind] {
- t.Fatalf("%s reports Severs()=%v; khaos confirms a severing fault by proving the "+
- "dependency is unreachable and a forwarding one by proving the stream was "+
- "altered, and one cannot stand in for the other", kind, fault.Severs())
+ t.Fatalf(
+ "%s reports Severs()=%v; khaos confirms a severing fault by proving the "+
+ "dependency is unreachable and a forwarding one by proving the stream was "+
+ "altered, and one cannot stand in for the other",
+ kind,
+ fault.Severs(),
+ )
}
}
}
@@ -490,7 +557,7 @@ func TestSeveringAndForwardingFaultsAreSeparated(t *testing.T) {
func TestSlowCloseHoldsTheConnectionOpenAfterTheAnswer(t *testing.T) {
const delay = 600 * time.Millisecond
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: SlowClose, Delay: delay}); err != nil {
t.Fatalf("arm: %v", err)
@@ -505,7 +572,10 @@ func TestSlowCloseHoldsTheConnectionOpenAfterTheAnswer(t *testing.T) {
// Connection: close is load-bearing. Without it the upstream keeps the
// connection alive, the answer leg never finishes, and the "hold" being
// measured is the test's own read deadline rather than the fault.
- _, _ = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
+ _, _ = io.WriteString(
+ conn,
+ "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n",
+ )
_ = conn.SetReadDeadline(time.Now().Add(probeWait * 4))
buffer := make([]byte, 4096)
@@ -523,19 +593,25 @@ func TestSlowCloseHoldsTheConnectionOpenAfterTheAnswer(t *testing.T) {
}
if lastByte.IsZero() {
- t.Fatal("slow-close delivered nothing at all, so it is not a slow CLOSE")
+ t.Fatal(
+ "slow-close delivered nothing at all, so it is not a slow CLOSE",
+ )
}
held := ended.Sub(lastByte)
if held < delay {
- t.Fatalf("the stream ended %s after the last byte, want at least %s; slow-close is not "+
- "holding the connection open and is only distinguishable from pass-through because "+
- "it also delays every chunk, which is what latency does", held, delay)
+ t.Fatalf(
+ "the stream ended %s after the last byte, want at least %s; slow-close is not "+
+ "holding the connection open and is only distinguishable from pass-through because "+
+ "it also delays every chunk, which is what latency does",
+ held,
+ delay,
+ )
}
}
func TestEOFStaysAFINWhenTheRequestIsLargerThanOneRead(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: EOF}); err != nil {
t.Fatalf("arm: %v", err)
@@ -549,7 +625,10 @@ func TestEOFStaysAFINWhenTheRequestIsLargerThanOneRead(t *testing.T) {
body := strings.Repeat("x", 4<<20)
go func() {
- _, _ = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: x\r\n\r\n"+body)
+ _, _ = io.WriteString(
+ conn,
+ "POST / HTTP/1.1\r\nHost: x\r\n\r\n"+body,
+ )
}()
_ = conn.SetReadDeadline(time.Now().Add(probeWait))
@@ -557,14 +636,17 @@ func TestEOFStaysAFINWhenTheRequestIsLargerThanOneRead(t *testing.T) {
_ = conn.Close()
if errors.Is(readErr, syscall.ECONNRESET) {
- t.Fatalf("attempt %d: eof produced ECONNRESET on a request larger than one read, so "+
- "it is a nondeterministic duplicate of reset after all", attempt)
+ t.Fatalf(
+ "attempt %d: eof produced ECONNRESET on a request larger than one read, so "+
+ "it is a nondeterministic duplicate of reset after all",
+ attempt,
+ )
}
}
}
func TestArmRefusesAFaultWhoseKindIsNotRegistered(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
for _, fault := range []Fault{
{},
@@ -573,8 +655,11 @@ func TestArmRefusesAFaultWhoseKindIsNotRegistered(t *testing.T) {
{Kind: PassThrough},
} {
if err := p.Arm(fault); err == nil {
- t.Fatalf("Arm(%+v) was accepted; an unrecognised kind forwards every byte untouched "+
- "and the run reports a clean survival", fault)
+ t.Fatalf(
+ "Arm(%+v) was accepted; an unrecognised kind forwards every byte untouched "+
+ "and the run reports a clean survival",
+ fault,
+ )
}
if armed := p.Fault().Kind; armed != PassThrough {
@@ -587,7 +672,7 @@ func TestArmRefusesAFaultWhoseKindIsNotRegistered(t *testing.T) {
// The baseline is measured through the proxy, so getting this wrong makes a
// healthy dependency read as a dead one before any fault is armed.
func TestAHalfClosingClientStillReceivesTheWholeAnswer(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
conn, err := net.DialTimeout(network, p.Addr(), probeWait)
if err != nil {
@@ -600,7 +685,10 @@ func TestAHalfClosingClientStillReceivesTheWholeAnswer(t *testing.T) {
t.Fatal("expected a TCP connection")
}
- if _, err := io.WriteString(tcp, "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n"); err != nil {
+ if _, err := io.WriteString(
+ tcp,
+ "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n",
+ ); err != nil {
t.Fatalf("write: %v", err)
}
@@ -616,8 +704,12 @@ func TestAHalfClosingClientStillReceivesTheWholeAnswer(t *testing.T) {
}
if !strings.Contains(string(answer), body) {
- t.Fatalf("a half-closing client received %d bytes and never the answer; pass-through "+
- "dropped it: %q", len(answer), string(answer))
+ t.Fatalf(
+ "a half-closing client received %d bytes and never the answer; pass-through "+
+ "dropped it: %q",
+ len(answer),
+ string(answer),
+ )
}
}
@@ -629,14 +721,18 @@ func TestOpenRefusesAnAddressThatWouldExposeTheProxy(t *testing.T) {
if err == nil {
bound := p.Addr()
_ = p.Close()
- t.Fatalf("Open(%q) bound %s; a fault proxy in front of a deliberately vulnerable "+
- "dependency must not be reachable off the host", addr, bound)
+ t.Fatalf(
+ "Open(%q) bound %s; a fault proxy in front of a deliberately vulnerable "+
+ "dependency must not be reachable off the host",
+ addr,
+ bound,
+ )
}
}
}
func TestDisarmReleasesAConnectionThatRacedTheRevert(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
for attempt := range 300 {
if err := p.Arm(Fault{Kind: Hang}); err != nil {
@@ -657,10 +753,14 @@ func TestDisarmReleasesAConnectionThatRacedTheRevert(t *testing.T) {
var timeout net.Error
if errors.As(readErr, &timeout) && timeout.Timeout() {
- t.Fatalf("attempt %d: a hung connection was still held 400ms after Disarm. The "+
- "ceiling is %s against a %s recovery window, so the target reads as one that "+
- "never came back and khaos manufactures the verdict itself",
- attempt, hangCeiling, "5s")
+ t.Fatalf(
+ "attempt %d: a hung connection was still held 400ms after Disarm. The "+
+ "ceiling is %s against a %s recovery window, so the target reads as one that "+
+ "never came back and khaos manufactures the verdict itself",
+ attempt,
+ hangCeiling,
+ "5s",
+ )
}
}
}
@@ -678,7 +778,9 @@ func TestOpenRefusesThisHostsRoutableAddress(t *testing.T) {
}
for _, iface := range interfaces {
- if _, err := os.Stat(filepath.Join(sysClassNet, iface.Name, bridgeMarker)); err == nil {
+ if _, err := os.Stat(
+ filepath.Join(sysClassNet, iface.Name, bridgeMarker),
+ ); err == nil {
continue
}
@@ -704,7 +806,10 @@ func TestOpenRefusesThisHostsRoutableAddress(t *testing.T) {
if err == nil {
bound := p.Addr()
_ = p.Close()
- t.Fatalf("Open bound %s, which is reachable from outside this host", bound)
+ t.Fatalf(
+ "Open bound %s, which is reachable from outside this host",
+ bound,
+ )
}
if !errors.Is(err, ErrUnsafeBind) {
@@ -721,7 +826,9 @@ func TestOpenAcceptsABridgeAddress(t *testing.T) {
}
for _, iface := range interfaces {
- if _, err := os.Stat(filepath.Join(sysClassNet, iface.Name, bridgeMarker)); err != nil {
+ if _, err := os.Stat(
+ filepath.Join(sysClassNet, iface.Name, bridgeMarker),
+ ); err != nil {
continue
}
@@ -736,9 +843,16 @@ func TestOpenAcceptsABridgeAddress(t *testing.T) {
continue
}
- p, err := Open(net.JoinHostPort(network.IP.String(), "0"), "127.0.0.1:1")
+ p, err := Open(
+ net.JoinHostPort(network.IP.String(), "0"),
+ "127.0.0.1:1",
+ )
if err != nil {
- t.Fatalf("Open refused the bridge address %s: %v", network.IP, err)
+ t.Fatalf(
+ "Open refused the bridge address %s: %v",
+ network.IP,
+ err,
+ )
}
_ = p.Close()
@@ -758,7 +872,7 @@ func TestOpenAcceptsABridgeAddress(t *testing.T) {
// and an ordinary close would send FIN, which is the eof fault wearing the wrong
// name.
func TestResetIsStillAnRSTWhenTheTargetSendsNothing(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
if err := p.Arm(Fault{Kind: Reset}); err != nil {
t.Fatalf("arm: %v", err)
@@ -780,8 +894,11 @@ func TestResetIsStillAnRSTWhenTheTargetSendsNothing(t *testing.T) {
_ = conn.Close()
if errors.Is(readErr, io.EOF) {
- t.Fatalf("attempt %d: a target that sent nothing got a clean EOF, so reset degraded "+
- "into the eof fault", attempt)
+ t.Fatalf(
+ "attempt %d: a target that sent nothing got a clean EOF, so reset degraded "+
+ "into the eof fault",
+ attempt,
+ )
}
if !isReset(readErr) {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/race_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/race_test.go
index c43da647..f7da1c5c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/race_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/race_test.go
@@ -24,7 +24,7 @@ const (
// attempts, and hang and reset are the two faults the design doc exists to keep
// distinguishable because they hit different branches in almost every client.
func TestAnArmedHangNeverArrivesAsAReset(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
resets := 0
@@ -52,9 +52,13 @@ func TestAnArmedHangNeverArrivesAsAReset(t *testing.T) {
}
if resets > 0 {
- t.Fatalf("%d of %d armed hangs arrived as a reset. A handler read the new fault with a "+
- "stale generation, so the connection was refused and closed rather than held, and "+
- "the operator measured the other fault in the catalogue", resets, raceAttempts)
+ t.Fatalf(
+ "%d of %d armed hangs arrived as a reset. A handler read the new fault with a "+
+ "stale generation, so the connection was refused and closed rather than held, and "+
+ "the operator measured the other fault in the catalogue",
+ resets,
+ raceAttempts,
+ )
}
}
@@ -62,7 +66,7 @@ func TestAnArmedHangNeverArrivesAsAReset(t *testing.T) {
// provide: a connection accepted just before a revert must not be left held by
// nothing once the revert has run.
func TestNoConnectionOutlivesTheRevertThatShouldHaveFreedIt(t *testing.T) {
- p, _ := through(t)
+ p := through(t)
for attempt := range raceAttempts {
if err := p.Arm(Fault{Kind: Hang}); err != nil {
@@ -83,10 +87,14 @@ func TestNoConnectionOutlivesTheRevertThatShouldHaveFreedIt(t *testing.T) {
var timeout net.Error
if errors.As(readErr, &timeout) && timeout.Timeout() {
- t.Fatalf("attempt %d: a connection was still held %s after the revert. The ceiling "+
- "is %s against a five second recovery window, so the target reads as one that "+
- "never came back and khaos manufactures that verdict itself",
- attempt, raceWindow, hangCeiling)
+ t.Fatalf(
+ "attempt %d: a connection was still held %s after the revert. The ceiling "+
+ "is %s against a five second recovery window, so the target reads as one that "+
+ "never came back and khaos manufactures that verdict itself",
+ attempt,
+ raceWindow,
+ hangCeiling,
+ )
}
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go
index 312ac5d0..16542887 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go
@@ -25,9 +25,13 @@ const (
describeProxy = "%s, through khaos's own proxy, which holds no capabilities and cannot reach the host"
)
-var ErrNoProxy = errors.New("this mutation needs a fault proxy that is not running")
+var ErrNoProxy = errors.New(
+ "this mutation needs a fault proxy that is not running",
+)
-var ErrProxyFaultMismatch = errors.New("the armed proxy fault does not match the mutation being applied")
+var ErrProxyFaultMismatch = errors.New(
+ "the armed proxy fault does not match the mutation being applied",
+)
// ProxyKind names the mutation that arms one proxy fault. The proxy fault kinds
// and the mutation kinds are deliberately one-to-one, so `khaos catalog` names
@@ -66,13 +70,22 @@ func (m proxyMutator) Describe(env Env, target dockerx.Target) string {
// Plan journals the fault that is about to be armed. For every other tier the
// payload is what the revert needs; here it is also the only durable record of
// what the run actually did, since the proxy itself dies with the process.
-func (m proxyMutator) Plan(_ context.Context, env Env, _ dockerx.Target) (json.RawMessage, error) {
+func (m proxyMutator) Plan(
+ _ context.Context,
+ env Env,
+ _ dockerx.Target,
+) (json.RawMessage, error) {
if env.Proxy == nil {
return nil, fmt.Errorf(errNoProxy, ErrNoProxy, ProxyKind(m.kind))
}
if env.ProxyFault.Kind != m.kind {
- return nil, fmt.Errorf(errWrongFault, ErrProxyFaultMismatch, env.ProxyFault.Kind, m.kind)
+ return nil, fmt.Errorf(
+ errWrongFault,
+ ErrProxyFaultMismatch,
+ env.ProxyFault.Kind,
+ m.kind,
+ )
}
if err := env.ProxyFault.Validate(); err != nil {
@@ -82,7 +95,12 @@ func (m proxyMutator) Plan(_ context.Context, env Env, _ dockerx.Target) (json.R
return journal.EncodePayload(env.ProxyFault)
}
-func (m proxyMutator) Apply(_ context.Context, env Env, _ dockerx.Target, raw json.RawMessage) error {
+func (m proxyMutator) Apply(
+ _ context.Context,
+ env Env,
+ _ dockerx.Target,
+ raw json.RawMessage,
+) error {
if env.Proxy == nil {
return fmt.Errorf(errNoProxy, ErrNoProxy, ProxyKind(m.kind))
}
@@ -100,7 +118,11 @@ func (m proxyMutator) Apply(_ context.Context, env Env, _ dockerx.Target, raw js
// provably went with it. Reporting that as a failure would wedge the journal
// record forever and, because `khaos reap` stops on a sweep error, would disable
// the dead man's switch for every other fault on the machine.
-func (m proxyMutator) Revert(_ context.Context, env Env, _ journal.Record) error {
+func (m proxyMutator) Revert(
+ _ context.Context,
+ env Env,
+ _ journal.Record,
+) error {
if env.Proxy == nil {
return nil
}
@@ -117,7 +139,11 @@ func (m proxyMutator) Revert(_ context.Context, env Env, _ journal.Record) error
// was chosen, not what reached the wire, so counter comparison confirms a fault
// that is not armed and confirms a severing fault while the dependency is fully
// reachable.
-func (m proxyMutator) Confirm(ctx context.Context, env Env, _ dockerx.Target) (string, bool, error) {
+func (m proxyMutator) Confirm(
+ ctx context.Context,
+ env Env,
+ _ dockerx.Target,
+) (string, bool, error) {
if env.Proxy == nil {
return "", false, fmt.Errorf(errNoProxy, ErrNoProxy, ProxyKind(m.kind))
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault_test.go
index 858647c5..e00314da 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault_test.go
@@ -28,9 +28,11 @@ const (
func armed(t *testing.T, fault proxy.Fault) Env {
t.Helper()
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- _, _ = io.WriteString(w, answer)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = io.WriteString(w, answer)
+ }),
+ )
t.Cleanup(server.Close)
p, err := proxy.Open(loopback, strings.TrimPrefix(server.URL, "http://"))
@@ -69,7 +71,11 @@ func TestEveryProxyFaultAppliesConfirmsAndReverts(t *testing.T) {
}
if registered != len(kinds()) {
- t.Fatalf("this test covers %d proxy faults but %d are registered", len(kinds()), registered)
+ t.Fatalf(
+ "this test covers %d proxy faults but %d are registered",
+ len(kinds()),
+ registered,
+ )
}
for _, fault := range kinds() {
@@ -90,11 +96,18 @@ func TestEveryProxyFaultAppliesConfirmsAndReverts(t *testing.T) {
var journaled proxy.Fault
if err := json.Unmarshal(payload, &journaled); err != nil {
- t.Fatalf("the journalled payload does not describe the fault: %v", err)
+ t.Fatalf(
+ "the journalled payload does not describe the fault: %v",
+ err,
+ )
}
if journaled != fault {
- t.Fatalf("journalled %+v, armed %+v; the journal is the only durable record of "+
- "what this run did, because the proxy dies with the process", journaled, fault)
+ t.Fatalf(
+ "journalled %+v, armed %+v; the journal is the only durable record of "+
+ "what this run did, because the proxy dies with the process",
+ journaled,
+ fault,
+ )
}
if err := mutator.Apply(ctx, env, target, payload); err != nil {
@@ -102,7 +115,11 @@ func TestEveryProxyFaultAppliesConfirmsAndReverts(t *testing.T) {
}
if got := env.Proxy.Fault(); got != fault {
- t.Fatalf("after apply the proxy holds %+v, want %+v", got, fault)
+ t.Fatalf(
+ "after apply the proxy holds %+v, want %+v",
+ got,
+ fault,
+ )
}
method, confirmed, err := mutator.Confirm(ctx, env, target)
@@ -110,15 +127,20 @@ func TestEveryProxyFaultAppliesConfirmsAndReverts(t *testing.T) {
t.Fatalf("confirm: %v", err)
}
if !confirmed {
- t.Fatalf("%s applied but could not be confirmed, so every run of it is void",
- fault.Kind)
+ t.Fatalf(
+ "%s applied but could not be confirmed, so every run of it is void",
+ fault.Kind,
+ )
}
// The run record has to carry what was MEASURED. A constant naming the
// technique is not evidence a reader can audit.
if method == "" || method == confirmProxy {
- t.Fatalf("%s confirmed with %q rather than the observable it measured",
- fault.Kind, method)
+ t.Fatalf(
+ "%s confirmed with %q rather than the observable it measured",
+ fault.Kind,
+ method,
+ )
}
if err := mutator.Revert(ctx, env, journal.Record{}); err != nil {
@@ -129,9 +151,19 @@ func TestEveryProxyFaultAppliesConfirmsAndReverts(t *testing.T) {
t.Fatalf("after revert the proxy holds %s", got)
}
- if body := reach(t, env.Proxy.Addr()); !strings.Contains(body, answer) {
- t.Fatalf("after reverting %s the dependency is still not reachable through the "+
- "proxy, got %q", fault.Kind, body)
+ if body := reach(
+ t,
+ env.Proxy.Addr(),
+ ); !strings.Contains(
+ body,
+ answer,
+ ) {
+ t.Fatalf(
+ "after reverting %s the dependency is still not reachable through the "+
+ "proxy, got %q",
+ fault.Kind,
+ body,
+ )
}
})
}
@@ -168,11 +200,26 @@ func TestAProxyMutationWithoutAProxyIsRefusedByName(t *testing.T) {
t.Fatalf("plan without a proxy returned %v, want ErrNoProxy", err)
}
- if err := mutator.Apply(ctx, empty, target, nil); !errors.Is(err, ErrNoProxy) {
+ if err := mutator.Apply(
+ ctx,
+ empty,
+ target,
+ nil,
+ ); !errors.Is(
+ err,
+ ErrNoProxy,
+ ) {
t.Fatalf("apply without a proxy returned %v, want ErrNoProxy", err)
}
- if _, _, err := mutator.Confirm(ctx, empty, target); !errors.Is(err, ErrNoProxy) {
+ if _, _, err := mutator.Confirm(
+ ctx,
+ empty,
+ target,
+ ); !errors.Is(
+ err,
+ ErrNoProxy,
+ ) {
t.Fatalf("confirm without a proxy returned %v, want ErrNoProxy", err)
}
}
@@ -186,7 +233,11 @@ func TestPlanRefusesAFaultTheRunDidNotArm(t *testing.T) {
t.Fatalf("lookup: %v", err)
}
- _, err = mutator.Plan(context.Background(), env, dockerx.Target{ID: "a", Name: "dep"})
+ _, err = mutator.Plan(
+ context.Background(),
+ env,
+ dockerx.Target{ID: "a", Name: "dep"},
+ )
if !errors.Is(err, ErrProxyFaultMismatch) {
t.Fatalf("err = %v, want ErrProxyFaultMismatch", err)
}
@@ -202,9 +253,16 @@ func TestRevertingWithoutAProxyIsResolvedRatherThanFailed(t *testing.T) {
t.Fatalf("lookup: %v", err)
}
- if err := mutator.Revert(context.Background(), Env{}, journal.Record{}); err != nil {
- t.Fatalf("revert on a cold start returned %v; it must resolve, because the proxy died "+
- "with the process and the fault went with it", err)
+ if err := mutator.Revert(
+ context.Background(),
+ Env{},
+ journal.Record{},
+ ); err != nil {
+ t.Fatalf(
+ "revert on a cold start returned %v; it must resolve, because the proxy died "+
+ "with the process and the fault went with it",
+ err,
+ )
}
}
@@ -228,7 +286,12 @@ func TestInProcessKindsAreNotOfferedForDirectInjection(t *testing.T) {
}
if IsDirect(kind) != wantDirect {
- t.Errorf("%s: IsDirect reports %v, want %v", kind, IsDirect(kind), wantDirect)
+ t.Errorf(
+ "%s: IsDirect reports %v, want %v",
+ kind,
+ IsDirect(kind),
+ wantDirect,
+ )
}
}
@@ -242,7 +305,10 @@ func TestInProcessKindsAreNotOfferedForDirectInjection(t *testing.T) {
}
if excluded == 0 {
- t.Errorf("no kind carries the %q prefix, so excluding it proves nothing", prefix)
+ t.Errorf(
+ "no kind carries the %q prefix, so excluding it proves nothing",
+ prefix,
+ )
}
for _, kind := range DirectKinds() {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go
index a2f95541..70c7b704 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go
@@ -11,12 +11,11 @@ import (
"slices"
"strings"
- "github.com/moby/moby/api/types/network"
-
"github.com/CarterPerez-dev/khaos/internal/dockerx"
"github.com/CarterPerez-dev/khaos/internal/idp"
"github.com/CarterPerez-dev/khaos/internal/inject/proxy"
"github.com/CarterPerez-dev/khaos/internal/journal"
+ "github.com/moby/moby/api/types/network"
)
const (
@@ -36,7 +35,9 @@ const (
var ErrAlreadyPaused = errors.New("that container is already paused")
-var ErrUnknownKind = errors.New("no injector is registered for this mutation kind")
+var ErrUnknownKind = errors.New(
+ "no injector is registered for this mutation kind",
+)
// Proxy, ProxyFault, IdP and IdPTrap are nil and zero for every tier that does
// not use them. Both the fault proxy and khaos's identity provider are per-run,
@@ -78,7 +79,12 @@ var registry = map[string]Mutator{
func Lookup(kind string) (Mutator, error) {
mutator, ok := registry[kind]
if !ok {
- return nil, fmt.Errorf(errUnknownKind, ErrUnknownKind, kind, strings.Join(DirectKinds(), ", "))
+ return nil, fmt.Errorf(
+ errUnknownKind,
+ ErrUnknownKind,
+ kind,
+ strings.Join(DirectKinds(), ", "),
+ )
}
return mutator, nil
}
@@ -176,7 +182,11 @@ type pausePayload struct {
// cannot pause something already paused, so there is no experiment to run, and
// a fault that cannot be applied should be refused by name before anything is
// journaled.
-func (pauseMutator) Plan(ctx context.Context, env Env, t dockerx.Target) (json.RawMessage, error) {
+func (pauseMutator) Plan(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+) (json.RawMessage, error) {
paused, err := env.Docker.Paused(ctx, t.ID)
if err != nil {
return nil, err
@@ -189,13 +199,22 @@ func (pauseMutator) Plan(ctx context.Context, env Env, t dockerx.Target) (json.R
return journal.EncodePayload(pausePayload{})
}
-func (pauseMutator) Apply(ctx context.Context, env Env, t dockerx.Target, _ json.RawMessage) error {
+func (pauseMutator) Apply(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+ _ json.RawMessage,
+) error {
return env.Docker.Pause(ctx, t.ID)
}
// Revert unpauses only what khaos paused. The journaled precondition is what
// makes that knowable from a cold start, where khaos has no memory of the run.
-func (pauseMutator) Revert(ctx context.Context, env Env, record journal.Record) error {
+func (pauseMutator) Revert(
+ ctx context.Context,
+ env Env,
+ record journal.Record,
+) error {
var payload pausePayload
if len(record.Payload) > 0 {
if err := record.DecodePayload(&payload); err != nil {
@@ -256,7 +275,11 @@ func (disconnectMutator) Describe(_ Env, t dockerx.Target) string {
return fmt.Sprintf(describeDisconnect, t.Name)
}
-func (disconnectMutator) Plan(ctx context.Context, env Env, t dockerx.Target) (json.RawMessage, error) {
+func (disconnectMutator) Plan(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+) (json.RawMessage, error) {
endpoints, err := env.Docker.Endpoints(ctx, t.ID)
if err != nil {
return nil, err
@@ -292,7 +315,12 @@ func (disconnectMutator) Plan(ctx context.Context, env Env, t dockerx.Target) (j
return journal.EncodePayload(payload)
}
-func (disconnectMutator) Apply(ctx context.Context, env Env, t dockerx.Target, raw json.RawMessage) error {
+func (disconnectMutator) Apply(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+ raw json.RawMessage,
+) error {
var payload disconnectPayload
if err := json.Unmarshal(raw, &payload); err != nil {
return err
@@ -307,7 +335,11 @@ func (disconnectMutator) Apply(ctx context.Context, env Env, t dockerx.Target, r
return nil
}
-func (disconnectMutator) Revert(ctx context.Context, env Env, record journal.Record) error {
+func (disconnectMutator) Revert(
+ ctx context.Context,
+ env Env,
+ record journal.Record,
+) error {
var payload disconnectPayload
if err := record.DecodePayload(&payload); err != nil {
return err
@@ -328,7 +360,12 @@ func (disconnectMutator) Revert(ctx context.Context, env Env, record journal.Rec
if _, attached := endpoints[entry.Network]; attached {
continue
}
- if err := env.Docker.Connect(ctx, entry.Network, record.TargetID, entry.settings()); err != nil {
+ if err := env.Docker.Connect(
+ ctx,
+ entry.Network,
+ record.TargetID,
+ entry.settings(),
+ ); err != nil {
failures = append(failures, err)
}
}
@@ -336,7 +373,11 @@ func (disconnectMutator) Revert(ctx context.Context, env Env, record journal.Rec
return errors.Join(failures...)
}
-func (pauseMutator) Confirm(ctx context.Context, env Env, t dockerx.Target) (string, bool, error) {
+func (pauseMutator) Confirm(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+) (string, bool, error) {
paused, err := env.Docker.Paused(ctx, t.ID)
if err != nil || !paused {
return "", false, err
@@ -344,7 +385,11 @@ func (pauseMutator) Confirm(ctx context.Context, env Env, t dockerx.Target) (str
return confirmPause, true, nil
}
-func (disconnectMutator) Confirm(ctx context.Context, env Env, t dockerx.Target) (string, bool, error) {
+func (disconnectMutator) Confirm(
+ ctx context.Context,
+ env Env,
+ t dockerx.Target,
+) (string, bool, error) {
endpoints, err := env.Docker.Endpoints(ctx, t.ID)
if err != nil {
return "", false, err
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go
index b7ac0753..fd4fd79b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go
@@ -42,8 +42,12 @@ const (
)
var (
- ErrDamaged = errors.New("the journal contains a line khaos cannot parse, so it may be hiding an outstanding fault")
- ErrNoPayload = errors.New("the journal record carries no payload, so khaos cannot tell what to restore")
+ ErrDamaged = errors.New(
+ "the journal contains a line khaos cannot parse, so it may be hiding an outstanding fault",
+ )
+ ErrNoPayload = errors.New(
+ "the journal record carries no payload, so khaos cannot tell what to restore",
+ )
)
func NewID() string {
@@ -101,7 +105,8 @@ func (r Record) Expired(now time.Time) bool {
}
func (r Record) Outstanding() bool {
- return r.Phase == PhasePending || r.Phase == PhaseApplied || r.Phase == PhaseFailed
+ return r.Phase == PhasePending || r.Phase == PhaseApplied ||
+ r.Phase == PhaseFailed
}
type Journal struct {
@@ -114,7 +119,12 @@ func Open(path string) (*Journal, error) {
return nil, fmt.Errorf(errOpen, err)
}
- file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, fileMode)
+ //nolint:gosec // khaos's own state dir, from statedir.Paths
+ file, err := os.OpenFile(
+ path,
+ os.O_CREATE|os.O_WRONLY|os.O_APPEND,
+ fileMode,
+ )
if err != nil {
return nil, fmt.Errorf(errOpen, err)
}
@@ -148,6 +158,7 @@ func (j *Journal) Close() error {
}
func Replay(path string) ([]Record, error) {
+ //nolint:gosec // khaos's own journal, from statedir.Paths
file, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
@@ -239,6 +250,7 @@ func Compact(path string) error {
temp := path + tempSuffix
+ //nolint:gosec // the compaction temp beside khaos's own journal
file, err := os.OpenFile(temp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fileMode)
if err != nil {
return fmt.Errorf(errCompact, err)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal_test.go
index 1cf2d61c..138c8890 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal_test.go
@@ -48,7 +48,9 @@ type payload struct {
func TestAppendAndReplayRoundTrip(t *testing.T) {
j := tempJournal(t)
- raw, err := EncodePayload(payload{Networks: []string{"shop_default", "shop_edge"}})
+ raw, err := EncodePayload(
+ payload{Networks: []string{"shop_default", "shop_edge"}},
+ )
if err != nil {
t.Fatalf("encode: %v", err)
}
@@ -85,8 +87,17 @@ func TestAppendAndReplayRoundTrip(t *testing.T) {
}
func TestDecodingAnAbsentPayloadIsNamed(t *testing.T) {
- if err := record("m1", PhaseApplied).DecodePayload(&payload{}); !errors.Is(err, ErrNoPayload) {
- t.Fatalf("got %v, want ErrNoPayload so a revert can tell empty from corrupt", err)
+ if err := record(
+ "m1",
+ PhaseApplied,
+ ).DecodePayload(&payload{}); !errors.Is(
+ err,
+ ErrNoPayload,
+ ) {
+ t.Fatalf(
+ "got %v, want ErrNoPayload so a revert can tell empty from corrupt",
+ err,
+ )
}
}
@@ -112,13 +123,19 @@ func TestOutstandingCollapsesToTheLatestPhaseAndKeepsOrder(t *testing.T) {
}
if len(out) != 2 {
- t.Fatalf("got %d outstanding, want 2 (m1 applied, m3 pending)", len(out))
+ t.Fatalf(
+ "got %d outstanding, want 2 (m1 applied, m3 pending)",
+ len(out),
+ )
}
if out[0].MutationID != "m1" || out[1].MutationID != "m3" {
- t.Fatalf("outstanding came back as %s,%s; first-seen order must hold because "+
- "reclaim reverts in reverse to undo most-recent-first",
- out[0].MutationID, out[1].MutationID)
+ t.Fatalf(
+ "outstanding came back as %s,%s; first-seen order must hold because "+
+ "reclaim reverts in reverse to undo most-recent-first",
+ out[0].MutationID,
+ out[1].MutationID,
+ )
}
}
@@ -147,7 +164,10 @@ func TestOutstandingKeepsTheLatestPayload(t *testing.T) {
var decoded payload
if err := out[0].DecodePayload(&decoded); err != nil {
- t.Fatalf("the collapse dropped the payload, so a revert would silently do nothing: %v", err)
+ t.Fatalf(
+ "the collapse dropped the payload, so a revert would silently do nothing: %v",
+ err,
+ )
}
if len(decoded.Networks) != 1 {
@@ -157,12 +177,16 @@ func TestOutstandingKeepsTheLatestPayload(t *testing.T) {
func TestPendingAndFailedAreBothOutstanding(t *testing.T) {
if !record("m1", PhasePending).Outstanding() {
- t.Fatal("a mutation journaled before it was applied must still be reclaimed, " +
- "because khaos may have died between the write and the apply")
+ t.Fatal(
+ "a mutation journaled before it was applied must still be reclaimed, " +
+ "because khaos may have died between the write and the apply",
+ )
}
if !record("m1", PhaseFailed).Outstanding() {
- t.Fatal("a mutation whose apply failed may have partially landed and must stay reclaimable")
+ t.Fatal(
+ "a mutation whose apply failed may have partially landed and must stay reclaimable",
+ )
}
if record("m1", PhaseReverted).Outstanding() {
@@ -174,8 +198,10 @@ func TestARecordWithNoLeaseIsTreatedAsExpired(t *testing.T) {
r := record("m1", PhaseApplied)
if !r.Expired(time.Now().UTC()) {
- t.Fatal("a record carrying no lease was treated as immortal; every injected fault " +
- "must carry a lease, so a record without one is malformed and must fail safe")
+ t.Fatal(
+ "a record carrying no lease was treated as immortal; every injected fault " +
+ "must carry a lease, so a record without one is malformed and must fail safe",
+ )
}
r.ExpiresAt = time.Now().UTC().Add(time.Hour)
@@ -208,12 +234,18 @@ func TestADamagedLineIsQuarantinedNotFatal(t *testing.T) {
out, err := Outstanding(path)
if !errors.Is(err, ErrDamaged) {
- t.Fatalf("got %v; a damaged line must be reported, or khaos silently claims completeness", err)
+ t.Fatalf(
+ "got %v; a damaged line must be reported, or khaos silently claims completeness",
+ err,
+ )
}
if len(out) != 2 {
- t.Fatalf("got %d outstanding records; the readable records must still be acted on, "+
- "or one bad line strands every fault on the machine forever", len(out))
+ t.Fatalf(
+ "got %d outstanding records; the readable records must still be acted on, "+
+ "or one bad line strands every fault on the machine forever",
+ len(out),
+ )
}
}
@@ -247,7 +279,11 @@ func TestCompactKeepsOnlyOutstandingRecords(t *testing.T) {
}
if after.Size() >= before.Size() {
- t.Fatalf("compaction grew the journal from %d to %d bytes", before.Size(), after.Size())
+ t.Fatalf(
+ "compaction grew the journal from %d to %d bytes",
+ before.Size(),
+ after.Size(),
+ )
}
out, err := Outstanding(j.Path())
@@ -273,8 +309,11 @@ func TestTheJournalIsNotWorldReadable(t *testing.T) {
}
if info.Mode().Perm() != fileMode {
- t.Fatalf("journal mode is %v, want %v; it records container names and network topology",
- info.Mode().Perm(), fs.FileMode(fileMode))
+ t.Fatalf(
+ "journal mode is %v, want %v; it records container names and network topology",
+ info.Mode().Perm(),
+ fs.FileMode(fileMode),
+ )
}
dir, err := os.Stat(filepath.Dir(j.Path()))
@@ -283,7 +322,11 @@ func TestTheJournalIsNotWorldReadable(t *testing.T) {
}
if dir.Mode().Perm() != wantDirMode {
- t.Fatalf("state directory mode is %v, want %v", dir.Mode().Perm(), wantDirMode)
+ t.Fatalf(
+ "state directory mode is %v, want %v",
+ dir.Mode().Perm(),
+ wantDirMode,
+ )
}
}
@@ -295,8 +338,10 @@ func TestAppendSurfacesAWriteFailure(t *testing.T) {
}
if err := j.Append(record("m1", PhaseApplied)); err == nil {
- t.Fatal("append on a closed journal reported success, so a durability failure " +
- "would be swallowed while the fault stays applied")
+ t.Fatal(
+ "append on a closed journal reported success, so a durability failure " +
+ "would be swallowed while the fault stays applied",
+ )
}
}
@@ -306,7 +351,10 @@ func TestIDsAreDistinct(t *testing.T) {
for range 128 {
id := NewID()
if seen[id] {
- t.Fatalf("duplicate id %q; two mutations would collapse into one journal entry", id)
+ t.Fatalf(
+ "duplicate id %q; two mutations would collapse into one journal entry",
+ id,
+ )
}
seen[id] = true
}
@@ -345,7 +393,10 @@ func TestAReversionCannotBeUndoneByALaterApplied(t *testing.T) {
}
if len(outstanding) != 0 {
- t.Fatalf("a reverted mutation came back as outstanding: %+v", outstanding)
+ t.Fatalf(
+ "a reverted mutation came back as outstanding: %+v",
+ outstanding,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/lease/lease_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/lease/lease_test.go
index ea1d4558..b83307c1 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/lease/lease_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/lease/lease_test.go
@@ -19,7 +19,9 @@ func TestNewLeaseIsAliveImmediately(t *testing.T) {
}
if l.ID() == "" {
- t.Fatal("a lease was issued with no identifier, so the journal cannot attribute a fault to it")
+ t.Fatal(
+ "a lease was issued with no identifier, so the journal cannot attribute a fault to it",
+ )
}
}
@@ -27,7 +29,11 @@ func TestTTLIsClampedToAFloor(t *testing.T) {
l := New(time.Millisecond)
if l.TTL() != MinimumTTL {
- t.Fatalf("TTL %v was accepted; a lease shorter than %v would expire mid-injection", l.TTL(), MinimumTTL)
+ t.Fatalf(
+ "TTL %v was accepted; a lease shorter than %v would expire mid-injection",
+ l.TTL(),
+ MinimumTTL,
+ )
}
}
@@ -39,7 +45,9 @@ func TestLeaseExpiresWithoutRenewal(t *testing.T) {
}
if !l.Expired(time.Now().UTC().Add(MinimumTTL + time.Second)) {
- t.Fatal("a lease that is never renewed must expire, or the dead man's switch never fires")
+ t.Fatal(
+ "a lease that is never renewed must expire, or the dead man's switch never fires",
+ )
}
}
@@ -65,13 +73,19 @@ func TestRenewalAlwaysFitsTwiceInsideTheTTL(t *testing.T) {
l := New(ttl)
if l.RenewalInterval() >= l.TTL() {
- t.Fatalf("renewal interval %v is not shorter than TTL %v, so one missed tick drops the fault",
- l.RenewalInterval(), l.TTL())
+ t.Fatalf(
+ "renewal interval %v is not shorter than TTL %v, so one missed tick drops the fault",
+ l.RenewalInterval(),
+ l.TTL(),
+ )
}
if l.TTL()/l.RenewalInterval() < 2 {
- t.Fatalf("only %v fits inside TTL %v; a single hiccup would expire a live fault",
- l.TTL()/l.RenewalInterval(), l.TTL())
+ t.Fatalf(
+ "only %v fits inside TTL %v; a single hiccup would expire a live fault",
+ l.TTL()/l.RenewalInterval(),
+ l.TTL(),
+ )
}
})
}
@@ -102,12 +116,14 @@ func TestKeepRenewsUntilCancelled(t *testing.T) {
}
cancel()
- if err := <-done; err != context.Canceled {
+ if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("Keep returned %v, want context.Canceled", err)
}
if renewals.Load() == 0 {
- t.Fatal("Keep never renewed, so a held fault would expire under a live khaos")
+ t.Fatal(
+ "Keep never renewed, so a held fault would expire under a live khaos",
+ )
}
}
@@ -128,12 +144,18 @@ func TestKeepStopsWhenRenewalFails(t *testing.T) {
elapsed := time.Since(started)
if !errors.Is(got, want) {
- t.Fatalf("Keep returned %v; a journal write failure during renewal must surface, "+
- "not be swallowed while the fault stays applied", got)
+ t.Fatalf(
+ "Keep returned %v; a journal write failure during renewal must surface, "+
+ "not be swallowed while the fault stays applied",
+ got,
+ )
}
if elapsed > l.RenewalInterval()*3 {
- t.Fatalf("Keep took %v to notice a failing renewal, which is longer than it should wait", elapsed)
+ t.Fatalf(
+ "Keep took %v to notice a failing renewal, which is longer than it should wait",
+ elapsed,
+ )
}
}
@@ -143,7 +165,10 @@ func TestLeaseIDsAreDistinct(t *testing.T) {
for range 64 {
id := New(time.Minute).ID()
if seen[id] {
- t.Fatalf("duplicate lease id %q; two runs would reclaim each other's faults", id)
+ t.Fatalf(
+ "duplicate lease id %q; two runs would reclaim each other's faults",
+ id,
+ )
}
seen[id] = true
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go
index a482eed7..0afca58c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go
@@ -28,10 +28,14 @@ const (
)
var (
- ErrHeld = errors.New("another khaos instance is already running")
- ErrUnlockable = errors.New("khaos could not take its instance lock, so it cannot be sure another run is not already holding a fault")
+ ErrHeld = errors.New("another khaos instance is already running")
+ ErrUnlockable = errors.New(
+ "khaos could not take its instance lock, so it cannot be sure another run is not already holding a fault",
+ )
unsupportedFS = []error{unix.ENOLCK, unix.ENOSYS, unix.EOPNOTSUPP}
- ErrUnsupported = errors.New("this filesystem does not support file locking" + fixUnsupported)
+ ErrUnsupported = errors.New(
+ "this filesystem does not support file locking" + fixUnsupported,
+ )
)
type Lock struct {
@@ -39,23 +43,28 @@ type Lock struct {
}
func Acquire(path string) (*Lock, error) {
+ //nolint:gosec // khaos's own state dir, from statedir.Paths
if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {
return nil, fmt.Errorf(errOpen, err)
}
+ //nolint:gosec // khaos's own state dir, from statedir.Paths
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, fileMode)
if err != nil {
return nil, fmt.Errorf(errOpen, err)
}
- if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ if err := unix.Flock(
+ fd(file),
+ unix.LOCK_EX|unix.LOCK_NB,
+ ); err != nil {
holder := readHolder(file)
_ = file.Close()
return nil, classify(err, holder)
}
if err := recordHolder(file); err != nil {
- _ = unix.Flock(int(file.Fd()), unix.LOCK_UN)
+ _ = unix.Flock(fd(file), unix.LOCK_UN)
_ = file.Close()
return nil, err
}
@@ -64,13 +73,20 @@ func Acquire(path string) (*Lock, error) {
}
func (l *Lock) Release() error {
- if err := unix.Flock(int(l.file.Fd()), unix.LOCK_UN); err != nil {
+ if err := unix.Flock(fd(l.file), unix.LOCK_UN); err != nil {
_ = l.file.Close()
return err
}
return l.file.Close()
}
+// fd narrows a descriptor for the flock wrapper, which wants an int. A file
+// descriptor is bounded by RLIMIT_NOFILE, orders of magnitude below MaxInt, so
+// the conversion cannot overflow.
+func fd(file *os.File) int {
+ return int(file.Fd()) //nolint:gosec // bounded by RLIMIT_NOFILE
+}
+
func classify(err error, holder string) error {
if errors.Is(err, unix.EWOULDBLOCK) {
return fmt.Errorf(errHeldBy, ErrHeld, orUnknown(holder))
@@ -90,7 +106,10 @@ func recordHolder(file *os.File) error {
return fmt.Errorf(errWrite, err)
}
- if _, err := file.WriteAt([]byte(strconv.Itoa(os.Getpid())), 0); err != nil {
+ if _, err := file.WriteAt(
+ []byte(strconv.Itoa(os.Getpid())),
+ 0,
+ ); err != nil {
return fmt.Errorf(errWrite, err)
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix_test.go
index 72b55631..763708f7 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix_test.go
@@ -82,7 +82,9 @@ func TestASecondAcquireIsRefused(t *testing.T) {
second, err := Acquire(path)
if err == nil {
_ = second.Release()
- t.Fatal("two khaos instances held the lock at once, so both could inject into the same target")
+ t.Fatal(
+ "two khaos instances held the lock at once, so both could inject into the same target",
+ )
}
if !errors.Is(err, ErrHeld) {
@@ -101,8 +103,11 @@ func TestTheRefusalNamesTheHoldingProcessAndTheFix(t *testing.T) {
wantPid := strconv.Itoa(holder.Process.Pid)
if !strings.Contains(err.Error(), wantPid) {
- t.Fatalf("the refusal %q does not name the holding pid %s, so the operator cannot find it",
- err, wantPid)
+ t.Fatalf(
+ "the refusal %q does not name the holding pid %s, so the operator cannot find it",
+ err,
+ wantPid,
+ )
}
if !strings.Contains(err.Error(), "khaos reclaim") {
@@ -132,8 +137,10 @@ func TestTheLockIsReleasedWhenTheHolderIsKilled(t *testing.T) {
time.Sleep(10 * time.Millisecond)
}
- t.Fatal("the lock stayed held after its owner was killed; flock was chosen precisely " +
- "so the kernel releases it, and a stale lock would block every later khaos run")
+ t.Fatal(
+ "the lock stayed held after its owner was killed; flock was chosen precisely " +
+ "so the kernel releases it, and a stale lock would block every later khaos run",
+ )
}
func TestReleaseAllowsReacquisition(t *testing.T) {
@@ -173,7 +180,11 @@ func TestAcquireCreatesTheStateDirectoryPrivately(t *testing.T) {
}
if info.Mode().Perm() != fileMode {
- t.Fatalf("lock mode is %v, want %v", info.Mode().Perm(), os.FileMode(fileMode))
+ t.Fatalf(
+ "lock mode is %v, want %v",
+ info.Mode().Perm(),
+ os.FileMode(fileMode),
+ )
}
dir, err := os.Stat(filepath.Dir(path))
@@ -182,6 +193,10 @@ func TestAcquireCreatesTheStateDirectoryPrivately(t *testing.T) {
}
if dir.Mode().Perm() != dirMode {
- t.Fatalf("state directory mode is %v, want %v", dir.Mode().Perm(), os.FileMode(dirMode))
+ t.Fatalf(
+ "state directory mode is %v, want %v",
+ dir.Mode().Perm(),
+ os.FileMode(dirMode),
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go
index 58b6ac54..38bfd487 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go
@@ -78,7 +78,10 @@ func NewHTTP(options HTTPOptions) *HTTPProbe {
// a probe that resumes passes against a certificate that has
// since expired. A nil cache is what actually disables it:
// crypto/tls only stores and loads sessions when one is set.
- TLSClientConfig: &tls.Config{ClientSessionCache: nil, MinVersion: tls.VersionTLS12},
+ TLSClientConfig: &tls.Config{
+ ClientSessionCache: nil,
+ MinVersion: tls.VersionTLS12,
+ },
DisableKeepAlives: true,
// Setting TLSClientConfig disables automatic HTTP/2 unless this
// is set, and h2 connection reuse is itself a fail-open khaos
@@ -102,9 +105,19 @@ func (p *HTTPProbe) Credential() Credential {
func (p *HTTPProbe) Describe() string {
if p.options.Mint != nil {
- return fmt.Sprintf(describeHTTPMint, p.options.Method, p.options.URL, p.options.Credential)
+ return fmt.Sprintf(
+ describeHTTPMint,
+ p.options.Method,
+ p.options.URL,
+ p.options.Credential,
+ )
}
- return fmt.Sprintf(describeHTTP, p.options.Method, p.options.URL, p.options.Credential)
+ return fmt.Sprintf(
+ describeHTTP,
+ p.options.Method,
+ p.options.URL,
+ p.options.Credential,
+ )
}
func (p *HTTPProbe) Run(ctx context.Context) Outcome {
@@ -116,7 +129,12 @@ func (p *HTTPProbe) Run(ctx context.Context) Outcome {
Disposition: Unknown,
}
- request, err := http.NewRequestWithContext(ctx, p.options.Method, p.options.URL, nil)
+ request, err := http.NewRequestWithContext(
+ ctx,
+ p.options.Method,
+ p.options.URL,
+ nil,
+ )
if err != nil {
outcome.Disposition = ProbeFailed
outcome.Detail = fmt.Sprintf(detailError, err)
@@ -179,7 +197,8 @@ func (p *HTTPProbe) credential(ctx context.Context) (string, error) {
}
func transportDisposition(err error) Disposition {
- if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, os.ErrDeadlineExceeded) {
+ if errors.Is(err, context.DeadlineExceeded) ||
+ errors.Is(err, os.ErrDeadlineExceeded) {
return TimedOut
}
if errors.Is(err, context.Canceled) {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go
index 80b41ca9..639f327f 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go
@@ -74,6 +74,11 @@ func (s Stream) AcceptedAfter(rejected bool) int {
if rejected {
count++
}
+ default:
+ // A probe that neither answered nor refused is not evidence in
+ // either direction, so it must not move the count OR the latch. An
+ // outage counted as a refusal would manufacture the control giving
+ // way that this function exists to detect.
}
}
@@ -138,6 +143,9 @@ func (s Stream) AcceptedSinceLastRefusal() int {
count = 0
case Accepted:
count++
+ default:
+ // Neither an acceptance nor a refusal, so the run is neither
+ // extended nor broken by it.
}
}
@@ -184,6 +192,8 @@ func (s Stream) RejectedAfter(accepted bool) int {
if accepted {
count++
}
+ default:
+ // Not evidence either way, so neither the count nor the latch moves.
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample_test.go
index 18bdbe2b..866bf7c1 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample_test.go
@@ -69,9 +69,13 @@ func TestAcceptedAfterRejectedCountsOrderNotTotals(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
got := streamOf(tc.dispositions...).AcceptedAfterRejected()
if got != tc.want {
- t.Fatalf("got %d, want %d; this is the test that distinguishes "+
- "'a credential it had already refused was later honoured' from "+
- "'something succeeded at some point'", got, tc.want)
+ t.Fatalf(
+ "got %d, want %d; this is the test that distinguishes "+
+ "'a credential it had already refused was later honoured' from "+
+ "'something succeeded at some point'",
+ got,
+ tc.want,
+ )
}
})
}
@@ -105,8 +109,11 @@ func TestWindowLengthIsThePairedCount(t *testing.T) {
w.Record(Outcome{Credential: Invalid, Disposition: Rejected})
if w.Len() != 1 {
- t.Fatalf("Len() = %d, want 1; a window is only as long as its shorter stream, because "+
- "a verdict needs both halves of the pair", w.Len())
+ t.Fatalf(
+ "Len() = %d, want 1; a window is only as long as its shorter stream, because "+
+ "a verdict needs both halves of the pair",
+ w.Len(),
+ )
}
}
@@ -117,7 +124,11 @@ func TestRecordRoutesByCredential(t *testing.T) {
w.Record(Outcome{Credential: Invalid, Disposition: Rejected})
if w.Valid.Len() != 1 || w.Invalid.Len() != 1 {
- t.Fatalf("valid=%d invalid=%d, want 1 and 1", w.Valid.Len(), w.Invalid.Len())
+ t.Fatalf(
+ "valid=%d invalid=%d, want 1 and 1",
+ w.Valid.Len(),
+ w.Invalid.Len(),
+ )
}
if w.Valid.Outcomes[0].Disposition != Accepted {
@@ -141,10 +152,16 @@ func TestRejectedAfterCountsTheTargetGivingUp(t *testing.T) {
// cache for the first seconds of an outage and then starts
// refusing. Asking only whether it ever served calls that a clean
// survival.
- name: "served from cache, then refused",
- seed: true,
- dispositions: []Disposition{Accepted, Accepted, Rejected, Rejected, Rejected},
- want: 3,
+ name: "served from cache, then refused",
+ seed: true,
+ dispositions: []Disposition{
+ Accepted,
+ Accepted,
+ Rejected,
+ Rejected,
+ Rejected,
+ },
+ want: 3,
},
{
name: "served throughout",
@@ -170,7 +187,10 @@ func TestRejectedAfterCountsTheTargetGivingUp(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
s := Stream{Credential: Valid}
for _, d := range tc.dispositions {
- s.Outcomes = append(s.Outcomes, Outcome{Credential: Valid, Disposition: d})
+ s.Outcomes = append(
+ s.Outcomes,
+ Outcome{Credential: Valid, Disposition: d},
+ )
}
if got := s.RejectedAfter(tc.seed); got != tc.want {
@@ -188,8 +208,11 @@ func TestProbeFailuresAreNotChargedToTheTarget(t *testing.T) {
}}
if s.Countable() != 2 {
- t.Fatalf("Countable() = %d, want 2; khaos's own failure is not a target outcome and "+
- "must not enter any rate", s.Countable())
+ t.Fatalf(
+ "Countable() = %d, want 2; khaos's own failure is not a target outcome and "+
+ "must not enter any rate",
+ s.Countable(),
+ )
}
if ProbeFailed.Answered() {
@@ -199,16 +222,24 @@ func TestProbeFailuresAreNotChargedToTheTarget(t *testing.T) {
// The bounded-stale pattern is a PASS, and a plain count of acceptances reports
// it as a bypass. These are the three shapes that have to separate.
-func TestAcceptedSinceLastRefusalSeparatesABoundedCacheFromABrokenOne(t *testing.T) {
+func TestAcceptedSinceLastRefusalSeparatesABoundedCacheFromABrokenOne(
+ t *testing.T,
+) {
cases := []struct {
name string
sequence []Disposition
want int
}{
{
- name: "a bounded cache lapses and stays lapsed",
- sequence: []Disposition{Accepted, Accepted, Rejected, Rejected, Rejected},
- want: 0,
+ name: "a bounded cache lapses and stays lapsed",
+ sequence: []Disposition{
+ Accepted,
+ Accepted,
+ Rejected,
+ Rejected,
+ Rejected,
+ },
+ want: 0,
},
{
name: "a cache with no expiry never lapses",
@@ -216,9 +247,15 @@ func TestAcceptedSinceLastRefusalSeparatesABoundedCacheFromABrokenOne(t *testing
want: 4,
},
{
- name: "a cache that re-populates after refusing is its own bug",
- sequence: []Disposition{Accepted, Rejected, Rejected, Accepted, Accepted},
- want: 2,
+ name: "a cache that re-populates after refusing is its own bug",
+ sequence: []Disposition{
+ Accepted,
+ Rejected,
+ Rejected,
+ Accepted,
+ Accepted,
+ },
+ want: 2,
},
{
name: "a target that refused throughout",
@@ -241,11 +278,18 @@ func TestAcceptedSinceLastRefusalSeparatesABoundedCacheFromABrokenOne(t *testing
t.Run(each.name, func(t *testing.T) {
stream := Stream{Credential: Revoked}
for _, disposition := range each.sequence {
- stream.Outcomes = append(stream.Outcomes, Outcome{Disposition: disposition})
+ stream.Outcomes = append(
+ stream.Outcomes,
+ Outcome{Disposition: disposition},
+ )
}
if got := stream.AcceptedSinceLastRefusal(); got != each.want {
- t.Fatalf("AcceptedSinceLastRefusal() = %d, want %d", got, each.want)
+ t.Fatalf(
+ "AcceptedSinceLastRefusal() = %d, want %d",
+ got,
+ each.want,
+ )
}
})
}
@@ -262,24 +306,48 @@ func TestAcceptedSinceLastRefusalDisagreesWithAPlainCount(t *testing.T) {
}}
if bounded.Count(Accepted) == bounded.AcceptedSinceLastRefusal() {
- t.Fatal("the order-sensitive count agrees with the plain count on a bounded cache, " +
- "so nothing distinguishes the defensible pattern from the broken one")
+ t.Fatal(
+ "the order-sensitive count agrees with the plain count on a bounded cache, " +
+ "so nothing distinguishes the defensible pattern from the broken one",
+ )
}
}
// The case AcceptedSinceLastRefusal destroys. Enforcement resumed, the
// invalidated credential got through anyway, and a later refusal erased it.
-func TestAcceptedDespiteLapseKeepsAReacceptanceALaterRefusalWouldErase(t *testing.T) {
+func TestAcceptedDespiteLapseKeepsAReacceptanceALaterRefusalWouldErase(
+ t *testing.T,
+) {
cases := []struct {
name string
sequence []Disposition
despiteLapse int
sinceRefusal int
}{
- {"never lapsed", []Disposition{Accepted, Accepted, Accepted, Accepted}, 4, 4},
- {"lapsed and stayed lapsed", []Disposition{Accepted, Accepted, Rejected, Rejected}, 0, 0},
- {"came back after a lapse", []Disposition{Rejected, Accepted, Rejected}, 1, 0},
- {"came back and stayed", []Disposition{Accepted, Rejected, Rejected, Accepted, Accepted}, 2, 2},
+ {
+ "never lapsed",
+ []Disposition{Accepted, Accepted, Accepted, Accepted},
+ 4,
+ 4,
+ },
+ {
+ "lapsed and stayed lapsed",
+ []Disposition{Accepted, Accepted, Rejected, Rejected},
+ 0,
+ 0,
+ },
+ {
+ "came back after a lapse",
+ []Disposition{Rejected, Accepted, Rejected},
+ 1,
+ 0,
+ },
+ {
+ "came back and stayed",
+ []Disposition{Accepted, Rejected, Rejected, Accepted, Accepted},
+ 2,
+ 2,
+ },
{"refused throughout", []Disposition{Rejected, Rejected}, 0, 0},
{"empty", nil, 0, 0},
}
@@ -290,15 +358,24 @@ func TestAcceptedDespiteLapseKeepsAReacceptanceALaterRefusalWouldErase(t *testin
t.Run(each.name, func(t *testing.T) {
stream := Stream{Credential: Revoked}
for _, d := range each.sequence {
- stream.Outcomes = append(stream.Outcomes, Outcome{Disposition: d})
+ stream.Outcomes = append(
+ stream.Outcomes,
+ Outcome{Disposition: d},
+ )
}
if got := stream.AcceptedDespiteLapse(); got != each.despiteLapse {
- t.Fatalf("AcceptedDespiteLapse() = %d, want %d", got, each.despiteLapse)
+ t.Fatalf(
+ "AcceptedDespiteLapse() = %d, want %d",
+ got,
+ each.despiteLapse,
+ )
}
if stream.AcceptedSinceLastRefusal() != each.sinceRefusal {
- t.Fatalf("the older count changed behaviour; this test pins the difference")
+ t.Fatalf(
+ "the older count changed behaviour; this test pins the difference",
+ )
}
if each.despiteLapse != each.sinceRefusal {
@@ -310,6 +387,8 @@ func TestAcceptedDespiteLapseKeepsAReacceptanceALaterRefusalWouldErase(t *testin
// The two must disagree somewhere, or replacing one with the other fixed
// nothing and this whole test is decoration.
if !disagreed {
- t.Fatal("AcceptedDespiteLapse never differs from AcceptedSinceLastRefusal across these cases")
+ t.Fatal(
+ "AcceptedDespiteLapse never differs from AcceptedSinceLastRefusal across these cases",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/unique_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/unique_test.go
index 039e0759..8f5add47 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/unique_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/unique_test.go
@@ -23,12 +23,14 @@ func recorder(t *testing.T) (*httptest.Server, func() []string) {
var mu sync.Mutex
seen := []string{}
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- seen = append(seen, r.Header.Get("Authorization"))
- mu.Unlock()
- w.WriteHeader(http.StatusUnauthorized)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ seen = append(seen, r.Header.Get("Authorization"))
+ mu.Unlock()
+ w.WriteHeader(http.StatusUnauthorized)
+ }),
+ )
t.Cleanup(server.Close)
return server, func() []string {
@@ -59,8 +61,13 @@ func TestTheNegativeControlCarriesAFreshCredentialPerRequest(t *testing.T) {
})
for range samples {
- if outcome := p.Run(context.Background()); outcome.Disposition != Rejected {
- t.Fatalf("the recorder did not reject the credential, got %s", outcome.Disposition)
+ if outcome := p.Run(
+ context.Background(),
+ ); outcome.Disposition != Rejected {
+ t.Fatalf(
+ "the recorder did not reject the credential, got %s",
+ outcome.Disposition,
+ )
}
}
@@ -72,16 +79,23 @@ func TestTheNegativeControlCarriesAFreshCredentialPerRequest(t *testing.T) {
distinct := map[string]bool{}
for _, header := range headers {
if header == bearer+fixedToken {
- t.Fatalf("the negative control sent the bare fixed credential %q; a credential-keyed "+
- "decision cache answers every probe from one cached refusal and a control that "+
- "stops enforcing during the fault is never exercised", fixedToken)
+ t.Fatalf(
+ "the negative control sent the bare fixed credential %q; a credential-keyed "+
+ "decision cache answers every probe from one cached refusal and a control that "+
+ "stops enforcing during the fault is never exercised",
+ fixedToken,
+ )
}
distinct[header] = true
}
if len(distinct) != samples {
- t.Fatalf("the negative control sent %d distinct credentials across %d requests; every "+
- "repeat is a probe the target can answer from cache", len(distinct), samples)
+ t.Fatalf(
+ "the negative control sent %d distinct credentials across %d requests; every "+
+ "repeat is a probe the target can answer from cache",
+ len(distinct),
+ samples,
+ )
}
}
@@ -103,7 +117,11 @@ func TestTheValidProbeSendsOneStableCredential(t *testing.T) {
for i, header := range sent() {
if header != bearer+fixedToken {
- t.Fatalf("request %d carried %q, want the operator's credential unchanged", i, header)
+ t.Fatalf(
+ "request %d carried %q, want the operator's credential unchanged",
+ i,
+ header,
+ )
}
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/discovery_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/discovery_test.go
index a58a6456..1b831053 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/discovery_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/discovery_test.go
@@ -49,11 +49,18 @@ type tieredReader struct {
address string
}
-func (r tieredReader) Targets(context.Context, dockerx.Filter) ([]dockerx.Target, error) {
+func (r tieredReader) Targets(
+ context.Context,
+ dockerx.Filter,
+) ([]dockerx.Target, error) {
return r.targets, nil
}
-func (r tieredReader) PublishedPort(_ context.Context, id string, _ int) (int, error) {
+func (r tieredReader) PublishedPort(
+ _ context.Context,
+ id string,
+ _ int,
+) (int, error) {
port, ok := r.ports[id]
if !ok {
return 0, errors.New("no published port for " + id)
@@ -61,11 +68,18 @@ func (r tieredReader) PublishedPort(_ context.Context, id string, _ int) (int, e
return port, nil
}
-func (r tieredReader) ContainerEnv(_ context.Context, id string) (map[string]string, error) {
+func (r tieredReader) ContainerEnv(
+ _ context.Context,
+ id string,
+) (map[string]string, error) {
return r.environ[id], nil
}
-func (r tieredReader) NetworkAddress(context.Context, string, string) (string, error) {
+func (r tieredReader) NetworkAddress(
+ context.Context,
+ string,
+ string,
+) (string, error) {
return r.address, nil
}
@@ -74,7 +88,13 @@ func (r tieredReader) BridgeGateway(context.Context) (string, error) {
}
func container(id, name string) dockerx.Target {
- return dockerx.Target{ID: id, Name: name, Project: ProjectName, Running: true, Inspected: true}
+ return dockerx.Target{
+ ID: id,
+ Name: name,
+ Project: ProjectName,
+ Running: true,
+ Inspected: true,
+ }
}
// fullRange is every container a complete range runs, with the two khaos-side
@@ -93,7 +113,11 @@ func fullRange() tieredReader {
verifierID: verifierPort,
},
environ: map[string]map[string]string{
- proxiedID: {EnvUpstream: "http://host.docker.internal:" + strconv.Itoa(proxyPort)},
+ proxiedID: {
+ EnvUpstream: "http://host.docker.internal:" + strconv.Itoa(
+ proxyPort,
+ ),
+ },
verifierID: {EnvIssuer: testIssuer},
},
bridge: bridgeIP,
@@ -172,16 +196,33 @@ func TestAMissingVerifierGatewayIsNotFatal(t *testing.T) {
}
if lab.Port != directPort || lab.ProxyPort != proxyPort {
- t.Fatalf("the first two tiers did not survive: port=%d proxy=%d", lab.Port, lab.ProxyPort)
+ t.Fatalf(
+ "the first two tiers did not survive: port=%d proxy=%d",
+ lab.Port,
+ lab.ProxyPort,
+ )
}
if lab.VerifierPort != 0 || lab.IdPPort != 0 || lab.Issuer != "" {
- t.Fatalf("khaos invented an identity tier that is not running: port=%d idp=%d issuer=%q",
- lab.VerifierPort, lab.IdPPort, lab.Issuer)
+ t.Fatalf(
+ "khaos invented an identity tier that is not running: port=%d idp=%d issuer=%q",
+ lab.VerifierPort,
+ lab.IdPPort,
+ lab.Issuer,
+ )
}
- if _, _, err := lab.IdPEndpoint(context.Background(), reader); !errors.Is(err, ErrRangeIncomplete) {
- t.Fatalf("IdPEndpoint returned %v, want ErrRangeIncomplete so the refusal names the missing container", err)
+ if _, _, err := lab.IdPEndpoint(
+ context.Background(),
+ reader,
+ ); !errors.Is(
+ err,
+ ErrRangeIncomplete,
+ ) {
+ t.Fatalf(
+ "IdPEndpoint returned %v, want ErrRangeIncomplete so the refusal names the missing container",
+ err,
+ )
}
}
@@ -211,7 +252,10 @@ func TestAVerifierGatewayWithNoUsableIssuerIsRefusedByName(t *testing.T) {
}
if !strings.Contains(err.Error(), VerifierGatewayName) {
- t.Fatalf("the refusal does not name the container at fault: %v", err)
+ t.Fatalf(
+ "the refusal does not name the container at fault: %v",
+ err,
+ )
}
})
}
@@ -237,7 +281,10 @@ func TestAProxiedGatewayWithNoUsableUpstreamIsRefusedByName(t *testing.T) {
}
if !strings.Contains(err.Error(), ProxiedGatewayName) {
- t.Fatalf("the refusal does not name the container at fault: %v", err)
+ t.Fatalf(
+ "the refusal does not name the container at fault: %v",
+ err,
+ )
}
})
}
@@ -265,26 +312,45 @@ func TestIdPEndpointBindsTheBridgeAndKeepsTheIssuerVerbatim(t *testing.T) {
host, port, err := net.SplitHostPort(listen)
if err != nil {
- t.Fatalf("the listen address is not a host and port: %q (%v)", listen, err)
+ t.Fatalf(
+ "the listen address is not a host and port: %q (%v)",
+ listen,
+ err,
+ )
}
if host != bridgeIP {
- t.Errorf("khaos would bind %q; it has to bind the discovered bridge gateway %q, because a "+
- "listener anywhere else is unreachable from the container", host, bridgeIP)
+ t.Errorf(
+ "khaos would bind %q; it has to bind the discovered bridge gateway %q, because a "+
+ "listener anywhere else is unreachable from the container",
+ host,
+ bridgeIP,
+ )
}
if port != strconv.Itoa(idpPort) {
- t.Errorf("khaos would bind port %s, and the container will dial %d", port, idpPort)
+ t.Errorf(
+ "khaos would bind port %s, and the container will dial %d",
+ port,
+ idpPort,
+ )
}
if issuer != testIssuer {
- t.Errorf("khaos would mint under %q and the target trusts %q; one character of difference "+
- "refuses every credential khaos sends", issuer, testIssuer)
+ t.Errorf(
+ "khaos would mint under %q and the target trusts %q; one character of difference "+
+ "refuses every credential khaos sends",
+ issuer,
+ testIssuer,
+ )
}
if host == "127.0.0.1" || host == "0.0.0.0" || host == "" {
- t.Errorf("khaos would bind %q, which is either unreachable from containers or exposed off "+
- "the host; a deliberately-wrong identity provider must be neither", host)
+ t.Errorf(
+ "khaos would bind %q, which is either unreachable from containers or exposed off "+
+ "the host; a deliberately-wrong identity provider must be neither",
+ host,
+ )
}
}
@@ -300,8 +366,12 @@ func TestTheIssuerIsNormalisedTheSameWayTheTargetNormalisesIt(t *testing.T) {
}
if lab.Issuer != testIssuer {
- t.Fatalf("issuer = %q, want %q with the trailing slash removed, because the verifier "+
- "gateway trims it too and an `iss` that differs by one character is refused", lab.Issuer, testIssuer)
+ t.Fatalf(
+ "issuer = %q, want %q with the trailing slash removed, because the verifier "+
+ "gateway trims it too and an `iss` that differs by one character is refused",
+ lab.Issuer,
+ testIssuer,
+ )
}
}
@@ -327,8 +397,14 @@ func TestFreePortsAreFiveDistinctHighPorts(t *testing.T) {
for name, port := range chosen {
if port < portFloor || port >= portCeil {
- t.Fatalf("%s got port %d, outside the %d-%d range khaos picks from; a conventional "+
- "port is the one most likely already taken", name, port, portFloor, portCeil)
+ t.Fatalf(
+ "%s got port %d, outside the %d-%d range khaos picks from; a conventional "+
+ "port is the one most likely already taken",
+ name,
+ port,
+ portFloor,
+ portCeil,
+ )
}
if other, clash := seen[port]; clash {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go
index a05aa703..86a9282b 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go
@@ -210,6 +210,9 @@ func composePath() (string, error) {
// named volumes and reports success. khaos's own "set KHAOS_RANGE_DIR" error
// message is what teaches an operator to set that variable.
func VerifyOwned(path string) error {
+ // This read IS the ownership guard. Refusing to open an operator-supplied
+ // path here would mean khaos could never check whether it owns one.
+ //nolint:gosec // reading it is the whole point of this function
raw, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf(errUnreadable, ErrNotOurs, path, err)
@@ -217,7 +220,13 @@ func VerifyOwned(path string) error {
declared := declaredProject(raw)
if declared != ProjectName {
- return fmt.Errorf(errForeign, ErrNotOurs, path, orNone(declared), ProjectName)
+ return fmt.Errorf(
+ errForeign,
+ ErrNotOurs,
+ path,
+ orNone(declared),
+ ProjectName,
+ )
}
return nil
@@ -246,9 +255,15 @@ func orNone(declared string) string {
func FreePort() (int, error) {
for range portTries {
+ // A candidate, not a secret: the next statement actually binds it, and
+ // an unpredictable guess is no likelier to be free than any other.
+ //nolint:gosec // a bind candidate, immediately tested
port := portFloor + rand.IntN(portCeil-portFloor)
- listener, err := net.Listen("tcp", net.JoinHostPort(loopback, strconv.Itoa(port)))
+ listener, err := net.Listen(
+ "tcp",
+ net.JoinHostPort(loopback, strconv.Itoa(port)),
+ )
if err != nil {
continue
}
@@ -282,7 +297,11 @@ func (l Lab) ProxiedProtectedURL() string {
return l.ProxiedGatewayURL() + protectedPath
}
-func (l Lab) Up(ctx context.Context, out io.Writer, failMode, cacheTTL string) error {
+func (l Lab) Up(
+ ctx context.Context,
+ out io.Writer,
+ failMode, cacheTTL string,
+) error {
environ := append(os.Environ(),
EnvGatewayPort+"="+strconv.Itoa(l.Port),
EnvProxiedPort+"="+strconv.Itoa(l.ProxiedPort),
@@ -293,7 +312,15 @@ func (l Lab) Up(ctx context.Context, out io.Writer, failMode, cacheTTL string) e
EnvCacheTTL+"="+cacheTTL,
)
- if err := l.compose(ctx, out, environ, "up", "--build", "--detach", "--wait"); err != nil {
+ if err := l.compose(
+ ctx,
+ out,
+ environ,
+ "up",
+ "--build",
+ "--detach",
+ "--wait",
+ ); err != nil {
return err
}
@@ -314,10 +341,24 @@ func (l Lab) Down(ctx context.Context, out io.Writer) error {
EnvIdPPort+"="+strconv.Itoa(teardownPort),
)
- return l.compose(ctx, out, environ, "down", "--volumes", "--remove-orphans", "--rmi", "local")
+ return l.compose(
+ ctx,
+ out,
+ environ,
+ "down",
+ "--volumes",
+ "--remove-orphans",
+ "--rmi",
+ "local",
+ )
}
-func (l Lab) compose(ctx context.Context, out io.Writer, environ []string, args ...string) error {
+func (l Lab) compose(
+ ctx context.Context,
+ out io.Writer,
+ environ []string,
+ args ...string,
+) error {
// The project name is passed explicitly as well as declared in the file, so
// no edit to the file can make these commands act on another project.
full := append([]string{
@@ -328,6 +369,7 @@ func (l Lab) compose(ctx context.Context, out io.Writer, environ []string, args
var stderr bytes.Buffer
+ //nolint:gosec // khaos driving its own compose file as the operator
cmd := exec.CommandContext(ctx, dockerBinary, full...)
cmd.Dir = l.Dir
cmd.Env = environ
@@ -384,7 +426,12 @@ func (l Lab) awaitReady(ctx context.Context) error {
// IssueToken asks the range for a credential its gateway will accept, so an
// experiment against the range needs no flags at all.
func (l Lab) IssueToken(ctx context.Context) (string, error) {
- request, err := http.NewRequestWithContext(ctx, http.MethodPost, l.GatewayURL()+tokenPath, nil)
+ request, err := http.NewRequestWithContext(
+ ctx,
+ http.MethodPost,
+ l.GatewayURL()+tokenPath,
+ nil,
+ )
if err != nil {
return "", err
}
@@ -419,10 +466,23 @@ var ErrNoToken = errors.New("the range identity provider did not issue a token")
const GatewayInternalPort = 8080
type PortReader interface {
- Targets(ctx context.Context, filter dockerx.Filter) ([]dockerx.Target, error)
- PublishedPort(ctx context.Context, containerID string, internal int) (int, error)
- ContainerEnv(ctx context.Context, containerID string) (map[string]string, error)
- NetworkAddress(ctx context.Context, containerID, networkName string) (string, error)
+ Targets(
+ ctx context.Context,
+ filter dockerx.Filter,
+ ) ([]dockerx.Target, error)
+ PublishedPort(
+ ctx context.Context,
+ containerID string,
+ internal int,
+ ) (int, error)
+ ContainerEnv(
+ ctx context.Context,
+ containerID string,
+ ) (map[string]string, error)
+ NetworkAddress(
+ ctx context.Context,
+ containerID, networkName string,
+ ) (string, error)
BridgeGateway(ctx context.Context) (string, error)
}
@@ -462,7 +522,11 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {
return lab, nil
}
- if lab.ProxiedPort, err = reader.PublishedPort(ctx, proxied.ID, GatewayInternalPort); err != nil {
+ if lab.ProxiedPort, err = reader.PublishedPort(
+ ctx,
+ proxied.ID,
+ GatewayInternalPort,
+ ); err != nil {
return Lab{}, err
}
@@ -478,11 +542,19 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {
return lab, nil
}
- if lab.VerifierPort, err = reader.PublishedPort(ctx, verifierGateway.ID, GatewayInternalPort); err != nil {
+ if lab.VerifierPort, err = reader.PublishedPort(
+ ctx,
+ verifierGateway.ID,
+ GatewayInternalPort,
+ ); err != nil {
return Lab{}, err
}
- if lab.Issuer, lab.IdPPort, err = issuerOf(ctx, reader, verifierGateway.ID); err != nil {
+ if lab.Issuer, lab.IdPPort, err = issuerOf(
+ ctx,
+ reader,
+ verifierGateway.ID,
+ ); err != nil {
return Lab{}, err
}
@@ -500,7 +572,11 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {
// `host.docker.internal`, so khaos's own listener address is never the issuer
// the target expects, and minting under it would get every token refused on
// `iss` for a reason that has nothing to do with the trap under test.
-func issuerOf(ctx context.Context, reader PortReader, containerID string) (string, int, error) {
+func issuerOf(
+ ctx context.Context,
+ reader PortReader,
+ containerID string,
+) (string, int, error) {
environ, err := reader.ContainerEnv(ctx, containerID)
if err != nil {
return "", 0, err
@@ -508,17 +584,34 @@ func issuerOf(ctx context.Context, reader PortReader, containerID string) (strin
issuer := environ[EnvIssuer]
if issuer == "" {
- return "", 0, fmt.Errorf(errNoIssuer, ErrRangeIncomplete, VerifierGatewayName, EnvIssuer)
+ return "", 0, fmt.Errorf(
+ errNoIssuer,
+ ErrRangeIncomplete,
+ VerifierGatewayName,
+ EnvIssuer,
+ )
}
parsed, err := url.Parse(issuer)
if err != nil {
- return "", 0, fmt.Errorf(errBadIssuer, ErrRangeIncomplete, VerifierGatewayName, issuer, err)
+ return "", 0, fmt.Errorf(
+ errBadIssuer,
+ ErrRangeIncomplete,
+ VerifierGatewayName,
+ issuer,
+ err,
+ )
}
port, err := strconv.Atoi(parsed.Port())
if err != nil || port <= 0 {
- return "", 0, fmt.Errorf(errBadIssuer, ErrRangeIncomplete, VerifierGatewayName, issuer, err)
+ return "", 0, fmt.Errorf(
+ errBadIssuer,
+ ErrRangeIncomplete,
+ VerifierGatewayName,
+ issuer,
+ err,
+ )
}
return strings.TrimSuffix(issuer, "/"), port, nil
@@ -543,9 +636,16 @@ func (l Lab) VerifierProtectedURL() string {
// reaches a host listener there, a listener on the target network's own gateway
// is unreachable, and binding only loopback leaves the provider dead to every
// container.
-func (l Lab) IdPEndpoint(ctx context.Context, reader PortReader) (string, string, error) {
+func (l Lab) IdPEndpoint(
+ ctx context.Context,
+ reader PortReader,
+) (string, string, error) {
if l.IdPPort == 0 || l.Issuer == "" {
- return "", "", fmt.Errorf(errNoVerifierGateway, ErrRangeIncomplete, VerifierGatewayName)
+ return "", "", fmt.Errorf(
+ errNoVerifierGateway,
+ ErrRangeIncomplete,
+ VerifierGatewayName,
+ )
}
gatewayIP, err := reader.BridgeGateway(ctx)
@@ -561,7 +661,11 @@ func (l Lab) IdPEndpoint(ctx context.Context, reader PortReader) (string, string
// the only authority on where that gateway will actually look for the proxy, and
// khaos has to bind the port the target is already addressing, not the port khaos
// would have picked.
-func proxyPortOf(ctx context.Context, reader PortReader, containerID string) (int, error) {
+func proxyPortOf(
+ ctx context.Context,
+ reader PortReader,
+ containerID string,
+) (int, error) {
environ, err := reader.ContainerEnv(ctx, containerID)
if err != nil {
return 0, err
@@ -569,17 +673,34 @@ func proxyPortOf(ctx context.Context, reader PortReader, containerID string) (in
upstream := environ[EnvUpstream]
if upstream == "" {
- return 0, fmt.Errorf(errNoUpstream, ErrRangeIncomplete, ProxiedGatewayName, EnvUpstream)
+ return 0, fmt.Errorf(
+ errNoUpstream,
+ ErrRangeIncomplete,
+ ProxiedGatewayName,
+ EnvUpstream,
+ )
}
parsed, err := url.Parse(upstream)
if err != nil {
- return 0, fmt.Errorf(errBadUpstream, ErrRangeIncomplete, ProxiedGatewayName, upstream, err)
+ return 0, fmt.Errorf(
+ errBadUpstream,
+ ErrRangeIncomplete,
+ ProxiedGatewayName,
+ upstream,
+ err,
+ )
}
port, err := strconv.Atoi(parsed.Port())
if err != nil || port <= 0 {
- return 0, fmt.Errorf(errBadUpstream, ErrRangeIncomplete, ProxiedGatewayName, upstream, err)
+ return 0, fmt.Errorf(
+ errBadUpstream,
+ ErrRangeIncomplete,
+ ProxiedGatewayName,
+ upstream,
+ err,
+ )
}
return port, nil
@@ -595,7 +716,10 @@ func proxyPortOf(ctx context.Context, reader PortReader, containerID string) (in
// khaos too, so the change khaos needs to make at the authority could not be made
// at all, and the research is explicit that the revocation has to be real while
// the target cannot see it.
-func (l Lab) AuthorityURL(ctx context.Context, reader PortReader) (string, error) {
+func (l Lab) AuthorityURL(
+ ctx context.Context,
+ reader PortReader,
+) (string, error) {
targets, err := reader.Targets(ctx, dockerx.Filter{Project: ProjectName})
if err != nil {
return "", err
@@ -611,7 +735,10 @@ func (l Lab) AuthorityURL(ctx context.Context, reader PortReader) (string, error
return "", err
}
- return "http://" + net.JoinHostPort(address, strconv.Itoa(GatewayInternalPort)), nil
+ return "http://" + net.JoinHostPort(
+ address,
+ strconv.Itoa(GatewayInternalPort),
+ ), nil
}
return "", ErrNoRange
@@ -625,9 +752,16 @@ func (l Lab) AuthorityURL(ctx context.Context, reader PortReader) (string, error
// gateway is unreachable, and binding that one address leaves the proxy dead on
// loopback and dead on the host's LAN address. A wildcard bind would put a fault
// proxy for a deliberately vulnerable stack on the operator's network.
-func (l Lab) ProxyEndpoint(ctx context.Context, reader PortReader) (string, string, error) {
+func (l Lab) ProxyEndpoint(
+ ctx context.Context,
+ reader PortReader,
+) (string, string, error) {
if l.ProxyPort == 0 {
- return "", "", fmt.Errorf(errNoProxiedGateway, ErrRangeIncomplete, ProxiedGatewayName)
+ return "", "", fmt.Errorf(
+ errNoProxiedGateway,
+ ErrRangeIncomplete,
+ ProxiedGatewayName,
+ )
}
gatewayIP, err := reader.BridgeGateway(ctx)
@@ -659,6 +793,10 @@ func (l Lab) ProxyEndpoint(ctx context.Context, reader PortReader) (string, stri
return "", "", ErrNoRange
}
-var ErrRangeIncomplete = errors.New("the running range is missing the part this experiment needs")
+var ErrRangeIncomplete = errors.New(
+ "the running range is missing the part this experiment needs",
+)
-var ErrNoRange = errors.New("no running khaos range was found; start one with `khaos range up`, or point khaos at your own stack instead")
+var ErrNoRange = errors.New(
+ "no running khaos range was found; start one with `khaos range up`, or point khaos at your own stack instead",
+)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab_test.go
index baad0fe5..312b8b7c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab_test.go
@@ -34,10 +34,26 @@ func TestOnlyKhaosOwnComposeFileIsAccepted(t *testing.T) {
}{
{"khaos's own", "name: " + ProjectName + "\nservices: {}\n", true},
{"quoted name", "name: \"" + ProjectName + "\"\n", true},
- {"a comment mentioning it does not count", "# name: " + ProjectName + "\nname: someone-else\n", false},
- {"someone else's project", "name: my-production-stack\nservices: {}\n", false},
- {"no project name at all", "services:\n web:\n image: nginx\n", false},
- {"name nested under a service", "services:\n web:\n name: " + ProjectName + "\n", false},
+ {
+ "a comment mentioning it does not count",
+ "# name: " + ProjectName + "\nname: someone-else\n",
+ false,
+ },
+ {
+ "someone else's project",
+ "name: my-production-stack\nservices: {}\n",
+ false,
+ },
+ {
+ "no project name at all",
+ "services:\n web:\n image: nginx\n",
+ false,
+ },
+ {
+ "name nested under a service",
+ "services:\n web:\n name: " + ProjectName + "\n",
+ false,
+ },
}
for _, tc := range cases {
@@ -49,16 +65,24 @@ func TestOnlyKhaosOwnComposeFileIsAccepted(t *testing.T) {
}
if !tc.allowed && !errors.Is(err, ErrNotOurs) {
- t.Fatalf("got %v; pointing khaos at a compose file it does not own turns "+
- "`khaos range down` into `docker compose down --volumes` against that "+
- "project, which destroys its named volumes and reports success", err)
+ t.Fatalf(
+ "got %v; pointing khaos at a compose file it does not own turns "+
+ "`khaos range down` into `docker compose down --volumes` against that "+
+ "project, which destroys its named volumes and reports success",
+ err,
+ )
}
})
}
}
func TestAMissingComposeFileIsRefusedNotAssumed(t *testing.T) {
- if err := VerifyOwned(filepath.Join(t.TempDir(), composeFile)); !errors.Is(err, ErrNotOurs) {
+ if err := VerifyOwned(
+ filepath.Join(t.TempDir(), composeFile),
+ ); !errors.Is(
+ err,
+ ErrNotOurs,
+ ) {
t.Fatalf("got %v, want ErrNotOurs", err)
}
}
@@ -75,16 +99,22 @@ func TestFreePortIsHighAndNotConstant(t *testing.T) {
}
if port < portFloor || port >= portCeil {
- t.Fatalf("port %d is outside [%d, %d); every host port khaos binds must be a "+
- "random high one, because the conventional port is the one already taken",
- port, portFloor, portCeil)
+ t.Fatalf(
+ "port %d is outside [%d, %d); every host port khaos binds must be a "+
+ "random high one, because the conventional port is the one already taken",
+ port,
+ portFloor,
+ portCeil,
+ )
}
seen[port] = true
}
if len(seen) == 1 {
- t.Fatal("every call returned the same port, so the selection is not random")
+ t.Fatal(
+ "every call returned the same port, so the selection is not random",
+ )
}
}
@@ -97,7 +127,10 @@ type fakeReader struct {
err error
}
-func (f fakeReader) Targets(context.Context, dockerx.Filter) ([]dockerx.Target, error) {
+func (f fakeReader) Targets(
+ context.Context,
+ dockerx.Filter,
+) ([]dockerx.Target, error) {
return f.targets, f.err
}
@@ -105,11 +138,18 @@ func (f fakeReader) PublishedPort(context.Context, string, int) (int, error) {
return f.port, nil
}
-func (f fakeReader) ContainerEnv(context.Context, string) (map[string]string, error) {
+func (f fakeReader) ContainerEnv(
+ context.Context,
+ string,
+) (map[string]string, error) {
return f.environ, nil
}
-func (f fakeReader) NetworkAddress(context.Context, string, string) (string, error) {
+func (f fakeReader) NetworkAddress(
+ context.Context,
+ string,
+ string,
+) (string, error) {
return f.address, nil
}
@@ -118,7 +158,13 @@ func (f fakeReader) BridgeGateway(context.Context) (string, error) {
}
func gateway(running bool) dockerx.Target {
- return dockerx.Target{ID: "abc", Name: GatewayName, Project: ProjectName, Running: running, Inspected: true}
+ return dockerx.Target{
+ ID: "abc",
+ Name: GatewayName,
+ Project: ProjectName,
+ Running: running,
+ Inspected: true,
+ }
}
func TestDiscoverRequiresARunningGateway(t *testing.T) {
@@ -127,8 +173,16 @@ func TestDiscoverRequiresARunningGateway(t *testing.T) {
reader fakeReader
wantErr bool
}{
- {"running", fakeReader{targets: []dockerx.Target{gateway(true)}, port: 41234}, false},
- {"stopped", fakeReader{targets: []dockerx.Target{gateway(false)}, port: 41234}, true},
+ {
+ "running",
+ fakeReader{targets: []dockerx.Target{gateway(true)}, port: 41234},
+ false,
+ },
+ {
+ "stopped",
+ fakeReader{targets: []dockerx.Target{gateway(false)}, port: 41234},
+ true,
+ },
{"nothing at all", fakeReader{}, true},
{"some other container", fakeReader{targets: []dockerx.Target{
{ID: "x", Name: "unrelated", Project: ProjectName, Running: true},
@@ -141,8 +195,11 @@ func TestDiscoverRequiresARunningGateway(t *testing.T) {
if tc.wantErr {
if !errors.Is(err, ErrNoRange) {
- t.Fatalf("got %v, want ErrNoRange so the operator is told to run `khaos range up` "+
- "rather than handed a bare Docker error", err)
+ t.Fatalf(
+ "got %v, want ErrNoRange so the operator is told to run `khaos range up` "+
+ "rather than handed a bare Docker error",
+ err,
+ )
}
return
}
@@ -163,8 +220,11 @@ func TestTheGatewayURLIsLoopbackOnly(t *testing.T) {
for _, url := range []string{lab.GatewayURL(), lab.ProtectedURL()} {
if got := url[:len("http://127.0.0.1")]; got != "http://127.0.0.1" {
- t.Fatalf("%q is not loopback; the range is a deliberately vulnerable stack and must "+
- "never be reachable off the host", url)
+ t.Fatalf(
+ "%q is not loopback; the range is a deliberately vulnerable stack and must "+
+ "never be reachable off the host",
+ url,
+ )
}
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/render/render_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/render/render_test.go
index 116652f1..671635af 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/render/render_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/render/render_test.go
@@ -22,7 +22,13 @@ func TestCellIsExactlyOneWidthForEveryScript(t *testing.T) {
t.Run(name, func(t *testing.T) {
got := Width(Cell(name, column))
if got != column {
- t.Fatalf("Cell(%q, %d) occupies %d display columns, want %d", name, column, got, column)
+ t.Fatalf(
+ "Cell(%q, %d) occupies %d display columns, want %d",
+ name,
+ column,
+ got,
+ column,
+ )
}
})
}
@@ -33,11 +39,17 @@ func TestPadMeasuresDisplayWidthNotBytes(t *testing.T) {
padded := Pad(accented, column)
if got := Width(padded); got != column {
- t.Fatalf("a multi-byte name padded to %d display columns, want %d", got, column)
+ t.Fatalf(
+ "a multi-byte name padded to %d display columns, want %d",
+ got,
+ column,
+ )
}
if len(padded) == column {
- t.Fatal("padding matched the byte count, which means it is counting bytes rather than display width")
+ t.Fatal(
+ "padding matched the byte count, which means it is counting bytes rather than display width",
+ )
}
}
@@ -46,12 +58,21 @@ func TestTruncateNeverPanicsOnNarrowWidths(t *testing.T) {
got := Truncate("abcdefghij", width)
if width <= 0 {
if got != "" {
- t.Fatalf("Truncate at width %d returned %q, want empty", width, got)
+ t.Fatalf(
+ "Truncate at width %d returned %q, want empty",
+ width,
+ got,
+ )
}
continue
}
if Width(got) > width {
- t.Fatalf("Truncate(_, %d) returned %q which is %d wide", width, got, Width(got))
+ t.Fatalf(
+ "Truncate(_, %d) returned %q which is %d wide",
+ width,
+ got,
+ Width(got),
+ )
}
}
}
@@ -69,6 +90,10 @@ func TestTruncateMarksWhatItCut(t *testing.T) {
t.Fatalf("%q is wider than requested", got)
}
if len(got) < len(ellipsis) || got[len(got)-len(ellipsis):] != ellipsis {
- t.Fatalf("%q does not end in %q, so the operator cannot tell it was cut", got, ellipsis)
+ t.Fatalf(
+ "%q does not end in %q, so the operator cannot tell it was cut",
+ got,
+ ellipsis,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go
index 58804617..8e3eab5a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go
@@ -10,7 +10,12 @@ import (
)
type Resolver interface {
- Accept(ctx context.Context, name string, filter dockerx.Filter, guard dockerx.Guard) (dockerx.Target, error)
+ Accept(
+ ctx context.Context,
+ name string,
+ filter dockerx.Filter,
+ guard dockerx.Guard,
+ ) (dockerx.Target, error)
}
// Injector adapts a Session to the experiment engine, so the engine never
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go
index cbadc654..8d39c74a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go
@@ -23,7 +23,9 @@ type Reclaimed struct {
Err error
}
-var ErrOtherDaemon = errors.New("that fault belongs to a different Docker daemon")
+var ErrOtherDaemon = errors.New(
+ "that fault belongs to a different Docker daemon",
+)
const errOtherDaemon = "%w: it was applied on %s and khaos is attached to %s; point khaos at that daemon and reclaim there"
@@ -73,7 +75,10 @@ func reclaimWith(
) Sweep {
outstanding, damage := journal.Outstanding(log.Path())
- sweep := Sweep{Results: make([]Reclaimed, 0, len(outstanding)), Damage: damage}
+ sweep := Sweep{
+ Results: make([]Reclaimed, 0, len(outstanding)),
+ Damage: damage,
+ }
for i := len(outstanding) - 1; i >= 0; i-- {
record := outstanding[i]
@@ -93,8 +98,14 @@ func reclaimWith(
// An empty daemon on the record is ambiguous rather than matching. It
// predates this field or the daemon would not identify itself, and
// settling it on a guess is the same irreversible mistake.
- if mismatch := daemonMismatch(record, attachedDaemon(env)); mismatch != nil {
- sweep.Results = append(sweep.Results, Reclaimed{Record: record, Err: mismatch})
+ if mismatch := daemonMismatch(
+ record,
+ attachedDaemon(env),
+ ); mismatch != nil {
+ sweep.Results = append(
+ sweep.Results,
+ Reclaimed{Record: record, Err: mismatch},
+ )
continue
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim_test.go
index cdc5adc6..fcff8914 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim_test.go
@@ -36,7 +36,10 @@ func TestASweepWillNotSettleAFaultFromAnotherDaemon(t *testing.T) {
for _, each := range cases {
t.Run(each.name, func(t *testing.T) {
- err := daemonMismatch(journal.Record{Daemon: each.recorded, TargetID: "abc"}, each.here)
+ err := daemonMismatch(
+ journal.Record{Daemon: each.recorded, TargetID: "abc"},
+ each.here,
+ )
if (err != nil) != each.refuse {
t.Fatalf("recorded=%q here=%q refused=%v, want %v (%v)",
@@ -66,6 +69,8 @@ func TestASweepWillNotSettleAFaultFromAnotherDaemon(t *testing.T) {
// The ambiguous cases deliberately do NOT refuse, so without this the whole
// table could pass with a function that never refuses anything.
if refusals == 0 {
- t.Fatal("no case refused, so this table cannot detect a check that always allows")
+ t.Fatal(
+ "no case refused, so this table cannot detect a check that always allows",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go
index c0c02ea2..e6f91676 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go
@@ -26,9 +26,13 @@ const (
detailTakenAway = "another process reverted this fault before this run finished with it"
)
-var ErrFaultsTakenAway = errors.New("every fault this run was holding was reverted by something else, so the run no longer controls what it is measuring")
+var ErrFaultsTakenAway = errors.New(
+ "every fault this run was holding was reverted by something else, so the run no longer controls what it is measuring",
+)
-var ErrRevertFailed = errors.New("one or more faults could not be reverted; run `khaos reclaim` once the cause is fixed")
+var ErrRevertFailed = errors.New(
+ "one or more faults could not be reverted; run `khaos reclaim` once the cause is fixed",
+)
type Progress func(record journal.Record, err error)
@@ -45,11 +49,20 @@ type Session struct {
mutations []journal.Record
}
-func NewSession(env inject.Env, log *journal.Journal, ttl time.Duration) *Session {
+func NewSession(
+ env inject.Env,
+ log *journal.Journal,
+ ttl time.Duration,
+) *Session {
return newSessionWith(env, log, ttl, inject.Lookup)
}
-func newSessionWith(env inject.Env, log *journal.Journal, ttl time.Duration, lookup Registry) *Session {
+func newSessionWith(
+ env inject.Env,
+ log *journal.Journal,
+ ttl time.Duration,
+ lookup Registry,
+) *Session {
return &Session{
env: env,
log: log,
@@ -78,7 +91,11 @@ func (s *Session) Lease() *lease.Lease {
return s.lease
}
-func (s *Session) Inject(ctx context.Context, kind string, target dockerx.Target) error {
+func (s *Session) Inject(
+ ctx context.Context,
+ kind string,
+ target dockerx.Target,
+) error {
mutator, err := s.lookup(kind)
if err != nil {
return err
@@ -180,6 +197,10 @@ func (s *Session) RevertAll(ctx context.Context, progress Progress) error {
}
if firstErr != nil {
+ // ErrRevertFailed is what callers branch on, and khaos's exit policy
+ // ranks it above every other outcome. The first underlying failure is
+ // diagnostic text for the operator, not a second identity to match.
+ //nolint:errorlint // %v is deliberate
return fmt.Errorf("%w: %v", ErrRevertFailed, firstErr)
}
@@ -210,7 +231,10 @@ func (s *Session) remember(record journal.Record) {
s.mutations = append(s.mutations, record)
}
-func (s *Session) renewable(expiry time.Time, stillOutstanding map[string]bool) ([]journal.Record, int) {
+func (s *Session) renewable(
+ expiry time.Time,
+ stillOutstanding map[string]bool,
+) ([]journal.Record, int) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -252,7 +276,12 @@ func (s *Session) outstanding() []journal.Record {
return out
}
-func Revert(ctx context.Context, env inject.Env, log *journal.Journal, record journal.Record) error {
+func Revert(
+ ctx context.Context,
+ env inject.Env,
+ log *journal.Journal,
+ record journal.Record,
+) error {
return revertWith(ctx, env, log, record, inject.Lookup)
}
@@ -287,7 +316,11 @@ func revertWith(
return log.Append(record)
}
-func (s *Session) Confirm(ctx context.Context, kind string, target dockerx.Target) (string, error) {
+func (s *Session) Confirm(
+ ctx context.Context,
+ kind string,
+ target dockerx.Target,
+) (string, error) {
mutator, err := s.lookup(kind)
if err != nil {
return "", err
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session_test.go
index fa68571f..26046a3a 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session_test.go
@@ -37,14 +37,28 @@ type fake struct {
unconfirmable bool
}
-func (f *fake) Describe(inject.Env, dockerx.Target) string { return "a fake fault" }
+func (f *fake) Describe(
+ inject.Env,
+ dockerx.Target,
+) string {
+ return "a fake fault"
+}
-func (f *fake) Plan(context.Context, inject.Env, dockerx.Target) (json.RawMessage, error) {
+func (f *fake) Plan(
+ context.Context,
+ inject.Env,
+ dockerx.Target,
+) (json.RawMessage, error) {
f.planned++
return f.payload, f.planErr
}
-func (f *fake) Apply(context.Context, inject.Env, dockerx.Target, json.RawMessage) error {
+func (f *fake) Apply(
+ context.Context,
+ inject.Env,
+ dockerx.Target,
+ json.RawMessage,
+) error {
f.applied++
if f.path != "" {
f.journalAtApply, _ = journal.Outstanding(f.path)
@@ -52,7 +66,11 @@ func (f *fake) Apply(context.Context, inject.Env, dockerx.Target, json.RawMessag
return f.applyErr
}
-func (f *fake) Confirm(context.Context, inject.Env, dockerx.Target) (string, bool, error) {
+func (f *fake) Confirm(
+ context.Context,
+ inject.Env,
+ dockerx.Target,
+) (string, bool, error) {
if f.unconfirmable {
return "", false, nil
}
@@ -93,22 +111,35 @@ func target() dockerx.Target {
func TestTheJournalIsWrittenBeforeTheFaultIsApplied(t *testing.T) {
log := tempJournal(t)
- payload, err := journal.EncodePayload(map[string]string{"networks": "shop_default"})
+ payload, err := journal.EncodePayload(
+ map[string]string{"networks": "shop_default"},
+ )
if err != nil {
t.Fatalf("encode: %v", err)
}
mutator := &fake{payload: payload, path: log.Path()}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{fakeKind: mutator}))
-
- if err := session.Inject(context.Background(), fakeKind, target()); err != nil {
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{fakeKind: mutator}),
+ )
+
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err != nil {
t.Fatalf("inject: %v", err)
}
if len(mutator.journalAtApply) != 1 {
- t.Fatalf("the journal held %d outstanding records when Apply ran; it must already describe "+
- "the mutation, or a kill between the write and the apply is unrecoverable",
- len(mutator.journalAtApply))
+ t.Fatalf(
+ "the journal held %d outstanding records when Apply ran; it must already describe "+
+ "the mutation, or a kill between the write and the apply is unrecoverable",
+ len(mutator.journalAtApply),
+ )
}
if mutator.journalAtApply[0].Phase != journal.PhasePending {
@@ -118,8 +149,11 @@ func TestTheJournalIsWrittenBeforeTheFaultIsApplied(t *testing.T) {
var decoded map[string]string
if err := mutator.journalAtApply[0].DecodePayload(&decoded); err != nil {
- t.Fatalf("the pre-apply record carried no payload, so a revert from a cold start "+
- "would have nothing to restore: %v", err)
+ t.Fatalf(
+ "the pre-apply record carried no payload, so a revert from a cold start "+
+ "would have nothing to restore: %v",
+ err,
+ )
}
if decoded["networks"] != "shop_default" {
@@ -131,9 +165,18 @@ func TestPlanRunsBeforeAnythingIsJournaledOrApplied(t *testing.T) {
log := tempJournal(t)
mutator := &fake{planErr: errors.New("cannot read the target")}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{fakeKind: mutator}))
-
- if err := session.Inject(context.Background(), fakeKind, target()); err == nil {
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{fakeKind: mutator}),
+ )
+
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err == nil {
t.Fatal("a failing plan was treated as success")
}
@@ -155,9 +198,18 @@ func TestAFailedApplyStaysOutstandingAndIsReverted(t *testing.T) {
log := tempJournal(t)
mutator := &fake{applyErr: errors.New("daemon said no")}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{fakeKind: mutator}))
-
- if err := session.Inject(context.Background(), fakeKind, target()); err == nil {
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{fakeKind: mutator}),
+ )
+
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err == nil {
t.Fatal("a failing apply was treated as success")
}
@@ -166,8 +218,11 @@ func TestAFailedApplyStaysOutstandingAndIsReverted(t *testing.T) {
}
if mutator.reverted != 1 {
- t.Fatalf("a mutation whose apply failed was reverted %d times; it may have partially "+
- "landed and must always be undone", mutator.reverted)
+ t.Fatalf(
+ "a mutation whose apply failed was reverted %d times; it may have partially "+
+ "landed and must always be undone",
+ mutator.reverted,
+ )
}
}
@@ -176,10 +231,15 @@ func TestRevertAllUndoesMostRecentFirst(t *testing.T) {
first := &fake{}
second := &fake{}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{
- fakeKind: first,
- otherKind: second,
- }))
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{
+ fakeKind: first,
+ otherKind: second,
+ }),
+ )
ctx := context.Background()
if err := session.Inject(ctx, fakeKind, target()); err != nil {
@@ -207,10 +267,15 @@ func TestRevertAllContinuesPastAFailureAndReportsIt(t *testing.T) {
broken := &fake{revertRe: errors.New("stuck")}
working := &fake{}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{
- fakeKind: working,
- otherKind: broken,
- }))
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{
+ fakeKind: working,
+ otherKind: broken,
+ }),
+ )
ctx := context.Background()
_ = session.Inject(ctx, fakeKind, target())
@@ -219,11 +284,16 @@ func TestRevertAllContinuesPastAFailureAndReportsIt(t *testing.T) {
err := session.RevertAll(ctx, nil)
if !errors.Is(err, ErrRevertFailed) {
- t.Fatalf("got %v, want an error wrapping ErrRevertFailed so M10 can map it to an exit code", err)
+ t.Fatalf(
+ "got %v, want an error wrapping ErrRevertFailed so M10 can map it to an exit code",
+ err,
+ )
}
if working.reverted != 1 {
- t.Fatal("a failure on one mutation stopped the others from being reverted")
+ t.Fatal(
+ "a failure on one mutation stopped the others from being reverted",
+ )
}
}
@@ -231,7 +301,12 @@ func TestAnAlreadyRevertedMutationIsNotRevertedTwice(t *testing.T) {
log := tempJournal(t)
mutator := &fake{}
- session := newSessionWith(inject.Env{}, log, ttl, registryOf(map[string]inject.Mutator{fakeKind: mutator}))
+ session := newSessionWith(
+ inject.Env{},
+ log,
+ ttl,
+ registryOf(map[string]inject.Mutator{fakeKind: mutator}),
+ )
ctx := context.Background()
if err := session.Inject(ctx, fakeKind, target()); err != nil {
@@ -246,7 +321,10 @@ func TestAnAlreadyRevertedMutationIsNotRevertedTwice(t *testing.T) {
}
if mutator.reverted != 1 {
- t.Fatalf("reverted %d times across two RevertAll calls, want 1", mutator.reverted)
+ t.Fatalf(
+ "reverted %d times across two RevertAll calls, want 1",
+ mutator.reverted,
+ )
}
}
@@ -256,20 +334,36 @@ func TestReclaimHonoursTheLease(t *testing.T) {
registry := registryOf(map[string]inject.Mutator{fakeKind: mutator})
session := newSessionWith(inject.Env{}, log, time.Hour, registry)
- if err := session.Inject(context.Background(), fakeKind, target()); err != nil {
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err != nil {
t.Fatalf("inject: %v", err)
}
- live := reclaimWith(context.Background(), inject.Env{}, log, time.Now().UTC(), true, registry)
+ live := reclaimWith(
+ context.Background(),
+ inject.Env{},
+ log,
+ time.Now().UTC(),
+ true,
+ registry,
+ )
if len(live.Results) != 0 {
- t.Fatal("a fault with a live lease was reclaimed out from under the run holding it")
+ t.Fatal(
+ "a fault with a live lease was reclaimed out from under the run holding it",
+ )
}
expired := reclaimWith(context.Background(), inject.Env{}, log,
time.Now().UTC().Add(2*time.Hour), true, registry)
if len(expired.Results) != 1 {
- t.Fatalf("an expired lease produced %d reclaims, want 1", len(expired.Results))
+ t.Fatalf(
+ "an expired lease produced %d reclaims, want 1",
+ len(expired.Results),
+ )
}
}
@@ -279,12 +373,23 @@ func TestReclaimIsIdempotent(t *testing.T) {
registry := registryOf(map[string]inject.Mutator{fakeKind: mutator})
session := newSessionWith(inject.Env{}, log, ttl, registry)
- if err := session.Inject(context.Background(), fakeKind, target()); err != nil {
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err != nil {
t.Fatalf("inject: %v", err)
}
for i := range 3 {
- sweep := reclaimWith(context.Background(), inject.Env{}, log, time.Now().UTC(), false, registry)
+ sweep := reclaimWith(
+ context.Background(),
+ inject.Env{},
+ log,
+ time.Now().UTC(),
+ false,
+ registry,
+ )
if sweep.Failed() {
t.Fatalf("sweep %d failed", i)
}
@@ -301,18 +406,32 @@ func TestRenewDoesNotResurrectAFaultSomethingElseReverted(t *testing.T) {
registry := registryOf(map[string]inject.Mutator{fakeKind: mutator})
session := newSessionWith(inject.Env{}, log, ttl, registry)
- if err := session.Inject(context.Background(), fakeKind, target()); err != nil {
+ if err := session.Inject(
+ context.Background(),
+ fakeKind,
+ target(),
+ ); err != nil {
t.Fatalf("inject: %v", err)
}
- sweep := reclaimWith(context.Background(), inject.Env{}, log, time.Now().UTC(), false, registry)
+ sweep := reclaimWith(
+ context.Background(),
+ inject.Env{},
+ log,
+ time.Now().UTC(),
+ false,
+ registry,
+ )
if sweep.Failed() {
t.Fatal("the simulated reaper failed")
}
if err := session.Renew(); !errors.Is(err, ErrFaultsTakenAway) {
- t.Fatalf("got %v; a session whose faults were reverted elsewhere must stop renewing "+
- "and say so, not re-append applied records and make the mutation outstanding again", err)
+ t.Fatalf(
+ "got %v; a session whose faults were reverted elsewhere must stop renewing "+
+ "and say so, not re-append applied records and make the mutation outstanding again",
+ err,
+ )
}
outstanding, err := journal.Outstanding(log.Path())
@@ -321,7 +440,10 @@ func TestRenewDoesNotResurrectAFaultSomethingElseReverted(t *testing.T) {
}
if len(outstanding) != 0 {
- t.Fatalf("renewal resurrected %d reverted mutation(s)", len(outstanding))
+ t.Fatalf(
+ "renewal resurrected %d reverted mutation(s)",
+ len(outstanding),
+ )
}
}
@@ -329,7 +451,14 @@ func TestAnUnknownKindIsRefused(t *testing.T) {
log := tempJournal(t)
session := newSessionWith(inject.Env{}, log, ttl, registryOf(nil))
- if err := session.Inject(context.Background(), "nope", target()); !errors.Is(err, inject.ErrUnknownKind) {
+ if err := session.Inject(
+ context.Background(),
+ "nope",
+ target(),
+ ); !errors.Is(
+ err,
+ inject.ErrUnknownKind,
+ ) {
t.Fatalf("got %v, want ErrUnknownKind", err)
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go
index 87c351f4..46290061 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go
@@ -10,14 +10,13 @@ import (
"os"
"path/filepath"
- "github.com/reeflective/console"
- "github.com/spf13/cobra"
-
"github.com/CarterPerez-dev/khaos/internal/banner"
"github.com/CarterPerez-dev/khaos/internal/cli"
"github.com/CarterPerez-dev/khaos/internal/lock"
"github.com/CarterPerez-dev/khaos/internal/statedir"
"github.com/CarterPerez-dev/khaos/internal/version"
+ "github.com/reeflective/console"
+ "github.com/spf13/cobra"
)
const (
@@ -34,7 +33,9 @@ leaving at that moment would abandon the rollback and report success.`
exitCode = 0
)
-var ErrBusy = errors.New("a khaos run is still holding or reverting a fault; wait for it to finish, then exit again")
+var ErrBusy = errors.New(
+ "a khaos run is still holding or reverting a fault; wait for it to finish, then exit again",
+)
func Run(ctx context.Context, out io.Writer) error {
app := console.New(version.Name)
@@ -55,7 +56,7 @@ func Run(ctx context.Context, out io.Writer) error {
})
menu.AddInterrupt(io.EOF, func(*console.Console) {
- leave(out)
+ leaveOrSayWhyNot(out)
})
if path, ok := historyPath(); ok {
@@ -78,6 +79,18 @@ func newExitCmd(out io.Writer) *cobra.Command {
}
}
+// leaveOrSayWhyNot is the interrupt path's leave. An interrupt callback cannot
+// return an error, so the refusal has to be WRITTEN here or it is lost, and
+// losing it made Ctrl-D a silent no-op while a fault was still outstanding: the
+// same guard the `exit` command explains itself through, reached a second way
+// and saying nothing at all. An operator who gets no answer reasonably concludes
+// the key did not register and presses it again.
+func leaveOrSayWhyNot(out io.Writer) {
+ if err := leave(out); err != nil {
+ _, _ = io.WriteString(out, err.Error()+newline)
+ }
+}
+
func leave(out io.Writer) error {
if !idle() {
return ErrBusy
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell_test.go
new file mode 100644
index 00000000..0b30606c
--- /dev/null
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell_test.go
@@ -0,0 +1,108 @@
+// ©AngelaMos | 2026
+// shell_test.go
+
+package shell
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+
+ "github.com/CarterPerez-dev/khaos/internal/lock"
+ "github.com/CarterPerez-dev/khaos/internal/statedir"
+)
+
+// busy holds the instance lock for the duration of a test, which is what a live
+// run holds while it owns a fault. The state dir is redirected first so the
+// test cannot take the lock out from under a khaos the operator is running.
+func busy(t *testing.T) {
+ t.Helper()
+
+ t.Setenv(statedir.EnvStateDir, t.TempDir())
+
+ paths, err := statedir.Default()
+ if err != nil {
+ t.Fatalf("resolve the state dir: %v", err)
+ }
+
+ held, err := lock.Acquire(paths.Lock())
+ if err != nil {
+ t.Fatalf("hold the instance lock: %v", err)
+ }
+
+ t.Cleanup(func() { _ = held.Release() })
+}
+
+func TestIdleIsFalseWhileARunHoldsTheLock(t *testing.T) {
+ busy(t)
+
+ if idle() {
+ t.Fatal(
+ "idle() was true while the instance lock was held, so every guard " +
+ "built on it is inert and the rest of this file proves nothing",
+ )
+ }
+}
+
+// The bug this test exists for: the EOF interrupt discarded leave's error, so
+// Ctrl-D while a fault was outstanding printed NOTHING and did not exit. The
+// `exit` command explained itself through the same guard, which is what made
+// the silence a defect rather than a design.
+//
+// Only the refusal path is exercised. The accepting path ends in os.Exit, which
+// cannot be observed from inside the test binary.
+func TestInterruptSaysWhyItWillNotLeave(t *testing.T) {
+ busy(t)
+
+ var out bytes.Buffer
+
+ leaveOrSayWhyNot(&out)
+
+ said := out.String()
+
+ if said == "" {
+ t.Fatal(
+ "the interrupt path printed nothing while a fault was outstanding; " +
+ "an operator who gets no answer concludes the key did not register",
+ )
+ }
+
+ if !strings.Contains(said, ErrBusy.Error()) {
+ t.Fatalf(
+ "the interrupt path printed %q, which does not carry ErrBusy; the "+
+ "operator needs the reason, not just some output",
+ said,
+ )
+ }
+}
+
+// Both ways out have to give the same answer. The exit command and the EOF
+// interrupt share one guard, so a reader comparing them must not find two
+// different behaviours for the same outstanding fault.
+func TestExitAndInterruptRefuseAlike(t *testing.T) {
+ busy(t)
+
+ var typed bytes.Buffer
+
+ command := newExitCmd(&typed)
+ command.SetOut(&typed)
+ command.SetErr(&typed)
+
+ commandErr := command.RunE(command, nil)
+ if commandErr == nil {
+ t.Fatal("`exit` returned no error while a fault was outstanding")
+ }
+
+ var interrupted bytes.Buffer
+
+ leaveOrSayWhyNot(&interrupted)
+
+ if !strings.Contains(interrupted.String(), commandErr.Error()) {
+ t.Fatalf(
+ "`exit` refused with %q but the interrupt said %q; one guard has to "+
+ "produce one answer",
+ commandErr,
+ interrupted.String(),
+ )
+ }
+}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go
index 7f2675a8..14ef46fd 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go
@@ -20,7 +20,9 @@ const (
lockName = "khaos.lock"
)
-var ErrUnresolvable = errors.New("no state directory could be resolved: set " + EnvStateDir + " or " + EnvXDGState)
+var ErrUnresolvable = errors.New(
+ "no state directory could be resolved: set " + EnvStateDir + " or " + EnvXDGState,
+)
type Paths struct {
Root string
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir_test.go
index 971e598e..7ee540bc 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir_test.go
@@ -20,13 +20,21 @@ func TestResolvePrecedence(t *testing.T) {
EnvStateDir: "/tmp/explicit",
EnvXDGState: "/home/op/.state",
}, "/home/op", "/tmp/explicit"},
- {"xdg state home", map[string]string{EnvXDGState: "/home/op/.state"}, "/home/op", "/home/op/.state/khaos"},
+ {
+ "xdg state home",
+ map[string]string{EnvXDGState: "/home/op/.state"},
+ "/home/op",
+ "/home/op/.state/khaos",
+ },
{"home fallback", nil, "/home/op", "/home/op/.local/state/khaos"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got, err := Resolve(func(k string) string { return tc.env[k] }, tc.home)
+ got, err := Resolve(
+ func(k string) string { return tc.env[k] },
+ tc.home,
+ )
if err != nil {
t.Fatalf("resolve: %v", err)
}
@@ -38,7 +46,13 @@ func TestResolvePrecedence(t *testing.T) {
}
func TestResolveWithNothingToGoOnIsAnError(t *testing.T) {
- if _, err := Resolve(func(string) string { return "" }, ""); !errors.Is(err, ErrUnresolvable) {
+ if _, err := Resolve(
+ func(string) string { return "" },
+ "",
+ ); !errors.Is(
+ err,
+ ErrUnresolvable,
+ ) {
t.Fatalf("got %v; resolution must refuse rather than guess a path", err)
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient.go
index f43f1703..83b2d787 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient.go
@@ -13,7 +13,11 @@ import (
const newline = '\n'
func Ramp(steps int) []color.Color {
- return lipgloss.Blend1D(steps, lipgloss.Color(string(BrandDeep)), lipgloss.Color(string(BrandLight)))
+ return lipgloss.Blend1D(
+ steps,
+ lipgloss.Color(string(BrandDeep)),
+ lipgloss.Color(string(BrandLight)),
+ )
}
func Block(lines []string) string {
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient_test.go
index 38201b75..eced807e 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/gradient_test.go
@@ -22,14 +22,26 @@ func TestRampEndpointsAreExact(t *testing.T) {
t.Fatalf("Ramp(%d) returned %d colors", steps, len(ramp))
}
- wantFirstR, wantFirstG, wantFirstB := uint32(0x48), uint32(0x05), uint32(0xFF)
+ wantFirstR, wantFirstG, wantFirstB := uint32(
+ 0x48,
+ ), uint32(
+ 0x05,
+ ), uint32(
+ 0xFF,
+ )
wantLastR, wantLastG, wantLastB := uint32(0x94), uint32(0x6E), uint32(0xFF)
- if r, g, b := rgb(ramp[0]); r != wantFirstR || g != wantFirstG || b != wantFirstB {
+ if r, g, b := rgb(
+ ramp[0],
+ ); r != wantFirstR || g != wantFirstG ||
+ b != wantFirstB {
t.Fatalf("first stop = %02X%02X%02X, want %s", r, g, b, BrandDeep)
}
- if r, g, b := rgb(ramp[steps-1]); r != wantLastR || g != wantLastG || b != wantLastB {
+ if r, g, b := rgb(
+ ramp[steps-1],
+ ); r != wantLastR || g != wantLastG ||
+ b != wantLastB {
t.Fatalf("last stop = %02X%02X%02X, want %s", r, g, b, BrandLight)
}
}
@@ -41,7 +53,12 @@ func TestRampIsMonotonicTowardTheLightStop(t *testing.T) {
for i, c := range ramp {
r, _, _ := rgb(c)
if i > 0 && r < previous {
- t.Fatalf("red channel went backwards at step %d: %d after %d", i, r, previous)
+ t.Fatalf(
+ "red channel went backwards at step %d: %d after %d",
+ i,
+ r,
+ previous,
+ )
}
previous = r
}
@@ -75,6 +92,10 @@ func TestBlockEmitsOneStyleSpanPerRow(t *testing.T) {
out := Block([]string{"aaa", "bbb", "ccc"})
if got := strings.Count(out, "\x1b[38"); got != rows {
- t.Fatalf("Block emitted %d color sequences for %d rows; a vertical gradient needs exactly one per row", got, rows)
+ t.Fatalf(
+ "Block emitted %d color sequences for %d rows; a vertical gradient needs exactly one per row",
+ got,
+ rows,
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile.go
index aa69201b..3a94a8f9 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile.go
@@ -15,7 +15,11 @@ const (
envSep = "="
)
-func NewWriter(w io.Writer, environ []string, forceNoColor bool) *colorprofile.Writer {
+func NewWriter(
+ w io.Writer,
+ environ []string,
+ forceNoColor bool,
+) *colorprofile.Writer {
out := colorprofile.NewWriter(w, environ)
if forceNoColor || noColorRequested(environ) {
out.Profile = colorprofile.NoTTY
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile_test.go
index 4b4522e6..41e2ee26 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/theme/profile_test.go
@@ -30,21 +30,34 @@ func TestNoColorRequested(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := noColorRequested(tc.environ); got != tc.want {
- t.Fatalf("noColorRequested(%q) = %v, want %v", tc.environ, got, tc.want)
+ t.Fatalf(
+ "noColorRequested(%q) = %v, want %v",
+ tc.environ,
+ got,
+ tc.want,
+ )
}
})
}
}
func TestNewWriterStripsEverythingWhenNoColorRequested(t *testing.T) {
- forcing := []string{"CLICOLOR_FORCE=1", "COLORTERM=truecolor", "TERM=xterm-256color"}
+ forcing := []string{
+ "CLICOLOR_FORCE=1",
+ "COLORTERM=truecolor",
+ "TERM=xterm-256color",
+ }
cases := []struct {
name string
environ []string
force bool
}{
- {"NO_COLOR beats CLICOLOR_FORCE", append([]string{"NO_COLOR=1"}, forcing...), false},
+ {
+ "NO_COLOR beats CLICOLOR_FORCE",
+ append([]string{"NO_COLOR=1"}, forcing...),
+ false,
+ },
{"explicit force beats CLICOLOR_FORCE", forcing, true},
}
@@ -58,7 +71,11 @@ func TestNewWriterStripsEverythingWhenNoColorRequested(t *testing.T) {
}
if got := buf.String(); got != sample {
- t.Fatalf("got %q, want %q with no escape sequences at all", got, sample)
+ t.Fatalf(
+ "got %q, want %q with no escape sequences at all",
+ got,
+ sample,
+ )
}
})
}
@@ -66,13 +83,23 @@ func TestNewWriterStripsEverythingWhenNoColorRequested(t *testing.T) {
func TestNewWriterKeepsColorWhenForced(t *testing.T) {
var buf bytes.Buffer
- w := NewWriter(&buf, []string{"CLICOLOR_FORCE=1", "COLORTERM=truecolor", "TERM=xterm-256color"}, false)
+ w := NewWriter(
+ &buf,
+ []string{
+ "CLICOLOR_FORCE=1",
+ "COLORTERM=truecolor",
+ "TERM=xterm-256color",
+ },
+ false,
+ )
if _, err := io.WriteString(w, Fg(BrandDeep, sample)); err != nil {
t.Fatalf("write: %v", err)
}
if !strings.Contains(buf.String(), "\x1b[") {
- t.Fatal("no escape sequence survived, so the stripping tests above prove nothing")
+ t.Fatal(
+ "no escape sequence survived, so the stripping tests above prove nothing",
+ )
}
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/helpers_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/helpers_test.go
index 81ccc6fb..d60aafa4 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/helpers_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/helpers_test.go
@@ -18,7 +18,10 @@ import (
// it. The provider is reached over HTTP rather than in-process on purpose: the
// JWKS and introspection traps live in the HTTP handlers, so a verifier wired
// straight to the Go methods would never see them.
-func pair(t *testing.T, mode verifier.Mode) (*idp.Provider, *verifier.Verifier) {
+func pair(
+ t *testing.T,
+ mode verifier.Mode,
+) (*idp.Provider, *verifier.Verifier) {
t.Helper()
provider, err := idp.New(idp.Config{})
@@ -84,10 +87,12 @@ func serveSet(t *testing.T, set idp.JWKSet) string {
t.Fatalf("encode: %v", err)
}
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write(body)
- }))
+ server := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(body)
+ }),
+ )
t.Cleanup(server.Close)
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/matrix_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/matrix_test.go
index 46e2d075..2d2059f8 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/matrix_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/matrix_test.go
@@ -137,10 +137,13 @@ func subjects() []subject {
// service, and khaos's own experiment was hiding it by supplying the
// new-key traffic itself.
{
- trap: idp.KidRollover,
- present: func(p *idp.Provider) (string, error) { return p.HonestToken() },
- arm: func(*idp.Provider) idp.Trap { return idp.Trap{Kind: idp.KidRollover} },
- acceptedBy: []verifier.Mode{verifier.JWKSCacheForever, verifier.JWKSRefetchOnKidOnly},
+ trap: idp.KidRollover,
+ present: func(p *idp.Provider) (string, error) { return p.HonestToken() },
+ arm: func(*idp.Provider) idp.Trap { return idp.Trap{Kind: idp.KidRollover} },
+ acceptedBy: []verifier.Mode{
+ verifier.JWKSCacheForever,
+ verifier.JWKSRefetchOnKidOnly,
+ },
beforeFault: true,
},
@@ -192,10 +195,15 @@ func TestRevokedCredentialIsHonouredOnlyByAForeverCache(t *testing.T) {
credential := provider.Revocable()
if decision := v.Decide(credential); !decision.Allow {
- t.Fatalf("the provider's own active credential was refused before anything was revoked: %s", decision.Reason)
+ t.Fatalf(
+ "the provider's own active credential was refused before anything was revoked: %s",
+ decision.Reason,
+ )
}
- if err := provider.Arm(idp.Trap{Kind: idp.Revoke, Credential: credential}); err != nil {
+ if err := provider.Arm(
+ idp.Trap{Kind: idp.Revoke, Credential: credential},
+ ); err != nil {
t.Fatalf("revoke: %v", err)
}
@@ -208,8 +216,13 @@ func TestRevokedCredentialIsHonouredOnlyByAForeverCache(t *testing.T) {
wantAllow := verifier.Mode(mode) == verifier.DecisionCacheForever
if decision.Allow != wantAllow {
- t.Fatalf("mode %s allowed a revoked credential = %v, want %v (%s)",
- mode, decision.Allow, wantAllow, decision.Reason)
+ t.Fatalf(
+ "mode %s allowed a revoked credential = %v, want %v (%s)",
+ mode,
+ decision.Allow,
+ wantAllow,
+ decision.Reason,
+ )
}
})
}
@@ -233,7 +246,10 @@ func TestEveryTrapIsCaughtByCorrectAndLetThroughOnlyByItsOwnBug(t *testing.T) {
for _, kind := range idp.Kinds() {
if !covered[idp.Kind(kind)] {
- t.Errorf("trap %s has no row in the matrix, so nothing proves it is detectable", kind)
+ t.Errorf(
+ "trap %s has no row in the matrix, so nothing proves it is detectable",
+ kind,
+ )
}
}
@@ -249,8 +265,15 @@ func TestEveryTrapIsCaughtByCorrectAndLetThroughOnlyByItsOwnBug(t *testing.T) {
want := each.expects(verifier.Mode(mode))
if decision.Allow != want {
- t.Fatalf("%s under %s: allowed = %v, want %v (verifier said: %s; provider observed: %s)",
- each.trap, mode, decision.Allow, want, decision.Reason, armed)
+ t.Fatalf(
+ "%s under %s: allowed = %v, want %v (verifier said: %s; provider observed: %s)",
+ each.trap,
+ mode,
+ decision.Allow,
+ want,
+ decision.Reason,
+ armed,
+ )
}
})
}
@@ -277,7 +300,12 @@ func (s subject) expects(mode verifier.Mode) bool {
// is minted first; the caches are warmed before the fault so a verifier has
// something stale to serve; and the trap is confirmed through the provider's own
// surface so a cell that fails cannot be blamed on a fault that never landed.
-func stage(t *testing.T, provider *idp.Provider, v *verifier.Verifier, s subject) (string, string) {
+func stage(
+ t *testing.T,
+ provider *idp.Provider,
+ v *verifier.Verifier,
+ s subject,
+) (string, string) {
t.Helper()
// Warm the verifier the way khaos's baseline does, by presenting an honest
@@ -293,8 +321,10 @@ func stage(t *testing.T, provider *idp.Provider, v *verifier.Verifier, s subject
}
if decision := v.Decide(warm); !decision.Allow {
- t.Fatalf("the verifier refused an honest credential before any fault was armed (%s), so nothing it does afterwards can be attributed to the trap",
- decision.Reason)
+ t.Fatalf(
+ "the verifier refused an honest credential before any fault was armed (%s), so nothing it does afterwards can be attributed to the trap",
+ decision.Reason,
+ )
}
early := ""
@@ -314,8 +344,11 @@ func stage(t *testing.T, provider *idp.Provider, v *verifier.Verifier, s subject
observable, confirmed, err := provider.Observe(context(t), s.trap)
if err != nil || !confirmed {
- t.Fatalf("khaos could not confirm %s on its own provider (%v), so this cell would be measuring nothing",
- s.trap, orErr(err, observable))
+ t.Fatalf(
+ "khaos could not confirm %s on its own provider (%v), so this cell would be measuring nothing",
+ s.trap,
+ orErr(err, observable),
+ )
}
// Past the key cache's lifetime, so a correct verifier refetches and sees
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go
index 4e7b3115..9129439c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go
@@ -125,6 +125,11 @@ const (
// RFC 9068's media type for an OAuth 2.0 access token.
typAccessToken = "at+jwt"
+ // One refusal for all three verification paths, because a reader comparing
+ // khaos's output across modes must not have to decide whether three
+ // different wordings mean three different findings.
+ reasonBadSignature = "the signature does not verify"
+
minimumModulusBits = 1024
// DefaultNegativeTTL and DefaultForcedCooldown bound the unknown-kid refetch.
@@ -287,7 +292,9 @@ func (v *Verifier) Decide(credential string) Decision {
token, err := idp.Parse(credential)
if err != nil {
- return Decision{Reason: "the credential is shaped like a JWS and does not parse as one"}
+ return Decision{
+ Reason: "the credential is shaped like a JWS and does not parse as one",
+ }
}
return v.validate(token)
@@ -302,26 +309,39 @@ func (v *Verifier) validate(token idp.Token) Decision {
// degradation. It is an unauthenticated-request-accepted path gated on
// an outage.
if v.mode == JWKSFailOpen {
- return Decision{Allow: true, Reason: "the key set was unavailable, so the signature was not checked"}
+ return Decision{
+ Allow: true,
+ Reason: "the key set was unavailable, so the signature was not checked",
+ }
}
return Decision{Reason: errNoKeys}
}
alg, ok := v.algorithm(token.Header.Alg)
if !ok {
- return Decision{Reason: fmt.Sprintf("algorithm %q is not acceptable", token.Header.Alg)}
+ return Decision{
+ Reason: fmt.Sprintf(
+ "algorithm %q is not acceptable",
+ token.Header.Alg,
+ ),
+ }
}
// `alg: none` only ever reaches here under AlgAny, because the allowlist
// above refuses it otherwise. RFC 7515 registers it as "no digital signature
// or MAC performed", and a verifier that routes on it has agreed.
if alg == string(idp.None) {
- return v.claims(token, "the token declared no signature and it was believed")
+ return v.claims(
+ token,
+ "the token declared no signature and it was believed",
+ )
}
key, found := v.resolve(keys, token)
if !found {
- return Decision{Reason: fmt.Sprintf("no key matches kid %q", token.Header.Kid)}
+ return Decision{
+ Reason: fmt.Sprintf("no key matches kid %q", token.Header.Kid),
+ }
}
// RFC 8725 rule 2: "Each key MUST be used with exactly one algorithm, and
@@ -329,11 +349,20 @@ func (v *Verifier) validate(token idp.Token) Decision {
// single line is what kills algorithm confusion, and AlgAny is what happens
// without it.
if v.mode != AlgAny && key.Alg != "" && key.Alg != alg {
- return Decision{Reason: fmt.Sprintf("kid %q is bound to %q and the token asked for %q", key.Kid, key.Alg, alg)}
+ return Decision{
+ Reason: fmt.Sprintf(
+ "kid %q is bound to %q and the token asked for %q",
+ key.Kid,
+ key.Alg,
+ alg,
+ ),
+ }
}
if key.Use != "" && key.Use != idp.UseSignature {
- return Decision{Reason: fmt.Sprintf("kid %q is not a signing key", key.Kid)}
+ return Decision{
+ Reason: fmt.Sprintf("kid %q is not a signing key", key.Kid),
+ }
}
if reason, ok := v.signature(key, token, alg); !ok {
@@ -374,7 +403,11 @@ func (v *Verifier) resolve(keys idp.JWKSet, token idp.Token) (idp.JWK, bool) {
return key, true
}
-func (v *Verifier) signature(key idp.JWK, token idp.Token, alg string) (string, bool) {
+func (v *Verifier) signature(
+ key idp.JWK,
+ token idp.Token,
+ alg string,
+) (string, bool) {
// A signature that is absent, all zero, or shorter than THIS KEY produces is
// treated as a pass. CVE-2020-28042 is the no-minimum-length shape and
// CVE-2022-21449 is the all-zero shape; measured on go1.26.5, ecdsa.Verify
@@ -395,31 +428,7 @@ func (v *Verifier) signature(key idp.JWK, token idp.Token, alg string) (string,
switch alg {
case allowedRS:
- pub, err := key.RSAPublicKey()
- if err != nil {
- return "the key is not usable as RSA", false
- }
-
- // An explicit floor, rather than relying on crypto/rsa to have one. The
- // standard library does enforce 1024 bits, but a reference
- // implementation that depends on that is correct by luck, and the floor
- // is a GODEBUG away from being gone.
- if v.mode != AnyKeySize && pub.N.BitLen() < minimumModulusBits {
- return fmt.Sprintf("kid %q has a %d-bit modulus", key.Kid, pub.N.BitLen()), false
- }
-
- if v.mode == AnyKeySize {
- if !verifyRaw(pub, digest[:], token.Signature) {
- return "the signature does not verify", false
- }
- return "", true
- }
-
- if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], token.Signature); err != nil {
- return "the signature does not verify", false
- }
-
- return "", true
+ return v.verifyRSA(key, token, digest)
case allowedES:
pub, err := key.ECPublicKey()
@@ -431,7 +440,7 @@ func (v *Verifier) signature(key idp.JWK, token idp.Token, alg string) (string,
s := new(big.Int).SetBytes(token.Signature[p256SignatureBytes/2:])
if !ecdsa.Verify(pub, digest[:], r, s) {
- return "the signature does not verify", false
+ return reasonBadSignature, false
}
return "", true
@@ -460,6 +469,50 @@ func (v *Verifier) signature(key idp.JWK, token idp.Token, alg string) (string,
}
}
+// verifyRSA is the RS256 arm, and the only one with a function of its own
+// because it is the only one carrying a key-size policy on top of a signature
+// check: two of the broken modes act here and nowhere else.
+func (v *Verifier) verifyRSA(
+ key idp.JWK,
+ token idp.Token,
+ digest [sha256.Size]byte,
+) (string, bool) {
+ pub, err := key.RSAPublicKey()
+ if err != nil {
+ return "the key is not usable as RSA", false
+ }
+
+ // An explicit floor, rather than relying on crypto/rsa to have one. The
+ // standard library does enforce 1024 bits, but a reference implementation
+ // that depends on that is correct by luck, and the floor is a GODEBUG away
+ // from being gone.
+ if v.mode != AnyKeySize && pub.N.BitLen() < minimumModulusBits {
+ return fmt.Sprintf(
+ "kid %q has a %d-bit modulus",
+ key.Kid,
+ pub.N.BitLen(),
+ ), false
+ }
+
+ if v.mode == AnyKeySize {
+ if !verifyRaw(pub, digest[:], token.Signature) {
+ return reasonBadSignature, false
+ }
+ return "", true
+ }
+
+ if err := rsa.VerifyPKCS1v15(
+ pub,
+ crypto.SHA256,
+ digest[:],
+ token.Signature,
+ ); err != nil {
+ return reasonBadSignature, false
+ }
+
+ return "", true
+}
+
func weakSignature(key idp.JWK, signature []byte, alg string) bool {
if len(signature) == 0 || allZero(signature) {
return true
@@ -485,7 +538,10 @@ func weakSignature(key idp.JWK, signature []byte, alg string) bool {
// no revocation at all.
func (v *Verifier) claims(token idp.Token, reason string) Decision {
if v.mode == SkipClaims {
- return Decision{Allow: true, Reason: reason + ", and no claim was checked"}
+ return Decision{
+ Allow: true,
+ Reason: reason + ", and no claim was checked",
+ }
}
// RFC 8725 section 3.11, Use Explicit Typing, and RFC 9068 which requires
@@ -500,7 +556,13 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {
// described a refusal that never happened and the property it defends (every
// forged token carrying `at+jwt`) was inert against this fixture.
if token.Header.Typ != typAccessToken {
- return Decision{Reason: fmt.Sprintf("typ %q is not %q", token.Header.Typ, typAccessToken)}
+ return Decision{
+ Reason: fmt.Sprintf(
+ "typ %q is not %q",
+ token.Header.Typ,
+ typAccessToken,
+ ),
+ }
}
now := v.now()
@@ -513,12 +575,19 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {
return Decision{Reason: "the token has expired"}
}
- if token.Claims.NotBefore != nil && time.Unix(*token.Claims.NotBefore, 0).Add(-clockSkew).After(now) {
+ if token.Claims.NotBefore != nil &&
+ time.Unix(*token.Claims.NotBefore, 0).Add(-clockSkew).After(now) {
return Decision{Reason: "the token is not valid yet"}
}
if v.issuer != "" && token.Claims.Issuer != v.issuer {
- return Decision{Reason: fmt.Sprintf("issuer %q is not %q", token.Claims.Issuer, v.issuer)}
+ return Decision{
+ Reason: fmt.Sprintf(
+ "issuer %q is not %q",
+ token.Claims.Issuer,
+ v.issuer,
+ ),
+ }
}
// RFC 9700: "every resource server is obliged to verify, for every request,
@@ -528,7 +597,13 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {
// resource servers carries all of them, and RFC 9700's obligation is that
// this one "was meant to be used for that particular resource server".
if !token.Claims.Audience.Contains(v.audience) {
- return Decision{Reason: fmt.Sprintf("audience %q does not include %q", token.Claims.Audience, v.audience)}
+ return Decision{
+ Reason: fmt.Sprintf(
+ "audience %q does not include %q",
+ token.Claims.Audience,
+ v.audience,
+ ),
+ }
}
return Decision{Allow: true, Reason: reason}
@@ -675,7 +750,10 @@ func (v *Verifier) fetchKeys() (idp.JWKSet, error) {
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
- return idp.JWKSet{}, fmt.Errorf("the key set answered %d", response.StatusCode)
+ return idp.JWKSet{}, fmt.Errorf(
+ "the key set answered %d",
+ response.StatusCode,
+ )
}
body, err := io.ReadAll(response.Body)
@@ -699,7 +777,10 @@ func (v *Verifier) introspect(credential string) Decision {
if !answered {
if v.mode == IntrospectFailOpen {
- return Decision{Allow: true, Reason: "introspection did not answer usefully, so the credential was allowed"}
+ return Decision{
+ Allow: true,
+ Reason: "introspection did not answer usefully, so the credential was allowed",
+ }
}
return Decision{Reason: "introspection did not answer"}
}
@@ -719,7 +800,10 @@ func (v *Verifier) ask(credential string) (bool, bool) {
// own private convention and not the specification — so the fixture and the
// provider agreed with each other and neither would interoperate with
// anything real.
- response, err := v.client.PostForm(v.introspectURI, url.Values{paramToken: {credential}})
+ response, err := v.client.PostForm(
+ v.introspectURI,
+ url.Values{paramToken: {credential}},
+ )
if err != nil {
return false, false
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier_test.go
index ca4727db..0cff069d 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier_test.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier_test.go
@@ -23,7 +23,9 @@ import (
// It stays in the reference implementation anyway, because it is normative and
// because this is the file readers copy. This test is what stops it being a
// branch nothing runs.
-func TestKeyAlgorithmCrossCheckRefusesAHeaderThatDisagreesWithTheKey(t *testing.T) {
+func TestKeyAlgorithmCrossCheckRefusesAHeaderThatDisagreesWithTheKey(
+ t *testing.T,
+) {
provider, v := pair(t, verifier.Correct)
honest, err := provider.HonestToken()
@@ -44,7 +46,9 @@ func TestKeyAlgorithmCrossCheckRefusesAHeaderThatDisagreesWithTheKey(t *testing.
// header is the mismatch the rule forbids.
ec, ok := signingKidFor(provider, string(idp.ES256))
if !ok {
- t.Fatal("khaos's provider publishes no ES256 key, so this mismatch is not expressible")
+ t.Fatal(
+ "khaos's provider publishes no ES256 key, so this mismatch is not expressible",
+ )
}
mismatched := idp.Retarget(token, ec)
@@ -124,8 +128,11 @@ func TestAKeyNotMarkedForSigningIsRefused(t *testing.T) {
})
if decision := loose.Decide(honest); !decision.Allow {
- t.Fatalf("the same token was refused against the real key set, so the test above proves "+
- "nothing about `use`: %s", decision.Reason)
+ t.Fatalf(
+ "the same token was refused against the real key set, so the test above proves "+
+ "nothing about `use`: %s",
+ decision.Reason,
+ )
}
}
@@ -159,14 +166,19 @@ func TestTheDecisionCacheExpiresInCorrectMode(t *testing.T) {
t.Fatalf("an active credential was refused: %s", decision.Reason)
}
- if err := provider.Arm(idp.Trap{Kind: idp.Revoke, Credential: credential}); err != nil {
+ if err := provider.Arm(
+ idp.Trap{Kind: idp.Revoke, Credential: credential},
+ ); err != nil {
t.Fatalf("revoke: %v", err)
}
time.Sleep(decisionTTL * 3)
if decision := v.Decide(credential); decision.Allow {
- t.Fatalf("a revoked credential was still honoured after the cache lifetime: %s", decision.Reason)
+ t.Fatalf(
+ "a revoked credential was still honoured after the cache lifetime: %s",
+ decision.Reason,
+ )
}
}
@@ -198,11 +210,16 @@ func TestAnUnknownKidTriggersARefetch(t *testing.T) {
}
if decision := v.Decide(rotated); !decision.Allow {
- t.Fatalf("a correctly signed token under a published new key was refused: %s", decision.Reason)
+ t.Fatalf(
+ "a correctly signed token under a published new key was refused: %s",
+ decision.Reason,
+ )
}
if provider.JWKSFetches() <= before {
- t.Fatal("the verifier accepted a token under an unseen kid without refetching the key set")
+ t.Fatal(
+ "the verifier accepted a token under an unseen kid without refetching the key set",
+ )
}
}
@@ -251,7 +268,9 @@ func TestATokenWithNoExpiryIsRefused(t *testing.T) {
decision := v.Decide(stripped)
if decision.Allow {
- t.Fatal("a token carrying no `exp` was accepted, so nothing can ever revoke it")
+ t.Fatal(
+ "a token carrying no `exp` was accepted, so nothing can ever revoke it",
+ )
}
if !containsText(decision.Reason, "no `exp`") {
@@ -275,12 +294,19 @@ func TestATokenOfTheWrongTypeIsRefused(t *testing.T) {
decision := v.Decide(retyped)
if decision.Allow {
- t.Errorf("a token with typ %q was accepted where an access token belongs", typ)
+ t.Errorf(
+ "a token with typ %q was accepted where an access token belongs",
+ typ,
+ )
continue
}
if !containsText(decision.Reason, "typ") {
- t.Errorf("typ %q was refused for the wrong reason: %s", typ, decision.Reason)
+ t.Errorf(
+ "typ %q was refused for the wrong reason: %s",
+ typ,
+ decision.Reason,
+ )
}
}
@@ -292,7 +318,10 @@ func TestATokenOfTheWrongTypeIsRefused(t *testing.T) {
}
if decision := v.Decide(honest); !decision.Allow {
- t.Fatalf("the explicit-typing check refuses khaos's own correct token: %s", decision.Reason)
+ t.Fatalf(
+ "the explicit-typing check refuses khaos's own correct token: %s",
+ decision.Reason,
+ )
}
}
@@ -323,14 +352,20 @@ func TestUnknownKidsDoNotAmplifyIntoOneFetchEach(t *testing.T) {
before := provider.JWKSFetches()
for i := range attempts {
- _ = v.Decide(idp.Retarget(token, "attacker-chosen-kid-"+strconv.Itoa(i)))
+ _ = v.Decide(
+ idp.Retarget(token, "attacker-chosen-kid-"+strconv.Itoa(i)),
+ )
}
fetches := provider.JWKSFetches() - before
if fetches >= attempts {
- t.Fatalf("%d requests carrying unknown kids caused %d upstream fetches; an "+
- "attacker-controlled header field must not be a one-to-one amplifier", attempts, fetches)
+ t.Fatalf(
+ "%d requests carrying unknown kids caused %d upstream fetches; an "+
+ "attacker-controlled header field must not be a one-to-one amplifier",
+ attempts,
+ fetches,
+ )
}
// The control. Bounding the refetch must not stop a legitimate rotation being
@@ -364,9 +399,12 @@ func TestUnknownKidsDoNotAmplifyIntoOneFetchEach(t *testing.T) {
time.Sleep(10 * time.Millisecond)
}
- t.Fatalf("a correctly signed token under a newly published key was still refused after %s, "+
- "so the amplifier fix turned a routine rotation into an outage: %s",
- rotationPickupBudget, last)
+ t.Fatalf(
+ "a correctly signed token under a newly published key was still refused after %s, "+
+ "so the amplifier fix turned a routine rotation into an outage: %s",
+ rotationPickupBudget,
+ last,
+ )
}
// How long a legitimate rotation may take to be picked up after an unknown-kid
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go
index bb13c9ba..b97f069c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go
@@ -78,7 +78,13 @@ func open(ctx context.Context, exclusive bool) (*Workspace, error) {
// fault out from under it; a shared open is a read-only command and must not
// mutate anything. That is the same split `khaos reap` already uses.
if exclusive {
- work.Reconciled = run.Reclaim(ctx, work.Env(), log, time.Now().UTC(), true)
+ work.Reconciled = run.Reclaim(
+ ctx,
+ work.Env(),
+ log,
+ time.Now().UTC(),
+ true,
+ )
}
return work, nil