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 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
refactor(khaos): prune development archaeology out of every comment
CarterPerez-devdfa5f3fca52d
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.goindex c4778208..2d4fd3d0 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/gateway.go@@ -18,28 +18,14 @@ const (headerAuthorization = "Authorization"bearerPrefix = "Bearer "- // FailClosed refuses when it cannot reach the identity provider. This is- // the correct behaviour for an authentication check.- //- // FailOpen serves anyway. This is the defect khaos exists to find, and it- // is modelled on the Okta AD/LDAP delegated-authentication advisory, where- // a cached decision was consulted first and could be reached only while the- // agent was "down or cannot be reached".+ // FailClosed refuses when it cannot reach the identity provider. FailOpen+ // serves anyway, which is the defect khaos exists to find.FailClosed = "closed"FailOpen = "open"- // FailStaleRearm is the bug research 07 section 3.3 says to name, build and- // detect, because it reads as a resilience feature in review. It serves a- // cached decision when the provider is unreachable AND re-arms that cache- // entry for a full lifetime on every failed check. The lifetime therefore- // stops bounding staleness and starts bounding IDLENESS: a cached allow- // becomes permanent exactly when the authority that could revoke it is- // unreachable, for as long as traffic keeps arriving.- //- // It is one line different from a defensible design. Serving a stale allow up- // to a fixed ceiling and never re-arming is the bounded-stale pattern, which- // is a trade plenty of teams make deliberately. The difference is whether the- // error branch writes to the cache.+ // FailStaleRearm serves a cached decision when the provider is unreachable+ // AND re-arms it on every failed check, so the lifetime bounds idleness+ // rather than staleness.FailStaleRearm = "stale-rearm"introspectPath = "/introspect?token="@@ -48,9 +34,7 @@ const (defaultCacheTTL = 2 * time.SecondupstreamTimeout = 500 * time.Millisecond- // Generous on purpose. The ceiling has to be wide enough that khaos's own- // probe interval cannot fall out of it by accident, or a run measures the- // fixture's timing rather than the bug.+ // Wide enough that a probe interval cannot fall out of the window.staleCeilingFactor = 4)@@ -70,24 +54,9 @@ type cachedDecision struct {expires time.Time}-// newGateway builds the fixture. reresolve is what the DNS tier needs and is-// worth the extra parameter, because without it that whole family is inert-// against this gateway.-//-// Go's `http.Transport` keeps connections alive, so a client resolves its-// upstream's name ONCE when it opens a connection and then never again for the-// life of that connection. Measured on this fixture: 46 probes produced TWO-// queries to khaos's resolver, both at the first request. A DNS fault armed-// after that changes nothing the gateway can see, and khaos would report a clean-// survival of a fault the target never experienced.-//-// That is a true property of the fault class rather than a fixture defect — it-// is the DNS analogue of session resumption defeating a certificate probe — and-// khaos reports it as such when it measures it. But a fixture that can NEVER-// experience the fault cannot be the thing an exit gate asserts against, so this-// gateway re-resolves per request. Research 05 section 11 ranks the-// application's own connection pool as the caching layer most likely to void a-// DNS experiment, which is exactly what it did here.+// newGateway builds the fixture. reresolve disables keep-alives, because+// http.Transport resolves an upstream's name once per connection and never+// again, which hides any DNS fault armed after the first request.func newGateway(upstream, failMode string,cacheTTL time.Duration,@@ -152,8 +121,7 @@ func (g *gateway) protected(w http.ResponseWriter, r *http.Request) {return}- // The whole bug is the next three lines. A stale allow is served AND written- // back, so the next request finds it fresh and writes it back again.+ // Served AND written back, so the next request finds it fresh again.if g.failMode == FailStaleRearm {if decision, ok := g.stale(token); ok {g.remember(token, decision)@@ -165,10 +133,8 @@ func (g *gateway) protected(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusForbidden)}-// forward passes credential administration through to the identity provider so-// the range needs exactly one host port. It is deliberately unauthenticated:-// this is a loopback-only fixture whose whole purpose is to be broken, and-// khaos needs to mint itself a credential before it has one.+// forward passes credential administration to the identity provider, and is+// deliberately unauthenticated: khaos needs a credential before it has one.func (g *gateway) forward(path string) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {target := g.upstream + path@@ -205,9 +171,6 @@ func (g *gateway) introspect(token string) (bool, bool) {defer func() { _ = response.Body.Close() }()// A refusal from the identity provider is an ANSWER, not an outage.- // 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 {return false, true@@ -237,15 +200,8 @@ func (g *gateway) cached(token string) (bool, bool) {return decision.active, true}-// stale returns a decision whose lifetime has passed but which is still inside a-// bounded staleness ceiling.-//-// The ceiling is what makes this the TTL-EXTENSION bug rather than the other one.-// Without it a stale entry is servable forever, which IS a cache with no expiry,-// and khaos measures it as exactly that. With it, every failed check pushes the-// entry back inside the window, so steady traffic keeps a cached allow alive-// indefinitely and a pause longer than the window lets it lapse. One ceiling, and-// the two bugs separate.+// stale returns a lapsed decision that is still inside the ceiling, which is+// what separates TTL extension from a cache with no expiry at all.func (g *gateway) stale(token string) (bool, bool) {g.mu.Lock()defer g.mu.Unlock()@@ -262,10 +218,6 @@ func (g *gateway) stale(token string) (bool, bool) {return decision.active, true}-// staleCeiling is how far past its lifetime a decision may still be served. It is-// a multiple of the lifetime rather than a separate knob, so a range configured-// with one number behaves predictably: steady traffic at any interval shorter-// than this keeps a cached allow alive.func (g *gateway) staleCeiling() time.Duration {return g.cacheTTL * staleCeilingFactor}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/idp.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/idp.goindex e55c8a66..bae90cfb 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/idp.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/idp.go@@ -29,11 +29,8 @@ type introspection struct {Active bool `json:"active"`User string `json:"user,omitempty"`- // Asked is how many times the ROGUE provider has been introspected, and it- // is only ever set by that fixture. It is the measurement that separates a- // DNS redirect that landed from a dependency outage: a gateway that failed- // open because it could not resolve anything never asked anybody, and one- // that was redirected asked the wrong service.+ // Asked counts introspections of the ROGUE provider and is only ever set+ // by that fixture.Asked int64 `json:"asked,omitempty"`}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.goindex ac6757ea..cb38be45 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/main.go@@ -30,9 +30,7 @@ const (envListen = "KHAOS_RANGE_LISTEN"envUpstream = "KHAOS_RANGE_UPSTREAM"- // envReresolve makes this gateway resolve its dependency's name on EVERY- // request instead of once per kept-alive connection. Only the DNS gateway- // sets it; the other tiers are measured on the ordinary pooled path.+ // envReresolve resolves the dependency's name on EVERY request. DNS only.envReresolve = "KHAOS_RANGE_RERESOLVE"trueValue = "true"envFailMode = "KHAOS_RANGE_FAIL_MODE"@@ -41,21 +39,16 @@ const (defaultListen = ":8080"defaultUpstream = "http://idp:8080"- // Both deliberately unreachable. khaos's authority is not a container and- // its address is chosen per run, so a default that looked plausible would- // let the gateway start and silently measure nothing; these fail loudly- // and the baseline refuses, which voids the run instead.+ // Deliberately unreachable: a plausible default would let the gateway+ // start and measure nothing.defaultDependency = "https://host.docker.internal:0"defaultAuthorityBase = "http://host.docker.internal:0"shutdownGrace = 2 * time.Second- // Generous on purpose. At three seconds this fixture closed khaos's upstream- // before a `--delay` beyond that could be observed, so khaos's one graduated- // fault had a usable window of roughly 500ms to 3s against its own range and- // aborted above it. That ceiling belonged to the fixture, not to the fault.- // This is a deliberately-breakable test stack, not a hardened service, so the- // header timeout exists only to stop a wedged connection living forever.+ // Generous on purpose: a short header timeout closes the connection before+ // a longer injected delay can be observed, making the fixture's ceiling+ // look like the fault's.readHeaderTimeout = 120 * time.Secondusage = "usage: khaos-range <idp|gateway|verifier|tls|rogue|resolver|healthcheck>"@@ -81,9 +74,7 @@ func run() error {return selfCheck()}- // The resolver is the one role that is not an HTTP service: it binds UDP and- // TCP on 53 and its own control surface, so it never reaches the server- // below.+ // The resolver binds UDP and TCP, so it never reaches the server below.if os.Args[1] == roleResolver {return serveResolver(os.Args[2:])}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/resolver.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/resolver.goindex 691901fe..ae60548f 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/resolver.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/resolver.go@@ -34,21 +34,9 @@ var errZoneMissing = errors.New("a chaos resolver needs at least one zone entry",)-// serveResolver runs khaos's chaos resolver as a range service.-//-// It is the SAME `internal/dnsrv` package khaos runs outside the range, behind a-// different entry point, and that matters for what the range proves. If the-// range ran a separate implementation, every DNS experiment the gate asserts-// would be asserting something an operator's khaos never executes.-//-// Outside the range khaos imports its own binary as a one-layer image, because-// an operator's khaos has no source tree to build from. In here the image-// already exists, so the resolver is an ordinary compose service with the labels-// khaos matches on, and khaos finds it exactly as it finds one it started-// itself.-//-// It does not go through roleHandler, because it is the one role that is not an-// HTTP service: it binds UDP and TCP on 53 and its control surface separately.+// serveResolver runs the same internal/dnsrv package khaos runs outside the+// range, behind a different entry point. It skips roleHandler because it is the+// one role that is not an HTTP service.func serveResolver(args []string) error {flags := flag.NewFlagSet(roleResolver, flag.ContinueOnError)@@ -66,8 +54,7 @@ func serveResolver(args []string) error {return err}- // From the ENVIRONMENT, for the measured reason in resolverArgs: a command- // line is world-readable in the host's process table and this is a secret.+ // Never from the command line, which is world-readable in the process table.resolver, err := dnsrv.New(dnsrv.Config{Nonce: os.Getenv(dockerx.EnvResolverNonce),Control: *control,@@ -98,9 +85,8 @@ func serveResolver(args []string) error {return resolver.Shutdown()}-// zoneEntries collects a repeated flag. It is a flag.Value rather than a-// StringArray because this binary has no cobra, and the repetition matters: a-// resolver with one zone entry has no control name to confirm against.+// zoneEntries collects a repeated flag, as a flag.Value because this binary+// has no cobra.type zoneEntries []stringfunc (z *zoneEntries) String() string {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/rogue.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/rogue.goindex 40705483..491f6ea8 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/rogue.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/rogue.go@@ -14,23 +14,9 @@ const (rogueUser = "whoever-asked")-// rogueProvider is the service a DNS redirect fault points the target at, and-// it is what turns `dns.wrong_address` from an outage into a fail-open-// demonstration.-//-// Pointing a redirect at an unroutable address only tests what an unreachable-// dependency tests, which khaos already has three tiers for. Research 05-// section 10 names the real finding: a hostname allowlist does not merely stop-// working when the name resolves somewhere else, it ACTIVELY AUTHORISES the new-// host. To observe that, the new host has to answer, and answer wrongly.-//-// So this approves everything. Every token is active, including the invalid-// control khaos has never issued, which is exactly the shape of an attacker who-// has won a name.-//-// It is NOT a khaos injector and never will be. It is a range fixture, in the-// range image, started by the range's compose file, and it carries the consent-// label like every other target in there.+// rogueProvider is the range fixture a DNS redirect points the target at. It+// approves everything, including the invalid control, because a hostname+// allowlist actively authorises the new host rather than merely failing.type rogueProvider struct {asked atomic.Int64}@@ -51,23 +37,15 @@ func (p *rogueProvider) routes() http.Handler {return mux}-// introspect approves anything. The token is not even read: a service that has-// taken over a name it was never entitled to has no reason to check, and-// pretending otherwise would make the fixture test a different bug.+// introspect approves anything and does not even read the token.func (p *rogueProvider) introspect(w http.ResponseWriter, _ *http.Request) {p.asked.Add(1)writeJSON(w, introspection{Active: true, User: rogueUser})}-// count is how the gate proves the redirect LANDED rather than inferring it-// from the verdict.-//-// Without it a run that found a bypass is ambiguous: the gateway could have-// failed open because it could not resolve its dependency at all, which is a-// different fault's finding. A non-zero count here says the gateway resolved-// the dependency's name to this service and asked it, which is the only-// observation that distinguishes a redirect from an outage.+// count reports how often the target actually asked, which is the only thing+// that tells a landed redirect apart from a failure to resolve at all.func (p *rogueProvider) count(w http.ResponseWriter, _ *http.Request) {writeJSON(w, introspection{Active: true,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/tlsgateway.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/tlsgateway.goindex bd491967..64cd90aa 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/tlsgateway.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/tlsgateway.go@@ -30,24 +30,8 @@ const (maxRootBytes = 64 << 10)-// tlsGateway is the FOURTH gateway, and the only one whose dependency is-// reached over TLS from a certificate authority khaos controls.-//-// It composes the introspection gateway rather than reimplementing it, because-// the authorization half of this fixture is not what the `tls.` family is-// about: the certificate is. So the token decision, the cache and the fail mode-// are exactly the ones the other gateways use, and the only thing this adds is-// a PRECONDITION -- the dependency has to be usable before any authorization-// happens at all.-//-// That precondition is what makes the three outcomes distinguishable:-//-// - the certificate is accepted, the dependency is reached, authorization-// proceeds normally, and nothing looks wrong. HELD, and it means the-// gateway talked to a dependency whose identity it could not verify.-// - the certificate is refused and the gateway declines to serve. DENIED,-// which is the correct outcome for a certificate fault.-// - the certificate is refused and the gateway serves anyway. PERMITTED.+// tlsGateway reaches its dependency over TLS and composes the introspection+// gateway for the authorization half.type tlsGateway struct {auth *gateway@@ -57,10 +41,8 @@ type tlsGateway struct {certHost stringfailMode string- // One cache for the gateway's whole lifetime. Resumption is the only thing- // that makes the policy-in-peer-callback defect reachable, and a cache that- // did not outlive a request would make that mode indistinguishable from a- // correct one.+ // One cache for the whole lifetime: resumption is what makes the+ // policy-in-peer-callback path reachable at all.sessions tls.ClientSessionCache}@@ -72,13 +54,7 @@ func newTLSGateway(auth: newGateway(upstream, failMode, cacheTTL, false),mode: resolveTLSMode(tlsMode),- // Normalised to host:port, because Decide DIALS this and a URL is not- // an address. The environment carries a URL on purpose -- it is- // self-documenting and khaos parses the port out of it -- and handing- // that straight to the dialer produced- // `too many colons in address https://host.docker.internal:58520`,- // which reached the verdict as a failed handshake and voided the- // baseline of every certificate experiment.+ // The environment carries a URL, but Decide dials this.dependency: dialAddress(dependency),authorityBase: authorityBase,@@ -88,21 +64,14 @@ func newTLSGateway(}}-// identity fetches the client certificate khaos is currently issuing this-// gateway, or nil when it is issuing none.-//-// Nil is NOT a failure. khaos withholding the identity is the-// client-cert-absent fault, and a gateway that refused to connect without one-// would be making khaos's point for it: the finding is whether it connects-// anyway and whether it notices being refused.+// identity is the client certificate khaos is currently issuing. Nil is not a+// failure: a withheld identity is itself one of the faults.func (g *tlsGateway) identity(ctx context.Context) *tls.Certificate {body, ok := g.fetch(ctx, pki.RouteIdentity)if !ok {return nil}- // One PEM bundle carrying both blocks, so the same bytes are handed to- // X509KeyPair twice.pair, err := tls.X509KeyPair(body, body)if err != nil {return nil@@ -111,8 +80,7 @@ func (g *tlsGateway) identity(ctx context.Context) *tls.Certificate {return &pair}-// dialAddress reduces a dependency URL to the host:port a dialer wants, and-// passes through anything that is already an address.+// dialAddress reduces a dependency URL to host:port.func dialAddress(raw string) string {parsed, err := url.Parse(raw)if err != nil || parsed.Host == "" {@@ -122,55 +90,32 @@ func dialAddress(raw string) string {return parsed.Host}-// client is built PER REQUEST, with the trust anchor re-read each time.-//-// A pool fetched once at startup would make CASwap inexpressible: that fault-// replaces the anchor after the gateway is already running, so a gateway-// holding a root from boot would never experience it and the experiment would-// report HELD over a fault that never reached it. Re-reading models what a-// substituted trust store IS -- managed out of band, changed without the-// application being asked.-//-// The client itself is configuration and no state, so building one per request-// costs nothing worth saving.+// client is built per request, because a trust store or certificate held from+// boot could never experience a fault armed after startup.func (g *tlsGateway) client(ctx context.Context) *tlsclient.Client {return tlsclient.New(tlsclient.Config{- Mode: g.mode,- Host: g.certHost,- Roots: g.trustStore(ctx),- Timeout: dependencyTimeout,-- // Fetched per request like the trust store, because khaos can withdraw- // or expire it mid-run and a gateway holding one from boot could not- // experience either fault.+ Mode: g.mode,+ Host: g.certHost,+ Roots: g.trustStore(ctx),+ Timeout: dependencyTimeout,Identity: g.identity(ctx),-- // SHARED across requests, which is the whole precondition for the- // resumption hole: a cache built per connection resumes nothing.Sessions: g.sessions,})}-// resolveTLSMode refuses an unknown mode rather than falling back to the-// correct client. A fixture that quietly became correct would report every-// experiment as fail-closed, which is the most expensive way to be wrong.+// resolveTLSMode falls back to the client that verifies nothing, never to the+// correct one, so a misconfigured fixture fails loudly.func resolveTLSMode(name string) tlsclient.Mode {mode, err := tlsclient.ParseMode(name)if err != nil {- // The range is a fixture, so there is nobody to return an error to. It- // picks the mode that cannot silently flatter the target: a client that- // verifies nothing fails every experiment loudly rather than passing- // one quietly.return tlsclient.SkipVerify}return mode}-// routes builds its OWN mux rather than taking the auth gateway's and-// overriding a pattern. ServeMux PANICS on a duplicate registration, so-// mutating the composed gateway's routes crashed the container on startup with-// exit 2 and no useful message.+// routes builds its own mux rather than overriding a pattern on the composed+// gateway's, because net/http.ServeMux panics on a duplicate registration.func (g *tlsGateway) routes() *http.ServeMux {mux := http.NewServeMux()@@ -180,8 +125,6 @@ func (g *tlsGateway) routes() *http.ServeMux {mux.HandleFunc(routeProtected, g.protected)- // Credential administration is forwarded to the identity provider so the- // range needs exactly one host port per gateway, the same as the others.mux.HandleFunc(issuePath, g.auth.forward(issuePath))mux.HandleFunc(revokePath, g.auth.forward(revokePath))@@ -202,15 +145,10 @@ func (g *tlsGateway) protected(w http.ResponseWriter, r *http.Request) {decision := g.client(r.Context()).Decide(r.Context(), g.dependency)- // A convenience for a human reading the fixture's responses, and khaos must- // never consume it. khaos judges a target from the outside and a real target- // volunteers nothing, so an experiment that read this header would pass- // against the range and be inert against everything else.+ // For a human reading the fixture's responses; khaos must never consume it.w.Header().Set(headerTLSReason, decision.Reason)if decision.Accepted {- // The dependency is usable, so the ordinary authorization decision- // applies and the certificate fault has changed nothing.g.auth.protected(w, r)return@@ -225,14 +163,9 @@ func (g *tlsGateway) protected(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusForbidden)}-// trustStore reads the anchor khaos's authority currently publishes.-//-// An EMPTY pool on failure, never the system roots. A nil pool would fall back-// to the host's real CAs, which cannot verify anything khaos mints, so every-// experiment would report the same refusal whether or not the fault landed and-// khaos could not tell its own plumbing failure from a target behaving-// correctly. An empty pool refuses too, but it refuses the BASELINE as well,-// which makes the run void instead of quietly wrong.+// trustStore reads the anchor khaos's authority publishes, and on failure+// returns an EMPTY pool rather than nil, which would fall back to the host's+// real CAs.func (g *tlsGateway) trustStore(ctx context.Context) *x509.CertPool {pool := x509.NewCertPool()@@ -251,10 +184,6 @@ func (g *tlsGateway) trustStore(ctx context.Context) *x509.CertPool {return pool}-// fetch reads one of khaos's own endpoints. A failure is reported as false-// rather than as an error, because every caller's honest response to "khaos is-// not answering" is to proceed with nothing and let the BASELINE fail, which-// voids the run instead of making a fault's measurement quietly wrong.func (g *tlsGateway) fetch(ctx context.Context,route string,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.goindex a8ee7399..ab18a7bd 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos-range/verifier.go@@ -21,15 +21,9 @@ const (headerVerifierReason = "X-Khaos-Reason")-// verifierGateway is the third gateway the range runs, and the only one whose-// identity provider is khaos itself. The other two introspect the range's own-// provider container, which khaos cannot make lie; this one resolves keys and-// introspects against khaos's in-process provider, which khaos can arm.-//-// It serves BOTH validation strategies, chosen by the shape of the credential,-// because research 07 section 3.1 establishes that local validation and-// introspection have genuinely different outage shapes and the `identity.`-// family spans both. Real gateways dispatch the same way.+// verifierGateway is the only gateway whose identity provider is khaos itself,+// so it is the only one khaos can arm. It serves both validation strategies,+// chosen by the credential's shape, as real gateways do.type verifierGateway struct {verifier *verifier.Verifier}@@ -76,10 +70,7 @@ func (g *verifierGateway) protected(w http.ResponseWriter, r *http.Request) {decision := g.verifier.Decide(token)- // The reason is a convenience for a human reading the fixture's responses,- // and khaos must never consume it. khaos judges a target from the outside and- // a real target volunteers nothing, so an experiment that read this header- // would pass against the range and be inert against everything else.+ // For a human reading the fixture's responses; khaos must never consume it.w.Header().Set(headerVerifierReason, decision.Reason)if decision.Allow {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.goindex c13cae7c..5885b7eb 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/cmd/khaos/main.go@@ -27,10 +27,7 @@ const (exitError = 1exitDefect = 2- // Design section 8 assigns 4 to an inconclusive run. An interrupted run is a- // kind of inconclusive one, and Chaos Toolkit's lattice keeps `interrupted`- // on the same epistemic axis, so they share it until M10 builds the full- // taxonomy out. What matters here is that neither is 0.+ // An interrupted run is a kind of inconclusive one, so they share a code.exitInconclusive = 4exitInterrupted = 4@@ -87,9 +84,8 @@ func interactive(args []string, stdin, stdout *os.File) bool {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.+// fd narrows a descriptor for the syscall wrappers that want an int.+// RLIMIT_NOFILE bounds it far below MaxInt, so it cannot overflow.func fd(file *os.File) int {return int(file.Fd()) //nolint:gosec // bounded by RLIMIT_NOFILE}@@ -107,14 +103,9 @@ func noColorRequested(args []string) bool {return false}-// fail maps an error to an exit code, and the ORDER is the contract.-//-// Anything about the state khaos left the target in outranks anything about the-// verdict, and both outrank interruption. Cancellation used to be checked first,-// so an interrupted run that ALSO failed to revert its fault returned-// "interrupted" and silently dropped the rollback failure — the one outcome an-// operator must never miss, hidden by the one they already know about, because-// `errors.Join` carries both and the first branch won.+// fail maps an error to an exit code, and the ORDER is the contract: the state+// khaos left the target in outranks the verdict, and both outrank interruption.+// errors.Join carries several at once, so the first match decides.func fail(err error) int {if errors.Is(err, run.ErrRevertFailed) {fmt.Fprintf(os.Stderr, errorFormat, version.Name, err)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.goindex bde74268..e08674fc 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go@@ -69,10 +69,7 @@ enforcing in the first place.`headerExperiment = "EXPERIMENT"headerFamily = "FAMILY"headerFault = "FAULT"- // Wide enough for the longest NAME in the catalogue, because the experiment- // name is the thing an operator types. `identity.claim_foreign_issuer` was- // truncated to `identity.claim_foreign_is...` at 30, which is a listing that- // cannot be copied from.+colExperiment = 32colFamily = 12colFault = 30@@ -160,12 +157,8 @@ func newCatalogCmd() *cobra.Command {}}-// Every experiment is its own subcommand, so the flags an operator sees are-// exactly the parameters the selected experiment declares. Registering the union-// of every experiment's parameters on one `run` would show a beginner twenty-// flags that do nothing for the experiment they picked, and deciding the set-// from a positional argument is not available in the console surface at all:-// the console regenerates the command tree without being told the line.+// Every experiment is its own subcommand, so an operator sees exactly the flags+// it declares; the console regenerates the tree without being told the line.func newPlanCmd() *cobra.Command {cmd := experimentParent("plan <experiment>", planShort, planLong)@@ -187,8 +180,7 @@ func newRunCmd() *cobra.Command {}// experimentParent resolves a name and nothing else. Unknown flags are tolerated-// on purpose: without that, `khaos run typo --url x` reports the unknown FLAG,-// burying the only thing wrong with the line.+// so `khaos run typo --url x` reports the unknown experiment, not the flag.func experimentParent(use, short, long string) *cobra.Command {verb := strings.Fields(use)[0]@@ -277,9 +269,7 @@ func newRunExperimentCmd(definition experiment.Definition) *cobra.Command {func experimentFlags(cmd *cobra.Command, definition experiment.Definition) {cmd.Flags().String(flagProject, "", projectUsage)- // Every parameter registers with an empty default even when it declares one,- // because an empty value is how khaos tells "the operator did not set this"- // from "the operator set this". Defaults are applied once, by Bind.+ // Registered empty even where a default is declared: Bind applies defaults.for _, param := range definition.Params {cmd.Flags().String(param.Name, "", paramUsage(param))}@@ -315,11 +305,8 @@ func experimentInputs(return inputs{}, err}- // Changed, not a non-empty value. Sniffing for "" cannot tell an operator who- // typed `--invalid-token ""` from one who typed nothing, and those must differ:- // an empty credential means no Authorization header at all, which is the- // canonical unauthenticated negative control. Treating it as unset silently- // replaced it with the default and made that control inexpressible.+ // Changed, not a non-empty value: `--invalid-token ""` means no Authorization+ // header at all, which an operator has to be able to ask for.supplied := map[string]string{}for _, param := range definition.Params {if !cmd.Flags().Changed(param.Name) {@@ -506,13 +493,6 @@ func runExperiment(project := given.Projectguard := dockerx.Guard{Project: project, SelfID: dockerx.SelfContainerID()}- // The target is resolved and checked against every refusal predicate BEFORE- // anything is printed, exactly as plan does it. Without this, a target khaos- // would refuse by name reached the engine instead, the baseline found nothing- // serving, and the run reported `baseline-not-met` and exit 0 against a target- // 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,@@ -550,9 +530,6 @@ func runExperiment(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,@@ -604,14 +581,8 @@ func wire(}}-// 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.+// underLease keeps the lease renewed while the run holds a fault, or `khaos+// reap` reverts it mid-measurement. A lapsed lease is an epistemic failure.func underLease(ctx context.Context,engine experiment.Engine,@@ -643,9 +614,7 @@ func underLease(}// 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.+// contract: the state of the operator's system outranks the verdict about it.func exitFor(result experiment.Result, runErr error) error {if runErr != nil {return runErr@@ -655,10 +624,6 @@ func exitFor(result experiment.Result, runErr error) error {return run.ErrRevertFailed}- // A target khaos could not see come back is a target khaos may have left- // broken, and that must not exit 0. It ranks above the defect check for the- // same reason a failed rollback does: the operator's first job is the state- // of their system, not the verdict about it.if result.Verdict.Recovery == experiment.Degraded {return ErrNotRecovered}@@ -667,12 +632,6 @@ func exitFor(result experiment.Result, runErr error) error {return ErrDefectFound}- // A run that measured nothing must not exit 0. Every inconclusive epistemic- // outcome used to, so `khaos run network.dependency_partial --bytes 999999`- // against a gateway explicitly configured to fail open was a GREEN build: the- // fault was too large to confirm, the engine aborted before measuring, the- // 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,@@ -681,16 +640,10 @@ func exitFor(result experiment.Result, runErr error) error {)}- // khaos's OWN confidence field, which the exit code used to ignore entirely.- // A HELD verdict carrying `Conclusive=false` says in its own reasons that the- // sample cannot rule out a bypass, and then exited 0 anyway — the same- // dishonesty the inconclusive exit code was introduced to end, arriving one- // field over.if !result.Verdict.Conclusive {return fmt.Errorf(errInconclusive, ErrInconclusive, verdictThinEvidence)}- // Recovery that was never observed is not recovery.if result.Verdict.Recovery == experiment.Unobserved {return fmt.Errorf(errInconclusive,@@ -702,9 +655,6 @@ func exitFor(result experiment.Result, runErr error) error {return nil}-// conclusive reports whether the epistemic axis reached a belief about the target-// at all. Passed and Deviated are answers; everything else says the run could not-// produce one.func conclusive(epistemic experiment.Epistemic) bool {return epistemic == experiment.Passed || epistemic == experiment.Deviated}@@ -721,9 +671,6 @@ func reportVerdict(out io.Writer, result experiment.Result) {),))- // 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,@@ -777,10 +724,6 @@ func orDefault(value, fallback time.Duration) time.Duration {return value}-// rangeSupplies names the parameters a running range answers for itself. It is-// the key set of rangeDefaults, pinned by a test, and it has to be knowable-// without touching anything because it decides whether khaos looks for a range-// at all.func rangeSupplies() []string {return []string{experiment.ParamTarget,@@ -801,12 +744,8 @@ func rangeSupplies() []string {}}-// tier is which of the range's three gateways an experiment belongs to, and it-// is derived from the registry rather than from the experiment's name. Each-// gateway exists so one injection tier is measured on an uncontaminated path:-// pointing a Docker-native experiment at a gateway that talks through a proxy-// measures the pair, and pointing a forgery experiment at a gateway whose issuer-// khaos cannot arm measures nothing at all.+// tier is which of the range's gateways an experiment belongs to, derived from+// the injection registry. Each gateway isolates one tier's measurement path.type tier intconst (@@ -832,43 +771,20 @@ func tierOf(kind string) tier {}}-// rangeDefaults answers per EXPERIMENT, not just per range. A proxy-tier-// experiment must probe the gateway whose own upstream runs through khaos's-// proxy; pointing it at the direct gateway would arm a fault on a path that-// gateway never uses and measure a service with no causal connection to it.-//-// The credential is always issued by the direct gateway. Both gateways share one-// identity provider, so the credential is valid at either, and issuing it on the-// direct path means token issuance never depends on the proxy already being up.-// rangeAnswers is everything khaos has to go and get before it can answer for-// the range. Keeping rangeDefaults pure over this is what lets a test pin the-// VALUES rather than only the key set.type rangeAnswers struct {Token stringRevocable stringAuthority string- // Where the range's proxied gateway expects khaos's proxy, and the- // dependency behind it. Both come from the daemon rather than from what- // `range up` chose, for the reason recorded on proxyPortOf.ProxyListen stringProxyUpstream string- // Where khaos binds its certificate authority's two listeners, and the URL- // the TLS gateway reaches the revocation endpoints by.- //- // AuthorityBase is NOT derived from AuthorityListen. khaos binds the bridge- // gateway's numeric address and the container addresses- // `host.docker.internal`, so the two are different strings for the same- // endpoint and conflating them is the identity provider's most expensive- // bug.+ // AuthorityBase is NOT derived from AuthorityListen: khaos binds a numeric+ // bridge address, while the container addresses `host.docker.internal`.AuthorityListen stringAuthorityTLS stringAuthorityBase string- // CertHost is the name the TLS gateway asks for, read back from its own- // configuration for the same reason the issuer is: khaos has to mint for- // the name the target expects, character for character.CertHost string}@@ -884,37 +800,21 @@ func rangeDefaults(case tierProxy:url = lab.ProxiedProtectedURL()case tierIdP:- // The target is the VERIFIER GATEWAY, not the provider container. That is- // the one place this tier inverts the others: there the fault is applied- // to the dependency and the gateway is probed, while here the fault is- // applied to khaos's own in-process provider and the gateway is both the- // subject and the thing khaos needs consent for. Naming the provider- // container would ask consent for a container this experiment never- // touches and leave the one it does measure unchecked.+ // The target is the gateway, not the provider: the fault lands on khaos's+ // own provider, so the gateway is the only container to ask consent for.url = lab.VerifierProtectedURL()target = rangelab.VerifierGatewayNamecase tierTLS:- // The TLS gateway, for the same reason the identity tier names the- // verifier gateway: the fault is applied to khaos's own authority and- // the gateway is both the subject and the thing khaos needs consent- // for. Naming the dependency would ask consent for a container this- // experiment never touches.url = lab.TLSProtectedURL()target = rangelab.TLSGatewayNamecase tierDNS:- // The DNS gateway, and the target is the GATEWAY rather than the- // dependency for the same reason again: the fault is applied to khaos's- // resolver, and the gateway is both the subject and the container whose- // consent khaos needs. The dependency is never touched at all here --- // it stays healthy and reachable, and the target simply cannot find it.url = lab.DNSProtectedURL()target = rangelab.DNSGatewayNamedefault:- // The direct tier probes the protected URL and names the provider- // container, both of which are already set above.+ // The direct tier's URL and target are the values set above.}return map[string]string{@@ -936,26 +836,14 @@ func rangeDefaults(experiment.ParamDNSHost: rangelab.DNSDependencyName,experiment.ParamResolverNetwork: rangelab.NetworkName,- // The redirect faults point at the range's ROGUE provider rather than at- // the documentation address they default to, and that is what makes them- // findings instead of outages. The rogue approves every credential, so a- // gateway that follows the redirect without verifying who it reached- // serves the invalid control and khaos reports PERMITTED. Pointed at an- // unroutable address the same fault only reproduces what three other- // tiers already do to an unreachable dependency.+ // The redirect faults point at the range's ROGUE provider, which approves+ // every credential; an unroutable address would only be another outage.experiment.ParamDNSAddress: rangelab.RogueAddress,}}-// fillFromRange supplies everything the operator did not, from a running range.-// It is what makes the zero-flag commitment in the UX law real: khaos already-// knows the gateway's randomly chosen port and can ask it for a credential, so-// it does not make the operator repeat either one.-//-// Three states, not two, and the partition is derived from what the range can-// answer rather than from a hand-written pair of field checks. Filling part of-// an invocation fuses the operator's target with the range's URL, which pauses a-// container they named and measures a service they did not.+// fillFromRange fills every unsupplied parameter from a running range, all of+// them or none: half-filling fuses the operator's target with the range's URL.func fillFromRange(ctx context.Context,out io.Writer,@@ -985,9 +873,7 @@ func fillFromRange(return nil, err}- // Refuse BEFORE announcing anything. Without this the note printed a URL- // khaos had already resolved to port 0, immediately above the refusal saying- // the part that would have supplied the port is missing.+ // Refuse before announcing, or the note names a URL resolved to port 0.at := tierOf(definition.FaultKind)if at == tierProxy && lab.ProxiedPort == 0 {@@ -1019,14 +905,10 @@ func fillFromRange(defaults := rangeDefaults(lab, answers, at)filled := maps.Clone(supplied)- // Filled from the wider set, so a range answer beats a generic declaration- // default. See fillable.answered := fillable(definition, supplied)resolved := make([]string, 0, len(answered))- // Credentials are deliberately omitted from the note. Everything else khaos- // chose on the operator's behalf is named, because this line is the only thing- // telling them which stack they are about to break.+ // Credentials stay out of the note; everything else khaos chose is named.for _, name := range answered {if defaults[name] == "" {continue@@ -1046,8 +928,6 @@ func fillFromRange(return filled, nil}-// 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,@@ -1061,18 +941,13 @@ func partitionFillable(continue}- // Presence, not emptiness: an operator who typed `--token ""` DID supply- // it, and refusing with "you gave --target, --url but not --token"- // contradicts the line they just typed. An empty value that is not allowed- // is Bind's refusal to make, by name.+ // Presence, not emptiness: `--token ""` was supplied. Whether an empty+ // value is allowed is Bind's refusal to make.if _, present := supplied[param.Name]; present {given = append(given, param.Name)continue}- // A parameter the declaration already answers is not missing. Demanding a- // value the experiment supplies itself sends the operator looking for- // something khaos already has.if param.Default != "" {continue}@@ -1083,25 +958,8 @@ func partitionFillable(return given, missing}-// fillable is what the range should ANSWER, which is a wider set than what is-// missing, and separating the two is a correctness fix rather than tidying.-//-// `missing` drives the half-specified refusal, so a parameter the declaration-// already defaults is deliberately not in it: demanding a value khaos supplies-// itself sends the operator looking for nothing. But a default is a GENERIC-// answer, and the range knows its own topology, so where both exist the range's-// answer has to win.-//-// `--dns-address` is the first parameter where that mattered and it mattered a-// lot. Its default is a documentation address with nothing on it, which makes a-// redirect fault indistinguishable from the dependency outage three other tiers-// already test. The range answers it with its rogue provider, which approves-// every credential, and that is what turns the fault into the finding research 05-// section 10 names: a hostname allowlist does not merely stop working when the-// name moves, it authorises the new host. With the default winning, the gate's-// own assertion caught it: the report named the documentation address.-//-// Precedence is operator, then range, then declaration.+// fillable is what the range should ANSWER, a wider set than what is missing,+// because precedence is operator, then range, then declaration default.func fillable(definition experiment.Definition,supplied map[string]string,@@ -1132,31 +990,18 @@ func flagList(names []string) string {return strings.Join(out, listSep)}-// startProxy stands up khaos's in-process fault proxy where the target is already-// looking for it. The address is not khaos's choice: the proxied gateway's-// environment is fixed at container creation, so khaos binds the port that target-// is ALREADY addressing rather than one it would have picked.-//-// The listen address is the Docker bridge gateway, discovered rather than assumed.-// Measured: a container reaches a host listener there, a listener on the target-// network's own gateway is unreachable, and binding that one address leaves the-// proxy dead on loopback and dead on the host's LAN address.+// startProxy binds khaos's fault proxy where the target already looks for it:+// the gateway's environment is fixed at container creation, so khaos has no say.func startProxy(_ context.Context,out io.Writer,_ rangelab.PortReader,spec experiment.Experiment,) (*proxy.Proxy, error) {- // From the SPEC, not from a range. These are declared parameters now, so a- // fully specified invocation against somebody's own stack no longer fails- // looking for a fixture it was never going to use.listen, upstream := spec.ProxyListen, spec.ProxyUpstreamfault, err := proxy.Open(listen, upstream)if err != nil {- // A refusal to bind THERE is not a port collision, and telling the- // operator to bring the range down and up again prescribes a fix that- // cannot work. Only a genuine collision gets the collision advice.if errors.Is(err, proxy.ErrUnsafeBind) {return nil, err}@@ -1168,33 +1013,15 @@ func startProxy(return fault, nil}-// startProvider binds khaos's own identity provider where the target is already-// addressing it. The address is not khaos's choice: the verifier gateway's-// environment is fixed at container creation, so khaos binds the port that-// container will dial rather than one it would have picked.-//-// The listen address is the Docker bridge gateway, discovered rather than-// assumed, which is the same measured fact the fault proxy rests on. A wildcard-// bind would put a deliberately-wrong identity provider on the operator's-// network, which is the one thing this tier must never do.+// startProvider binds khaos's own identity provider on the Docker bridge gateway+// at the port the issuer names, never a wildcard: the target addresses the issuer+// as `host.docker.internal`, which does not resolve here.func startProvider(ctx context.Context,out io.Writer,reader rangelab.PortReader,spec experiment.Experiment,) error {- // The ISSUER already says where to bind, so this tier needs no range at all.- //- // It used to call rangelab.Discover unconditionally, which meant a fully- // specified invocation against somebody's own stack failed looking for a- // range it was never going to use — while khaos's own refusal text invited- // exactly that: "or point khaos at your own stack instead". Seventeen of the- // eighteen identity experiments were unusable outside the bundled fixture.- //- // khaos cannot BIND the issuer's host, because the target addresses it as- // `host.docker.internal` and that name does not resolve here. It binds the- // Docker bridge gateway on the issuer's PORT, which is the same address the- // container reaches and the same discovery the fault proxy already does.issuer := spec.IdP.Issuer()port, err := portOf(issuer)@@ -1218,18 +1045,9 @@ func startProvider(return nil}-// standUpTiers starts whichever of khaos's own in-process tiers this experiment-// needs, and returns a closer for all of them.-//-// Every one of them has to be answering before the BASELINE, not before the-// fault, and that is the same reason three times over: the baseline is measured-// through them, so a proxy, a provider or an authority that arrived at-// injection time would make the two phases travel different paths and the-// difference between them would be KHAOS rather than the fault.-//-// The closer is returned rather than deferred here, because deferring inside-// this function would tear the tiers down before the run that measures through-// them has started.+// standUpTiers starts whichever in-process tiers this experiment needs. Every+// one must answer before the BASELINE is measured through it, or the difference+// between the phases is khaos rather than the fault.func standUpTiers(ctx context.Context,out io.Writer,@@ -1259,9 +1077,6 @@ func standUpTiers(env.ProxyFault = *spec.ProxyFault}- // The experiment already BUILT the provider, because its probes mint out of- // it and minting needs no listener. All that is left is to bind it where the- // target is already looking.if spec.IdPTrap != nil {if err := startProvider(ctx, out, work.Docker, *spec); err != nil {return env, closeAll, err@@ -1273,8 +1088,6 @@ func standUpTiers(env.IdPTrap = *spec.IdPTrap}- // The authority plays the dependency the target dials, so without it the- // baseline measures a dependency that is simply absent.if spec.PKITrap != nil {if err := startAuthority(out, *spec); err != nil {return env, closeAll, err@@ -1286,30 +1099,14 @@ func standUpTiers(env.PKITrap = *spec.PKITrap}- // The resolver is ATTACHED, not started, and that is the one structural- // difference between this tier and the other three in-process ones.- //- // khaos cannot stand a resolver up at run time and have the target use it:- // `--dns` is fixed at container creation and Docker offers no API to change- // it on a running container, measured, so a resolver created now would be- // one nothing is pointed at. The resolver has to pre-exist the target, and- // khaos finds the one already serving the target's network.+ // ATTACHED, not started: `--dns` is fixed at container creation, so a+ // resolver started now would be one nothing is pointed at.if spec.DNSTrap != nil {client, err := attachResolver(ctx, out, work.Docker, *spec)if err != nil {return env, closeAll, err}- // The liveness guard is wired HERE and not by the builder, and the- // reason is structural: it needs the resolver client, which does not- // exist until the run finds one, and the target's container address,- // which needs the daemon. The identity tier can set its own counter at- // build time because it BUILDS its provider; this tier attaches to one.- //- // The address is what makes the count a proof of arrival rather than a- // number that is always non-zero. khaos's own confirmation queries come- // from the host; the target's are forwarded by its embedded resolver out- // of its own network namespace, so counting by source separates them.if err := wireArrivalGuard(ctx,work.Docker,@@ -1320,10 +1117,7 @@ func standUpTiers(return env, closeAll, err}- // Disarmed on the way out, so the recovery window is measured through a- // WORKING resolver. Unlike the in-process tiers this authority outlives- // the khaos process, so leaving it armed would leave the target unable- // to resolve its dependency after khaos exited.+ // This resolver outlives the khaos process; armed, it would stay armed.closers = append(closers, func() {_, _ = client.Disarm(context.WithoutCancel(ctx))})@@ -1336,25 +1130,8 @@ func standUpTiers(return env, closeAll, nil}-// attachResolver finds the chaos resolver serving the target's network and-// returns a client for it, with the fault disarmed and the confirmation-// control read back out of the resolver itself.-//-// Everything here is read back rather than remembered, which is the discipline-// the identity provider's most expensive bug established. The address comes-// from the daemon, because Docker refuses a static one on a network whose-// subnet it chose. The nonce comes off the container's label. And the control-// name comes from the resolver's own health endpoint, because the resolver is-// the only authority on which name it will refuse to fault.-// wireArrivalGuard installs the count of the TARGET's own queries for the name-// under fault, which is the proof-of-arrival control research 05 section 12-// makes mandatory.-//-// Without it khaos cannot distinguish "the control failed closed" from "the-// fault never reached the target", and the second is the likely one: `--dns` is-// fixed at container creation and Docker offers no way to change it afterwards,-// so a target that was not CREATED pointing at khaos's resolver never sends it a-// single query and every verdict about it would be about nothing.+// wireArrivalGuard counts the TARGET's own queries for the name under fault,+// which separates a control that failed closed from a fault that never arrived.func wireArrivalGuard(ctx context.Context,docker *dockerx.Client,@@ -1381,11 +1158,6 @@ func wireArrivalGuard(return nil}-// requireDNSTier refuses a DNS experiment against a range with no DNS gateway,-// BY NAME, before anything is probed.-//-// A missing gateway otherwise surfaces as a published port of zero, so the run-// blames the target for not enforcing when khaos was pointing at nowhere.func requireDNSTier(lab rangelab.Lab, want func(string) bool) error {if !want(experiment.ParamDNSHost) &&!want(experiment.ParamResolverNetwork) {@@ -1417,8 +1189,6 @@ func attachResolver(client.ControlName = health.Control- // The zone is read back too, so a redirect's observable can name the honest- // address the fault replaced rather than restating the one it served.state, err := client.State(ctx)if err != nil {return nil, fmt.Errorf(errResolverSilent, resolver.Name, control, err)@@ -1426,9 +1196,6 @@ func attachResolver(client.Zone = state.Zone- // Disarmed before the baseline, because the baseline is measured through- // this resolver and one still carrying a previous run's fault would make the- // two phases see different topologies.if _, err := client.Disarm(ctx); err != nil {return nil, err}@@ -1444,19 +1211,8 @@ func attachResolver(return client, nil}-// startAuthority stands khaos's certificate authority up on BOTH of its-// listeners, before the baseline.-//-// Before the baseline and not before the fault, for the same reason the proxy-// and the provider are: the baseline is measured through this authority, so one-// that arrived at injection time would make the two phases see different-// topologies and the difference between them would be khaos rather than the-// fault.-//-// Both addresses come from the experiment's parameters, which the range answers-// and an operator can override. Nothing here is discovered, because the TLS-// gateway is already dialling a specific address and khaos does not get to pick-// a different one.+// startAuthority binds BOTH of the certificate authority's listeners. Neither+// address is discovered; the TLS gateway is already dialling specific ones.func startAuthority(out io.Writer,spec experiment.Experiment,@@ -1469,10 +1225,8 @@ func startAuthority(return fmt.Errorf(errAuthorityBind, spec.AuthorityTLS, err)}- // An HONEST chain, minted before anything is probed. Without it the- // authority has nothing armed, the baseline handshake falls back to a chain- // built per connection, and the leaf's serial changes under the target- // while khaos is trying to revoke it.+ // An HONEST chain up front, or the baseline builds one per connection and the+ // leaf's serial changes under the target while khaos is revoking it.if err := spec.Authority.Disarm(); err != nil {return err}@@ -1487,9 +1241,6 @@ func startAuthority(return nil}-// portOf reads the port an issuer names. It is the one thing khaos needs from-// the issuer beyond minting under it, and a missing or unusable port is a-// refusal by name rather than a bind to something arbitrary.func portOf(issuer string) (int, error) {parsed, err := url.Parse(issuer)if err != nil {@@ -1508,10 +1259,6 @@ func credentialParam(name string) bool {return name == experiment.ParamToken || name == experiment.ParamRevocable}-// askTheRange goes and gets only what this invocation is actually missing. A-// second credential costs a round trip and the authority's address costs a-// container inspection, and an experiment that needs neither should pay for-// neither.func askTheRange(ctx context.Context,reader rangelab.PortReader,@@ -1529,10 +1276,8 @@ func askTheRange(answers.Token = token}- // A SECOND credential, issued separately. The one khaos revokes has to be- // distinct from the one it keeps presenting as valid, or revoking it would- // take away the stream that proves the target is still serving at all and- // every verdict would read as a crash.+ // A SECOND credential: revoking the one khaos keeps presenting as valid would+ // also take away the stream proving the target is serving at all.if want(experiment.ParamRevocable) {revocable, err := lab.IssueToken(ctx)if err != nil {@@ -1563,9 +1308,6 @@ func askTheRange(answers.Authority = authority}- // All four together, because a certificate experiment needs every one of- // them and asking for them separately would let a run start with khaos- // bound where the gateway is not looking.if want(experiment.ParamAuthorityListen) ||want(experiment.ParamAuthorityTLS) ||want(experiment.ParamAuthorityBase) ||diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.goindex a3227c99..a271a2e1 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/inject.go@@ -116,9 +116,8 @@ func onlyKnownKind(_ *cobra.Command, args []string) error {return err}- // A registered kind that `inject` cannot apply alone has to be refused by- // name rather than attempted. It would otherwise fail deep inside the- // mutation with a message about a proxy the operator never asked for.+ // Refused by name, because attempting it fails deep inside the mutation+ // with a message about a proxy the operator never asked for.if !inject.IsDirect(args[0]) {return fmt.Errorf(errNotDirect,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.goindex c53c2203..37aaf611 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/rangecmd.go@@ -179,16 +179,8 @@ func newRangeStatusCmd() *cobra.Command {}}-// knownFailModes is every value the range answers to, across both kinds of-// gateway. The introspecting gateways understand three and khaos's verifier-// gateway understands ten, and an unrecognised value leaves EVERY gateway-// behaving correctly.-//-// That makes a typo the worst possible outcome: the range comes up, nothing is-// broken, and all eighteen identity experiments report a clean survival against-// a stack that was supposed to be carrying the bug. Refusing by name is the only-// safe behaviour, and the refusal lists what is available because nobody is-// going to remember ten mode names.+// knownFailModes is every value the range answers to. An unrecognised one+// would leave EVERY gateway behaving correctly, so a typo is refused by name.func knownFailModes() []string {modes := []string{rangelab.FailModeShut,@@ -217,10 +209,7 @@ func runRangeUp(strings.Join(knownFailModes(), listSep))}- // Refused here rather than inside the container, because a gateway handed- // an unrecognised mode has nobody to return an error to and a fixture that- // silently became correct would report every certificate experiment as- // fail-closed. The run would be green and the finding would be gone.+ // Refused here because the container has nobody to return an error to.if _, err := tlsclient.ParseMode(tlsMode); err != nil {return err}@@ -243,10 +232,7 @@ func runRangeUp(var lab rangelab.Labfor attempt := range portAttempts {- // Only the direct gateway's port is pinnable. The other two are khaos's- // own plumbing: the second gateway's published port and the port that- // gateway expects khaos's fault proxy on. Letting an operator pin those- // would be a footgun with no use case.+ // Only the direct gateway's port is pinnable; the others are plumbing.ports, err := rangelab.FreePorts()if err != nil {return err@@ -262,10 +248,8 @@ func runRangeUp(return err}- // A fresh nonce per `range up`, for the same reason khaos mints a fresh- // key set per run: a nonce that outlived the range would let anything- // that had seen a previous one arm the resolver, and the resolver shares- // a network with every target in there.+ // A fresh nonce per `range up`: one that outlived the range would let+ // anything that had seen it arm the resolver.nonce, err := newNonce()if err != nil {return err@@ -290,11 +274,8 @@ func runRangeUp(note(out, msgTokenHint)fmt.Fprintln(out)- // Printed from the containers rather than from what khaos just chose, which- // is the same discipline the proxy port is read back under: the container is- // the only authority on where it will actually dial and what issuer it will- // actually trust. Printing khaos's intent instead would hide exactly the- // mismatch this is most useful for.+ // Read back from the containers, which are the only authority on where+ // they will actually dial and which issuer they will trust.describeEntryPoints(ctx, out, work.Docker)return nil@@ -338,12 +319,7 @@ func runRangeStatus(ctx context.Context, out io.Writer) error {fmt.Fprintln(out)- // The entry points, which the container listing cannot give. It shows three- // gateways with truncated names and says nothing about which one is reached- // how, so an operator could not find the second or third tier from khaos's- // own output at all. Each tier is probed at a different URL and the whole- // point of running the same experiment against two of them is being able to- // address both.+ // The container listing says nothing about which tier is reached how.describeEntryPoints(ctx, out, work.Docker)return nildiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/resolvercmd.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/resolvercmd.goindex 2683c8a0..ff055957 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/resolvercmd.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/resolvercmd.go@@ -48,9 +48,7 @@ container's own address.`resolverNamePrefix = "khaos-resolver-"nonceBytes = dnsrv.NonceBytes- // readyTimeout and readyInterval are how long khaos waits for the resolver's- // health endpoint. A container starting from a one-file image has nothing to- // initialise, so this only ever covers scheduling.+ // A one-file image has nothing to initialise, so this covers scheduling.readyTimeout = 15 * time.SecondreadyInterval = 100 * time.Millisecond@@ -92,9 +90,8 @@ var ErrNoZone = errors.New("a chaos resolver needs at least one zone entry")var ErrNoNetwork = errors.New("a chaos resolver needs a network to serve")-// newServeResolverCmd is hidden because it is khaos's own plumbing: it runs-// inside the container khaos builds from its own binary, and an operator running-// it on the host would be told it cannot bind port 53.+// newServeResolverCmd is hidden because it runs inside the container khaos+// builds from its own binary, and on the host it could not bind port 53.func newServeResolverCmd() *cobra.Command {cmd := &cobra.Command{Use: dockerx.ResolverCommand,@@ -122,9 +119,8 @@ func runServeResolver(cmd *cobra.Command, _ []string) error {return err}- // From the ENVIRONMENT, not a flag. A command line is world-readable in- // `/proc/<pid>/cmdline` (mode 444, measured) and the nonce is the only- // authorisation for arming and disarming khaos's DNS faults.+ // Not a flag: /proc/<pid>/cmdline is world-readable, and this nonce is the+ // only authorisation for arming and disarming a DNS fault.nonce := os.Getenv(dockerx.EnvResolverNonce)control, err := cmd.Flags().GetString(FlagControl)@@ -150,10 +146,8 @@ func runServeResolver(cmd *cobra.Command, _ []string) error {return err}- // The container is the fault's lifetime, so the signal handler exists to- // make `docker stop` a clean shutdown rather than a kill. There is nothing- // to roll back here: the fault is the armed state, and it dies with the- // process that holds it.+ // The container is the fault's lifetime, so there is nothing to roll back;+ // this only makes `docker stop` a clean shutdown rather than a kill.stop := make(chan os.Signal, 1)signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)<-stop@@ -283,9 +277,6 @@ func runResolverUp(cmd *cobra.Command, _ []string) error {return err}-// waitReady blocks until the resolver answers its own health endpoint, so-// `resolver up` never prints an address that is not yet listening and an-// operator never recreates a target against a resolver that failed to start.func waitReady(ctx context.Context, resolver dockerx.Resolver) error {client := dnsrv.NewClient(resolver.Address,@@ -416,9 +407,7 @@ func newNonce() (string, error) {return hex.EncodeToString(buffer), nil}-// anyZoneAddress gives the generated control name the same address as a real-// zone entry, so the control resolves to something that exists. It is only ever-// used for the name khaos generates when the operator did not name one.+// anyZoneAddress points a generated control name at a real zone's address.func anyZoneAddress(zone map[string]string) string {for _, address := range zone {return addressdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.goindex 20708e71..627acdd7 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/targets.go@@ -130,8 +130,7 @@ func runTargets(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.+// printNoTargets is its own answer because an empty table carries no fix.func printNoTargets(out io.Writer) {fmt.Fprintf(out,@@ -148,9 +147,7 @@ func printNoTargets(out io.Writer) {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.+// printTargetTable returns how many targets were REFUSED.func printTargetTable(out io.Writer,targets []dockerx.Target,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/client.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/client.goindex cfe1f588..ab6147dc 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/client.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/client.go@@ -18,10 +18,8 @@ import ()const (- // probeTimeout has to clear the largest delay khaos can arm plus the time a- // client spends noticing a truncated answer and re-asking over TCP. At the- // MaxDelay ceiling of 3.999s a tighter budget would time out on khaos's own- // confirmation and report the resolver as dead.+ // probeTimeout must clear the largest delay khaos can arm plus a client's+ // re-ask over TCP, or confirmation times out and reports the resolver dead.probeTimeout = 10 * time.SecondcontrolTimeout = 5 * time.Second@@ -36,30 +34,22 @@ var ErrControlRefused = errors.New("the resolver's control surface refused this request",)-// Client is how khaos, on the host, talks to a resolver running in a container.-// Both addresses are the CONTAINER's own, reached directly: the host routes to-// container addresses on a bridge network, so neither the DNS port nor the-// control port is ever published, which is what keeps the whole tier at zero-// host ports.+// Client talks to a resolver running in a container. Both addresses are the+// CONTAINER's own, reached directly over the bridge network, so neither the DNS+// port nor the control port is ever published to the host.type Client struct {- // DNS is the resolver's address:port, used for arming confirmation by- // MEASURING what it serves.DNS string- // Control is the base URL of the resolver's control surface.Control string- // Nonce authorises every control call. Without it the target, which shares- // the network, could arm or disarm khaos's own fault.+ // Nonce authorises every control call. The target shares the network, so+ // without it the target could arm or disarm khaos's own fault.Nonce string- // ControlName is the zone name no fault touches, used as the confirmation- // oracle's positive control.ControlName string- // Zone is the honest answer the resolver serves for each name it owns, read- // back from it rather than remembered. A redirect's observable needs it to- // name the address the fault replaced.+ // Zone is read back from the resolver rather than remembered, so a+ // redirect's observable can name the address the fault replaced.Zone map[string]stringhttp *http.Client@@ -92,8 +82,8 @@ func (c *Client) State(ctx context.Context) (Stats, error) {return c.call(ctx, http.MethodGet, PathState, nil)}-// Healthy reports whether the resolver is up, without the nonce, so khaos can-// wait for a container to come up before it has read the nonce back out of it.+// Healthy reports whether the resolver is up without sending the nonce, so+// khaos can wait on a container before it has read the nonce back out of it.func (c *Client) Healthy(ctx context.Context) bool {request, err := http.NewRequestWithContext(ctx,@@ -174,8 +164,6 @@ func (c *Client) client() *http.Client {return c.http}-// answer is one measured DNS exchange. Everything the confirmation oracle-// decides on is in here, and all of it came off the wire.type answer struct {rcode inttruncated bool@@ -183,9 +171,8 @@ type answer struct {elapsed time.Durationerr error- // authoritative is the AA bit, and it is what separates the armed fault- // from khaos's own failure paths. Five paths in serveFault answer SERVFAIL,- // so the rcode alone could not tell the armed arm from the default.+ // authoritative is the AA bit. Several paths in serveFault answer SERVFAIL,+ // so the rcode alone cannot tell an armed fault from khaos's own failure.authoritative bool}@@ -212,8 +199,6 @@ func (a answer) cnames() []string {return out}-// ttls returns every TTL in the answer section, so a confirmation can require-// the armed value rather than merely the presence of a record.func (a answer) ttls() []uint32 {out := make([]uint32, 0, len(a.records))for _, rr := range a.records {@@ -232,8 +217,8 @@ func (a answer) resolved() bool {}// ask performs one exchange and records what came back, including the failure.-// A timeout is data here rather than an error to propagate: TruncationNoTCP's-// whole observable is that neither transport ever completes.+// A timeout is data rather than an error to propagate, because+// TruncationNoTCP's whole observable is that neither transport ever completes.func (c *Client) ask(name, proto string) answer {client := &dns.Client{Net: proto, Timeout: probeTimeout}@@ -280,12 +265,9 @@ func firstLine(payload []byte, fallback string) string {return text}-// Queries reads how many times one source asked khaos's resolver about one name-// it is authoritative for.-//-// A count of zero is the sentinel every guard downstream branches on, so a-// failed read must not become one: it would make khaos report the TARGET as-// never having asked when khaos simply could not count.+// Queries reads how many times one source asked about one name the resolver is+// authoritative for. A read failure returns an error rather than zero, because+// zero is the sentinel meaning the target never asked.func (c *Client) Queries(ctx context.Context,source, zoneName string,@@ -299,13 +281,8 @@ func (c *Client) Queries(}// Health reads the resolver's liveness endpoint, which also reports the control-// name no fault touches.-//-// khaos reads that name back out of the resolver rather than remembering what-// it passed, for the reason the identity provider's most expensive bug-// established: the resolver is the only authority on which name it will refuse-// to fault, and a confirmation built on khaos's own idea of it would refute-// every fault the moment the two disagreed.+// name no fault touches. That name is read back rather than remembered, since+// the resolver is the only authority on which name it will refuse to fault.func (c *Client) Health(ctx context.Context) (Health, error) {request, err := http.NewRequestWithContext(ctx,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/control.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/control.goindex d3268a6d..af79114a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/control.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/control.go@@ -13,23 +13,15 @@ import ()const (- // ControlPort is where the resolver's control surface listens INSIDE its- // container. Nothing is published to the host, and khaos reaches it on the- // container's own address the same way it reaches the resolver's DNS port,- // so this never collides with anything on the operator's machine and never- // needs remapping.+ // ControlPort listens INSIDE the resolver's container and is never+ // published, so it cannot collide with anything on the operator's machine.ControlPort = 9053// NonceHeader authorises a control request. The resolver shares a network- // with the target, so the target can reach this surface; the nonce is what- // stops it arming or disarming khaos's own fault. khaos generates it,- // passes it at container creation, and reads it back out of the container- // rather than remembering what it chose.+ // with the target, so the nonce is what stops the target arming or+ // disarming khaos's own fault.NonceHeader = "X-Khaos-Nonce"- // NonceBytes is 16, so a target cannot find the nonce by trying. Every- // refused attempt is counted and reported in Stats, which turns guessing- // into evidence rather than noise.NonceBytes = 16PathArm = "/arm"@@ -53,13 +45,9 @@ var ErrControlServing = errors.New("that resolver's control surface is already serving",)-// Health is what /healthz answers. It is a liveness signal and deliberately NOT-// nonce-protected, because khaos has to be able to wait for the container to-// come up before it has read the nonce back out of it, and because a readiness-// probe that needs a secret is one khaos cannot use from a `range status`.-//-// It reports nothing about the armed fault. A target that reads it learns only-// that a resolver exists, which it already knows from its own resolv.conf.+// Health is what /healthz answers. It is deliberately NOT nonce-protected,+// because khaos has to wait for the container to come up before it has read+// the nonce out of it. It reports nothing about the armed fault.type Health struct {OK bool `json:"ok"`Upstream string `json:"upstream"`@@ -100,9 +88,8 @@ func (r *Resolver) ServeControl(listen string) error {r.controlAddr = listener.Addr().String()r.mu.Unlock()- // The goroutine serves the LOCALS it was handed. Reading them back off the- // struct is the exact shape that gave `internal/pki` three data races, and- // the plain test suite was green for both of its new packages.+ // The goroutine serves the LOCALS it was handed; reading them back off the+ // struct would race a concurrent shutdown.go func() {_ = server.Serve(listener)}()@@ -110,8 +97,8 @@ func (r *Resolver) ServeControl(listen string) error {return nil}-// ControlAddr reports where the control surface bound, which a test needs when-// it asked for port 0.+// ControlAddr reports the address the control surface actually bound, which+// matters when port 0 was requested.func (r *Resolver) ControlAddr() string {r.mu.Lock()defer r.mu.Unlock()@@ -132,9 +119,8 @@ func (r *Resolver) shutdownControl() error {return server.Close()}-// guard refuses a request carrying the wrong nonce and COUNTS it. A refusal-// that is merely returned tells khaos nothing; a refusal that is counted is-// evidence khaos can read in the run record.+// guard refuses a request carrying the wrong nonce and counts the refusal, so+// a target probing the surface shows up in the run record.func (r *Resolver) guard(next func(http.ResponseWriter, *http.Request),) func(http.ResponseWriter, *http.Request) {@@ -166,14 +152,9 @@ func (r *Resolver) handleState(w http.ResponseWriter, _ *http.Request) {r.writeJSON(w, r.Stats())}-// handleArm installs a fault and answers with the resolver's resulting state,-// so the caller gets a synchronous acknowledgement of what is now armed.-//-// The acknowledgement is deliberately NOT what khaos confirms the fault by. A-// state echo says which branch was chosen, not what a target would receive, and-// the PKI tier's inert-authority control caught fifteen traps confirming-// themselves off exactly that kind of read-back. Confirmation measures the-// SERVED answer.+// handleArm installs a fault and echoes the resulting state. The echo says+// which branch was chosen, not what a target would receive, so it is never+// what a fault is confirmed by.func (r *Resolver) handleArm(w http.ResponseWriter, req *http.Request) {var trap Trapdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/observe.goindex 541e733c..7bfb475f 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/observe.go@@ -12,21 +12,15 @@ import ()const (- // slowMargin is how much slower the faulted name has to be than the control- // before khaos will call a delay confirmed. It is a differential rather than- // an absolute threshold, which is the proxy tier's most expensive lesson- // restated: an absolute threshold confirms `hang` or `latency` for free- // against any dependency that is simply slow.+ // slowMargin is a differential against the control rather than an absolute+ // threshold, which would confirm a delay for free against any dependency+ // that is merely slow.slowMargin = 500 * time.Millisecond- // chainMinimum is how many CNAME hops have to be present before a chain is- // a chain. One CNAME is an ordinary alias and every second zone has them;- // the fault is the indirection, so two is the floor.+ // chainMinimum is two because one CNAME is an ordinary alias; the fault is+ // the indirection.chainMinimum = 2- // unknownHonest stands in when khaos has not read the resolver's zone back.- // It is named rather than blank so a reader can tell a missing read-back from- // an address that happens to be empty.unknownHonest = "the address it really has")@@ -62,21 +56,10 @@ const (refuteMasked = "%s is a fault khaos refuses to deliver, so there is nothing to confirm")-// Observe measures what the resolver actually SERVES and reports the observable-// alongside the verdict. It never reads the armed state back.-//-// That distinction is the whole design of this function. A state echo from-// /arm says which branch was chosen, not what a target would receive, and the-// PKI tier's inert-authority control caught fifteen traps confirming themselves-// off exactly that kind of read-back. Here the resolver is asked the same-// question the target asks, over the same transports, and the answer is the-// evidence.-//-// Every observation is TWO-SIDED. The faulted name has to show the fault AND-// the control name has to keep resolving, because those two failures look-// identical from one query: a resolver that has crashed answers nothing for-// both, and calling that a confirmed NXDOMAIN fault would be a finding-// manufactured out of khaos's own breakage.+// Observe measures what the resolver actually SERVES, never the armed state.+// Every observation is TWO-SIDED: the faulted name must show the fault AND the+// control must keep resolving, because a crashed resolver answers nothing for+// either and that would read as a confirmed fault.func (c *Client) Observe(trap Trap) (string, bool, error) {if !Deliverable(trap.Kind) {return "", false, fmt.Errorf(@@ -138,15 +121,8 @@ func (c *Client) Observe(trap Trap) (string, bool, error) {}}-// rcodeObservation requires the rcode AND the authoritative bit.-//-// AA is what separates the armed fault from khaos's own breakage. Five paths in-// serveFault answer SERVFAIL — the armed arm, the unreachable-kind arm, the-// default, a record-building failure and a forwarding failure — so deleting-// `case ServFail:` fell through to `default`, served the same rcode, and left-// every test and the whole gate green. khaos IS authoritative for a name in its-// own zone, so the fault sets AA and the failure paths do not, which makes the-// two distinguishable from the outside by exactly the thing that differs.+// rcodeObservation requires the rcode AND the authoritative bit: several paths+// in serveFault answer SERVFAIL, and only the armed fault sets AA.func rcodeObservation(trap Trap,faulted answer,@@ -174,15 +150,9 @@ func rcodeObservation(return fmt.Sprintf(observed, trap.Host, controlName), true, nil}-// wrongObservation requires the wrong address to be answered DIRECTLY, with no-// CNAME in the reply, and the isolation control is what forced that too.-//-// Once the chain fault was made to end at the same address — which it has to, or-// the indirection goes nowhere and there is nothing for a control to have failed-// to notice — its final A record satisfied this observable and the two faults-// alibi each other again. The claims really are different: this one is "the name-// resolves somewhere else", and the chain's is "the name resolves somewhere else-// THROUGH indirection that defeats matching on the name you asked for".+// wrongObservation requires the wrong address DIRECTLY, with no CNAME in the+// reply. The chain fault ends at the same address, so without the hop check+// either fault would satisfy both observables.func wrongObservation(trap Trap,faulted answer,@@ -199,9 +169,8 @@ func wrongObservation(return refutation(refuteWrongIndirect, trap.Host, hops)}- // The HONEST address, not the one khaos was told to serve. Naming the served- // address on both sides of "instead of" states the same thing twice and- // tells a reader nothing about what was replaced.+ // The HONEST address, since naming the served address on both sides of+ // "instead of" states the same thing twice.if honest == "" {honest = unknownHonest}@@ -209,8 +178,6 @@ func wrongObservation(return fmt.Sprintf(observeWrong, trap.Host, addresses, honest), true, nil}-// honest reports the address this resolver really serves for a name, read back-// from the resolver rather than assumed.func (c *Client) honest(host string) string {if c.Zone == nil {return ""@@ -219,14 +186,8 @@ func (c *Client) honest(host string) string {return c.Zone[dns.CanonicalName(host)]}-// chainObservation requires hops that do NOT cycle, and the isolation control-// is what forced that.-//-// A loop also has three CNAME hops, so a hop count alone confirmed CNAMELoop's-// answer as a chain. Two observables that accept the same reply alibi each-// other: gut whichever one builds the records and the other's control stays-// green. The chain's claim is indirection ENDING somewhere, so it has to reject-// indirection that goes nowhere.+// chainObservation requires hops that do NOT cycle. A loop answers the same+// number of hops, and the chain's claim is indirection that ENDS somewhere.func chainObservation(trap Trap, faulted answer) (string, bool, error) {hops := faulted.cnames()if len(hops) < chainMinimum {@@ -246,9 +207,7 @@ func chainObservation(trap Trap, faulted answer) (string, bool, error) {}// loopObservation requires an actual cycle rather than merely several hops,-// because a chain also has several hops and the two faults would then alibi-// each other: gut whichever one produces the records and the other's control-// still passes.+// which a chain has too.func loopObservation(trap Trap, faulted answer) (string, bool, error) {hops := faulted.cnames()@@ -270,27 +229,9 @@ func hasCycle(hops []string) bool {return false}-// slowObservation requires the slow answer to be an ANSWER, and the first-// version did not.-//-// It was the only observable in this file that never looked at `faulted.err` or-// `faulted.resolved()`. `ask` records a failure as `answer{elapsed, err}` and-// `probeTimeout` is 10s, and `miekg/dns` Client.Exchange is one dial, one write,-// one read with no retry — so a single dropped UDP datagram on khaos's own-// confirmation query produced `elapsed ≈ 10s` with a non-nil error and this-// returned CONFIRMED, wording it as "answering <name> after 10s". khaos had-// received nothing. It then measured a full fault window and attributed what it-// saw to a delay it could not prove was served.-//-// Every sibling already failed safe on exactly this — both truncation arms-// refute an unreachable TCP path BY NAME. The lesson was written in this file-// and not applied to the UDP case.-//-// The honest-address check is the second half. The kind promises an answer that-// is "correct but late", so a slow NXDOMAIN or a slow redirect satisfied the old-// predicate and the report said it answered correctly. The ordered cross-product-// cannot catch that, because it only ever confronts this fault with faults that-// are FAST.+// slowObservation requires the slow answer to be an ANSWER, and the honest one.+// `miekg/dns` does not retry, so one dropped datagram elapses the full+// probeTimeout and would read as a served delay.func slowObservation(trap Trap,faulted answer,@@ -337,14 +278,9 @@ func slowObservation(), true, nil}-// truncObservation needs BOTH halves. A truncated UDP answer alone does not-// distinguish this fault from TruncationNoTCP, and the difference between them-// is the entire point: one tests whether the client makes the RFC 5966 retry,-// the other tests whether the retry is permitted to leave the network.-//-// The decision is split from the measuring so each arm has a control. Every arm-// below was reachable only through a live resolver before, and the gutting pass-// showed what that costs: deleting one left the whole suite green.+// truncObservation needs BOTH halves: a truncated UDP answer alone does not+// distinguish this fault from TruncationNoTCP, which asks whether the retry is+// allowed to leave the network rather than whether the client makes it.func truncObservation(trap Trap,overUDP answer,@@ -378,8 +314,7 @@ func truncObservation(}// truncNoTCPObservation requires the truncation bit ON TCP, not merely a TCP-// path that produced no answer. "The resolver truncates on both transports" and-// "TCP is unreachable" are different findings and only the first is this fault.+// path that produced no answer: an unreachable TCP path is a different finding.func truncNoTCPObservation(trap Trap,overUDP answer,@@ -405,12 +340,8 @@ func truncNoTCPObservation(}// ttlObservation requires the armed TTL on the faulted name AND a different one-// on the control.-//-// The control half is load-bearing rather than decorative. A zone that happens-// to serve a zero TTL would confirm TTLZero against a resolver with nothing-// armed, so the fault has to be a DIFFERENCE from what the same resolver serves-// for a name it is not faulting.+// on the control, since a zone that happens to serve a zero TTL would otherwise+// confirm TTLZero against a resolver with nothing armed.func ttlObservation(trap Trap,faulted answer,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/records.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/records.goindex 34d925bf..691eb29b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/records.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/records.go@@ -12,35 +12,25 @@ import ()const (- // chainLabel and loopLabel prefix the hops khaos synthesizes. They are- // deliberately readable rather than random, because the whole point of the- // CNAME faults is that an operator reading the target's logs can see the- // name it actually connected to was not the name it asked for.chainLabel = "hop"loopLabel = "cycle"// chainExit is the zone the chain ends OUTSIDE. `.invalid` is reserved by- // RFC 2606 and can never resolve publicly, so a target that follows the- // chain and connects anyway is observably following it rather than quietly- // reaching a real service.+ // RFC 2606 and can never resolve publicly.chainExit = "khaos-elsewhere.invalid."errRecord = "build a %s record for %s: %w")-// ErrNoRecord is returned when a question asks for a type khaos's synthesizing-// faults do not produce. It is not a failure: a target asking for SRV while-// khaos is faulting an address record should be forwarded, not answered with-// something invented.+// ErrNoRecord means the question asked for a type these faults do not+// synthesize, so it should be forwarded rather than answered with an invention.var ErrNoRecord = errors.New("this fault does not synthesize an answer for that query type",)-// addressAnswer is WrongAddress: the name resolves, to somewhere nobody-// approved. It answers A for an IPv4 address and AAAA for an IPv6 one, and it-// answers the question that was ASKED rather than both, because a target that-// asked only for A and received a AAAA has been sent something it never-// requested and the fault would be about khaos rather than about the address.+// addressAnswer is WrongAddress. It answers the question that was ASKED rather+// than both families, since a target handed a AAAA it never requested would+// make the fault about khaos instead of about the address.func addressAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {address := trap.address()@@ -57,21 +47,15 @@ func addressAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {case question.Qtype == dns.TypeAAAA && !isV4:return newRR(dns.TypeAAAA, question.Name, trap.ttl(), address)default:- // The family the target asked for is not the family of the address khaos- // was given, so there is no honest record to make. An empty NOERROR is- // the right answer: the name exists and has no record of that type,- // which is exactly true.+ // The family asked for is not the family of the address khaos was+ // given, so an empty NOERROR is the only honest answer.return nil, nil}}// chainAnswer is CNAMEChain: a multi-hop CNAME whose last hop lands in a-// different zone from the one the target asked about.-//-// It is built as a `file`-zone-shaped full chain rather than a single CNAME,-// because research 05 section 8.2 measured that a resolver answering one CNAME-// at a time is a different thing to test than one answering the whole chain, and-// the whole chain is what a real authoritative server returns.+// different zone from the one the target asked about. The whole chain is+// returned at once, which is what a real authoritative server does.func chainAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {if question.Qtype != dns.TypeA && question.Qtype != dns.TypeAAAA {return nil, nil@@ -104,10 +88,9 @@ func chainAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {return append(records, final...), nil}-// loopAnswer is CNAMELoop: two CNAMEs pointing at each other, plus the entry-// hop. The server answering it does not hang, which the research measured; what-// is under test is the CLIENT's loop handling, and a client with none spins or-// exhausts its own retry budget.+// loopAnswer is CNAMELoop: two CNAMEs pointing at each other plus the entry+// hop. Serving it does not hang the server; the client's loop handling is what+// is under test.func loopAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {if question.Qtype != dns.TypeA && question.Qtype != dns.TypeAAAA {return nil, nil@@ -136,13 +119,9 @@ func loopAnswer(question dns.Question, trap Trap) ([]dns.RR, error) {return records, nil}-// rettl rewrites every TTL in an answer, which is how the two TTL faults corrupt-// exactly one property of a real answer rather than inventing one.-//-// It rewrites the authority and additional sections too. A caching resolver-// keyed off an SOA's TTL in the authority section would otherwise honour a-// lifetime khaos did not set, and the fault would be partially applied with-// nothing saying so.+// rettl rewrites every TTL in an answer, including the authority and additional+// sections: a resolver keyed off an SOA's TTL there would otherwise honour a+// lifetime khaos did not set, leaving the fault partially applied.func rettl(msg *dns.Msg, ttl uint32) *dns.Msg {if msg == nil {return nil@@ -160,10 +139,9 @@ func rettl(msg *dns.Msg, ttl uint32) *dns.Msg {return msg}-// validAddress refuses a WrongAddress magnitude that is not an address, before-// the trap reaches the journal. The fault's whole observable is the address the-// target connected to, so a malformed one would arm, answer an empty NOERROR-// and be reported as a target that resolved nothing.+// validAddress refuses a malformed WrongAddress magnitude before the trap arms,+// where it would answer an empty NOERROR and read as a target that resolved+// nothing.func validAddress(address string) error {if net.ParseIP(address) == nil {return fmt.Errorf(errBadAddress, ErrBadAddress, address)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/resolver.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/resolver.goindex ba54f56e..324ba438 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/resolver.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/resolver.go@@ -17,39 +17,23 @@ import ()const (- // DefaultPort is the port the resolver listens on INSIDE its container. It- // is 53 and it has to be, because `--dns` carries an address and no port:- // the CLI calls a port malformed and the daemon rejects it at container- // start with `ParseAddr(...): unexpected character`, after create has- // already succeeded. resolv.conf has no port field either.- //- // This is also why the resolver is a container and not a goroutine in khaos.- // An unprivileged process gets `bind: permission denied` on port 53 at every- // address, loopback included, while high ports on the same addresses bind- // fine. Inside a container the process is root in its own namespace and- // NET_BIND_SERVICE is in Docker's default set, so no host port is published- // and khaos still holds no capability.+ // Has to be 53, because `--dns` carries an address and no port. It is also+ // why the resolver is a container: an unprivileged process cannot bind 53.DefaultPort = 53- // DefaultUpstream is the resolver container's OWN embedded resolver.- //- // Forwarding there rather than to a public address is what keeps khaos- // keyless and offline-capable: the resolver inherits exactly the resolution- // the host has, with no configuration and no third party. There is no loop,- // because khaos's resolver container is never created with `--dns` pointing- // at itself, and khaos refuses to start one that is.+ // The resolver container's OWN embedded resolver, so it inherits exactly+ // the resolution the host has with no configuration and no third party.DefaultUpstream = "127.0.0.11:53"- // forwardTimeout is under the embedded resolver's own 4s `extIOTimeout`, so- // a slow upstream surfaces here as a forward error khaos can read rather- // than as the target's query dying one layer up where nothing records it.+ // Under the embedded resolver's own 4s ceiling, so a slow upstream surfaces+ // here rather than dying a layer up where nothing records it.forwardTimeout = 3 * time.SecondudpNet = "udp"tcpNet = "tcp"- // bindAttempts only ever matters for an ephemeral port: the kernel can hand- // out a UDP port that something else already holds in the TCP space.+ // Only matters for an ephemeral port: the kernel can hand out a UDP port+ // something else already holds in the TCP space.bindAttempts = 8)@@ -90,54 +74,28 @@ var ErrOutsideZone = errors.New("this resolver is not authoritative for that name",)-// Config is everything the resolver needs to exist. It is deliberately small:-// the FAULT is not here, because a resolver is armed in band after it is-// running, for a reason that is measured rather than stylistic. Docker refuses-// `--ip` on a network whose subnet it chose, so khaos cannot pin the resolver's-// address, so re-creating the container to arm it would move the address the-// target was created to dial and the target would be talking to nothing.+// Config is everything the resolver needs to exist. The FAULT is not here+// because Docker refuses `--ip` on a network whose subnet it chose, so+// recreating the container to arm it would move the address the target dials.type Config struct {- // Listen is the address:port to bind. Empty binds every address on- // DefaultPort, which is correct inside a container and is why khaos never- // binds a wildcard on the host.Listen string- // Upstream answers everything OUTSIDE the zone. A resolver that NXDOMAINed- // unrelated names would break the target for reasons the experiment never- // claimed, and the measured property that makes this safe is that the- // target's own embedded resolver answers container names locally and never- // forwards them here at all.+ // Answers everything OUTSIDE the zone, so unrelated names keep working.Upstream string- // Nonce authorises the control surface. khaos generates it, passes it at- // container creation, and reads it back out of the container rather than- // remembering what it chose, the same way the range reads its ports back- // from the containers that will dial them.Nonce string- // Zone is the set of names khaos is AUTHORITATIVE for, mapped to the honest- // address each one really has.- //- // This exists because of a measured constraint rather than for convenience.- // A container name or network alias can never be faulted: the target's own- // embedded resolver answers those out of its own table and never forwards- // them to an upstream, so khaos would never see the query. The faulted name- // therefore has to be one the embedded resolver cannot answer — and then- // NOBODY would answer it, and the baseline would measure a target whose- // dependency never resolved. So khaos serves it honestly itself, and the- // fault is a deviation from khaos's own correct answer.+ // The names khaos is AUTHORITATIVE for, mapped to their honest addresses. A+ // container name or alias can never be faulted, because the target's own+ // embedded resolver answers those locally and never forwards them here.Zone map[string]string- // Control is the name in Zone that no fault ever touches. It is the- // confirmation oracle's positive control: khaos serves it from the same- // table, over the same transports, through the same handler, so a control- // that stops resolving means khaos's resolver is broken rather than lying.+ // The name in Zone no fault touches, served from the same table, so a+ // control that stops resolving means khaos is broken rather than lying.Control string}-// Resolver is khaos's authoritative chaos resolver. One instance serves one-// network, is armed and disarmed in band, and attributes every query it answers-// to the address it came from.+// Resolver is khaos's authoritative chaos resolver, one instance per network.type Resolver struct {cfg Configzone map[string]string@@ -158,9 +116,7 @@ type Resolver struct {controls int64}-// New builds a resolver without binding anything. Nothing listens until Serve,-// which is what makes the whole package unit-testable in process on a high port-// with no container and no privilege.+// New builds a resolver without binding anything; nothing listens until Serve.func New(cfg Config) (*Resolver, error) {if cfg.Listen == "" {cfg.Listen = fmt.Sprintf(":%d", DefaultPort)@@ -206,16 +162,13 @@ func New(cfg Config) (*Resolver, error) {}, nil}-// Zone reports the names this resolver is authoritative for, so khaos can state-// them in a plan and a gate can census them.+// Zone reports the names this resolver is authoritative for.func (r *Resolver) Zone() map[string]string {return maps.Clone(r.zone)}-// Serve binds UDP and TCP and returns once both are accepting. Both transports-// are mandatory and not a nicety: a client that sees the truncation bit re-asks-// over TCP, the embedded resolver forwards on the transport the client used, and-// a UDP-only resolver would turn every truncation experiment into a timeout.+// Serve binds UDP and TCP and returns once both accept. Both are mandatory: a+// client that sees the truncation bit re-asks over TCP.func (r *Resolver) Serve() error {mux := dns.NewServeMux()mux.HandleFunc(".", r.handle)@@ -241,10 +194,8 @@ func (r *Resolver) Serve() error {r.servers = serversr.mu.Unlock()- // Each goroutine serves the LOCAL it was handed, never a field it reads back- // off the struct. `internal/pki` shipped three data races doing the- // opposite: its serve goroutines dereferenced a field that mutex-held- // shutdown nils, and the plain test suite was green for both new packages.+ // Each goroutine serves the LOCAL it was handed, never a field that a+ // mutex-held shutdown nils underneath it.ready := make(chan error, len(servers))for _, server := range servers {srv := server@@ -271,17 +222,9 @@ func (r *Resolver) Serve() error {return nil}-// bindBoth puts UDP and TCP on the SAME port, and that is a correctness-// requirement rather than tidiness.-//-// Handing `dns.Server` an `Addr` with port 0 and letting each transport bind-// itself gives them DIFFERENT ports, because UDP and TCP are separate port-// spaces and the kernel picks independently. A resolver like that answers over-// UDP and is unreachable over TCP, so every client that sees the truncation bit-// and re-asks per RFC 5966 gets `connection refused` — the truncation fault-// becomes an outage, and the no-TCP variant confirms itself for free against a-// port that was never listening. A test caught it; at the real :53 both happen-// to land on the same number and nothing would have.+// bindBoth puts UDP and TCP on the SAME port. They are separate port spaces, so+// letting each bind port 0 itself yields different ports and a resolver that is+// unreachable for every RFC 5966 retry.func bindBoth(listen string) (net.PacketConn, net.Listener, error) {udpAddr, err := net.ResolveUDPAddr(udpNet, listen)if err != nil {@@ -304,9 +247,7 @@ func bindBoth(listen string) (net.PacketConn, net.Listener, error) {_ = conn.Close()last = fmt.Errorf(errBindFailed, tcpNet, err)- // An explicit port cannot be retried into success, so the only case- // worth another attempt is an ephemeral one the kernel chose for UDP- // that something else already holds in the TCP space.+ // An explicit port cannot be retried into success.if udpAddr.Port != 0 {break}@@ -315,8 +256,7 @@ func bindBoth(listen string) (net.PacketConn, net.Listener, error) {return nil, nil, last}-// Addr reports where the resolver actually bound, which matters because a test-// asks for port 0 and has to find out what it got.+// Addr reports where the resolver actually bound, which matters for port 0.func (r *Resolver) Addr() string {r.mu.Lock()defer r.mu.Unlock()@@ -330,10 +270,9 @@ func (r *Resolver) Addr() string {return r.cfg.Listen}-// Shutdown closes both DNS transports and the control surface. The control-// surface goes down too, and unconditionally, because a resolver whose DNS is-// gone but whose /arm still answers is one khaos could arm and then confirm-// against nothing.+// Shutdown closes both transports and, unconditionally, the control surface: a+// resolver whose /arm answers while its DNS is gone could be armed and then+// confirmed against nothing.func (r *Resolver) Shutdown() error {r.mu.Lock()servers := r.servers@@ -355,9 +294,8 @@ func (r *Resolver) Shutdown() error {return errors.Join(failures...)}-// Arm installs a fault. An inert trap is still installed, because the negative-// control has to travel the same path as a live one: a control that skipped-// arming would prove only that the resolver was never asked.+// Arm installs a fault. An inert trap is still installed, so it travels the+// same path as a live one.func (r *Resolver) Arm(trap Trap) error {if err := trap.Validate(); err != nil {return err@@ -380,12 +318,8 @@ func (r *Resolver) Arm(trap Trap) error {return nil}-// inZone refuses a fault aimed at a name this resolver does not answer.-//-// Without it the most likely operator mistake is also the most silent one: a-// trap on a name khaos is not authoritative for arms cleanly, every query for-// it is forwarded untouched, the target resolves it perfectly, and the run-// reports a clean survival against a fault that was never applied to anything.+// inZone refuses a fault on a name this resolver does not answer, which would+// arm cleanly, forward untouched, and report a survival against nothing.func (r *Resolver) inZone(host string) error {if _, ok := r.zone[dns.CanonicalName(host)]; ok {return nil@@ -416,16 +350,9 @@ func (r *Resolver) armed() Trap {return r.trap}-// Arrivals reports how many queries came from one address. It is attributed by-// SOURCE rather than counted in total, and that is the difference between a-// proof of arrival and a number that is always non-zero.-//-// khaos queries its own resolver to confirm the fault, from the host, so its-// source is the bridge gateway. The target's queries are forwarded by the-// embedded resolver from the TARGET's own network namespace, so their source is-// the target's container address. Counting both together would make "the target-// used khaos's resolver" true on every run, including the runs where the target-// never used it at all.+// Arrivals is attributed by SOURCE rather than totalled: khaos's own probes+// arrive from the bridge gateway and the target's from its container address,+// so a total would be non-zero even when the target never used this resolver.func (r *Resolver) Arrivals(from string) int64 {r.mu.Lock()defer r.mu.Unlock()@@ -446,21 +373,12 @@ type Stats struct {Denied int64 `json:"control_denied"`Arrivals map[string]int64 `json:"arrivals"`- // Zone is the honest answer khaos serves for each name it owns, read back- // rather than remembered. A redirect's observable needs it to name the- // address the fault replaced rather than restating the one it served.+ // Read back rather than remembered, so a redirect's observable can name the+ // address the fault replaced.Zone map[string]string `json:"zone"`- // Queries counts only the queries khaos was AUTHORITATIVE for, keyed by- // source address and zone name.- //- // Arrivals alone cannot carry the proof-of-arrival control, and that is the- // whole reason this exists. A target resolving anything else through khaos's- // resolver -- a public name, another service -- makes its arrival count- // non-zero without ever asking about the dependency under fault, so the- // guard would pass for a target that never experienced the experiment. It- // would also break the TTL faults outright, whose whole measurement is HOW- // MANY times the faulted name was asked for.+ // Only the queries khaos was AUTHORITATIVE for, keyed by source and name.+ // An arrival count alone goes non-zero for a target resolving anything else.Queries map[string]int64 `json:"queries"`}@@ -512,16 +430,9 @@ func (r *Resolver) handle(w dns.ResponseWriter, req *dns.Msg) {r.reply(w, req, r.serveFault(trap, req, question, name, w))}-// lookup resolves a query name to the zone entry it belongs to, and reports-// whether khaos is authoritative for it at all.-//-// Matching is on the WHOLE name or on the name plus a suffix, because a-// container's resolv.conf carries a forced `search` domain. A target asking for-// `dependency.khaos.test` was measured arriving as both-// `dependency.khaos.test.` and `dependency.khaos.test.mynetworksettings.com.`,-// and that is not cosmetic: under a negative fault the absolute attempt fails-// and the client RETRIES with the search suffix, so a resolver that faulted only-// the exact name would answer the retry honestly and defeat its own fault.+// lookup matches the whole name or the name plus a suffix, because a container's+// resolv.conf carries a forced `search` domain and a client whose absolute+// attempt fails RETRIES with that suffix.func (r *Resolver) lookup(name string) (string, bool) {asked := dns.CanonicalName(name)@@ -546,10 +457,8 @@ func (r *Resolver) applies(trap Trap, zoneName string) bool {return dns.CanonicalName(trap.Host) == zoneName}-// honestAnswer is what khaos serves for a zone name with nothing armed against-// it, and what it serves for the control name always. Every baseline is-// measured through this, so it has to be indistinguishable from a correct-// resolver's answer.+// honestAnswer is measured by every baseline, so it has to be+// indistinguishable from a correct resolver's answer.func (r *Resolver) honestAnswer(req *dns.Msg,question dns.Question,@@ -561,10 +470,8 @@ func (r *Resolver) honestAnswer(}, addressAnswer)}-// serveFault produces the faulted answer. Every kind acts on khaos's OWN honest-// answer for the name, which is the design rule from the PKI tier restated:-// every trap corrupts exactly ONE property. A fault that synthesized its own-// address as a side effect of being slow would be two faults reported as one.+// serveFault acts on khaos's OWN honest answer for the name, so each trap+// corrupts exactly ONE property rather than being two faults reported as one.func (r *Resolver) serveFault(trap Trap,req *dns.Msg,@@ -588,14 +495,8 @@ func (r *Resolver) serveFault(}, addressAnswer)case CNAMEChain:- // The chain ends at the trap's address, not the honest one, and that is- // what makes it a finding rather than decoration. Research 05 section 10- // states the fault precisely: if name matching happens on the name that- // was ASKED rather than on the target the connection goes to, a CNAME- // out of the allowlisted zone passes the check while the traffic goes- // somewhere else. Ending the chain at the honest address would test the- // indirection and change nothing about where the traffic went, so there- // would be nothing for a control to have failed to notice.+ // Ends at the trap's address, not the honest one, or the indirection+ // changes nothing about where the traffic went.return r.synthesize(req, question, Trap{Host: zoneName,Address: trap.address(),@@ -609,11 +510,8 @@ func (r *Resolver) serveFault(return r.synthesize(req, question, honest, addressAnswer)case Truncation:- // Truncated with nothing in it over UDP, complete over TCP: the shape a- // correct truncating server has. Emptying the UDP answer is what makes- // the fault about the RETRY rather than about the bit, because a client- // that ignores `tc` and keeps the records it was given has not been- // tested by a truncated message that was complete anyway.+ // Emptying the UDP answer makes the fault about the RETRY rather than+ // the bit, since a client that ignores `tc` keeps what it was given.reply := r.synthesize(req, question, honest, addressAnswer)if protoOf(w) == udpNet {reply.Truncated = true@@ -622,10 +520,6 @@ func (r *Resolver) serveFault(return replycase TruncationNoTCP:- // Truncated and empty on BOTH transports, so the client exhausts UDP and- // TCP and still has nothing. This is research 05 row 9's actual security- // question — whether DNS over TCP is permitted at all — rather than the- // fallback question above.reply := r.synthesize(req, question, honest, addressAnswer)reply.Truncated = truereply.Answer = nil@@ -638,11 +532,8 @@ func (r *Resolver) serveFault()case Refused, Timeout, PassThrough:- // Unreachable: Validate refuses both masked kinds before a trap can be- // armed, and applies() excludes PassThrough. SERVFAIL rather than a- // silent empty reply means a future kind that forgets its branch is- // observably broken instead of looking like a target that resolved- // nothing.+ // Unreachable, and SERVFAIL rather than a silent empty reply so a future+ // kind that forgets its branch is observably broken.return new(dns.Msg).SetRcode(req, dns.RcodeServerFailure)default:@@ -650,15 +541,9 @@ func (r *Resolver) serveFault(}}-// authoritativeRcode is an rcode khaos is answering ON PURPOSE, for a name it-// owns. Every other SERVFAIL in this file is khaos failing at something and is-// left NON-authoritative, which is what makes the two distinguishable from-// outside: deleting the ServFail arm used to fall through to `default`, serve-// the same rcode, and leave every test and the whole gate green.-//-// It is also the protocol-correct answer. khaos IS the authority for its zone,-// so an NXDOMAIN or a SERVFAIL it decides on carries AA, and one it stumbles-// into does not.+// authoritativeRcode is an rcode khaos answers ON PURPOSE; every other SERVFAIL+// here is khaos failing and stays NON-authoritative, which is what tells the+// two apart from outside.func authoritativeRcode(req *dns.Msg, rcode int) *dns.Msg {reply := new(dns.Msg).SetRcode(req, rcode)reply.Authoritative = true@@ -718,22 +603,18 @@ func (r *Resolver) record(source string) {r.mu.Unlock()}-// recordQuery counts a query for a name khaos answers authoritatively, keyed by-// source AND name, because both predicates built on it need the pair.func (r *Resolver) recordQuery(source, zoneName string) {r.mu.Lock()r.queries[QueryKey(source, zoneName)]++r.mu.Unlock()}-// QueryKey is the one place the composite key is spelled, so the resolver-// counting and khaos reading cannot disagree about its shape.+// QueryKey is the one place the composite key is spelled.func QueryKey(source, zoneName string) string {return source + " " + dns.CanonicalName(zoneName)}-// Queries reports how many times one source asked about one name khaos is-// authoritative for.+// Queries reports how many times one source asked about one name khaos owns.func (r *Resolver) Queries(source, zoneName string) int64 {r.mu.Lock()defer r.mu.Unlock()diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/trap.goindex 06577c87..8d624b1b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/trap.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dnsrv/trap.go@@ -10,139 +10,74 @@ import ("time")-// Kind names one way khaos makes name resolution wrong for a target. Every kind-// maps to a row of the injectable fault matrix in research 05 section 9, and the-// two rows khaos cannot deliver are kinds here as well, so that asking for one-// gets an explanation rather than silence.-//-// What separates these from the other families is that the fault is not in the-// dependency at all. The dependency is healthy; the target cannot find it, or-// finds something else. That reaches a different branch of the target's code-// from an unreachable dependency and from one presenting a bad certificate, and-// research 05 section 10 is the argument for why those branches are where the-// fail-open lives.+// Kind names one way khaos makes resolution wrong. The dependency stays+// healthy: the target cannot find it, or finds something else.type Kind stringconst (- // PassThrough is the zero value: the resolver answers correctly by- // forwarding. A resolver with nothing armed has to be indistinguishable from- // the one the target would otherwise use, because every baseline is measured- // through it.+ // The zero value forwards, so an unarmed resolver is indistinguishable+ // from the one the target would otherwise use.PassThrough Kind = ""- // NXDomain is a definite negative answer. The client stops immediately- // without trying other servers, and a Go target gets `IsNotFound`. It is the- // cleanest demonstration in research 05 section 10: a control whose- // allowlist entry is a hostname cannot evaluate itself when the name does- // not resolve, and a great deal of code reads "could not evaluate" as "not a- // violation". Row 1.+ // A definite negative answer: the client stops immediately and a Go target+ // gets `IsNotFound`.NXDomain Kind = "nxdomain"- // ServFail is a TEMPORARY failure, and that single word is the difference- // from NXDomain: clients with retry logic retry it, so it also measures- // whether a transient resolution failure turns into a retry storm or a hang- // rather than a decision. Row 2.+ // A TEMPORARY failure, so clients with retry logic retry it.ServFail Kind = "servfail"- // SlowResponse answers correctly but late. Its ceiling is not a preference:- // Docker's embedded resolver gives up at `extIOTimeout`, measured at exactly- // 4.001s, and above that this fault silently becomes Timeout, which khaos- // refuses. So the magnitude is bounded at MaxDelay and anything larger is- // refused by name. Row 5.+ // Correct but late. Docker's embedded resolver gives up at 4.001s, so a+ // larger magnitude would silently become Timeout and is refused instead.SlowResponse Kind = "slow-response"- // WrongAddress is the money experiment of the family. The name resolves, to- // an address the operator never approved. A hostname allowlist does not- // merely stop working here, it actively authorises the wrong host, and TLS- // is the only thing left that can object. Row 6.+ // Resolves to an address nobody approved, so a hostname allowlist actively+ // authorises the wrong host.WrongAddress Kind = "wrong-address"- // CNAMEChain answers with a multi-hop CNAME ending outside the queried zone.- // It asks whether name-based matching happens on the name that was ASKED or- // on the target the connection actually goes to, which research 05 section- // 10 lists as the fourth distinct failure of hostname allowlisting. Row 10.+ // A multi-hop CNAME ending outside the queried zone, which separates+ // matching on the asked name from matching on the reached one.CNAMEChain Kind = "cname-chain"- // CNAMELoop answers with a CNAME cycle. The research measured CoreDNS- // serving one without hanging and noted explicitly that the CLIENT's loop- // handling is the thing under test, which no other kind here covers.+ // A CNAME cycle. The server serves it without hanging; the CLIENT's loop+ // handling is what is under test.CNAMELoop Kind = "cname-loop"- // Truncation sets the `tc` bit on UDP and answers completely over TCP, which- // is what a correct truncating server does. The client must notice and- // re-ask over TCP per RFC 5966.- //- // This kind exists because of a CORRECTION rather than in spite of one.- // Research 05 section 5 recorded truncation as absorbed entirely by the- // embedded resolver, which would have made the fault undeliverable. It is- // not: measured 2026-10-13, `tc=1` reaches the client in every truncating- // shape and the client's TCP retry arrives here. The original measurement- // used `dig` without `+ignore`, so dig performed the fallback itself and- // reported the clean answer. Row 9.+ // Sets `tc` on UDP and answers completely over TCP, so the client must+ // notice and re-ask over TCP per RFC 5966.Truncation Kind = "truncation"- // TruncationNoTCP sets `tc` and then never completes over TCP either. It is- // a different question from Truncation and it is the one research 05 row 9- // names as the security control: whether DNS over TCP is actually permitted- // by the egress policy. A deny-all-TCP-53 rule turns every large answer into- // total resolution failure.- //- // Measured consequence worth knowing before reading a verdict: to a Go- // target this lands as `no such host` with `IsNotFound=true`, which is- // NXDomain's classification. khaos names which one it served because the- // target cannot.+ // Sets `tc` and never completes over TCP either, asking whether DNS over+ // TCP is permitted at all. To a Go target this lands as `no such host` with+ // `IsNotFound=true`, which is NXDomain's classification.TruncationNoTCP Kind = "truncation-no-tcp"- // TTLZero and TTLLong act on the answer's lifetime rather than its content.- // They are the two kinds whose fault may be a measured NO-OP: Go has no- // answer cache and ignores TTL entirely, proven against a 604800 TTL, so- // against a Go target these test nothing.- //- // khaos does not guess. It counts the target's own queries during the fault- // window, and a target that re-queries per probe is reported UNSUPPORTED,- // the same way the revocation group reports a target that never asked.- // Rows 7 and 8.+ // Act on the answer's lifetime rather than its content. Go has no answer+ // cache and ignores TTL, so khaos counts the target's own queries and+ // reports UNSUPPORTED instead of guessing.TTLZero Kind = "ttl-zero"TTLLong Kind = "ttl-long"- // Refused and Timeout are REFUSED BY KHAOS, and they are kinds rather than- // omissions on purpose. Docker's embedded resolver rewrites both: REFUSED- // becomes SERVFAIL because `forwardExtDNS` treats it as a reason to try the- // next upstream, and a dropped query becomes SERVFAIL at a hard 4.001s.- //- // Delivering SERVFAIL while claiming REFUSED would be worse than refusing,- // because the whole point is which branch of the target's code runs, and a- // real library branches on the rcode. An operator who asks for one of these- // gets the reason and the name of the mechanism instead of a wrong- // measurement. Rows 3 and 4.+ // REFUSED BY KHAOS: the embedded resolver rewrites both to SERVFAIL, and a+ // real library branches on the rcode, so delivering one under its own name+ // would be a wrong measurement rather than a fault.Refused Kind = "refused"Timeout Kind = "timeout")const (- // MaxDelay is one millisecond under the measured `extIOTimeout` ceiling. At- // or above 4.000s the embedded resolver answers SERVFAIL itself at 4.001s- // and the delay never reaches the client, so a larger magnitude would be- // Timeout wearing SlowResponse's name.+ // One millisecond under the embedded resolver's ceiling, above which it+ // answers SERVFAIL itself and the delay never reaches the client.MaxDelay = 3999 * time.Millisecond- // DefaultDelay sits well inside the ceiling and above any plausible- // sub-second client timeout, so the fault is observable without being at the- // edge of the window khaos is allowed to use.DefaultDelay = 3 * time.Second- // LongTTL is one week, matching the research's own measurement against Go.LongTTL = 604800- // HonestTTL is what an unfaulted khaos answer carries. It matches the TTL- // Docker's own embedded resolver puts on its internal answers, so a target- // comparing them sees nothing unusual.+ // Matches the TTL Docker's embedded resolver puts on its own answers, so a+ // target comparing them sees nothing unusual.HonestTTL = 600- // DefaultWrongAddress is in TEST-NET-2, which RFC 5737 reserves for- // documentation. Nothing can be running there, so a target that connects is- // observably connecting to an address its operator never approved rather- // than to some other real service.+ // In TEST-NET-2, reserved by RFC 5737, so nothing can be running there.DefaultWrongAddress = "198.51.100.66")@@ -171,10 +106,8 @@ const (errNoHost = "%w: %s needs the dependency's name, and none was given"errBadAddress = "%w: %q is not an IP address"- // maskedRefused and maskedTimeout are the refusals themselves. They name the- // mechanism, what the target would actually have received, and what to ask- // for instead, because a refusal that does not say what to do next is a dead- // end rather than a diagnosis.+ // Each names the mechanism, what the target would really have received, and+ // what to ask for instead.maskedRefused = "Docker's embedded resolver rewrites REFUSED to SERVFAIL before the target sees it. `forwardExtDNS` treats REFUSED as a reason to try the next upstream, and with one upstream configured there is no next one, so the client is answered SERVFAIL. khaos will not deliver SERVFAIL and call it REFUSED, because a real library branches on the rcode and the branch is the finding. Run `dns.servfail` to measure the branch the target will actually take"maskedTimeout = "Docker's embedded resolver answers SERVFAIL at a measured 4.001s rather than letting a query go unanswered, so a true socket timeout cannot reach a container on a user-defined bridge. Its `extIOTimeout` is 4 seconds and the ceiling is not configurable. khaos will not deliver an rcode and call it a timeout. Run `dns.slow_response` with a delay under 4s for a late answer, or `dns.servfail` for the definite failure the target would really get"@@ -184,9 +117,7 @@ const (var ErrUnknownKind = errors.New("no DNS fault is registered under that name")-// ErrMasked is the refusal the M8 exit gate is about. It is a distinct error-// from an unknown fault, because the fault IS known, is catalogued, and is-// refused for a measured reason rather than missing.+// ErrMasked is distinct from an unknown fault: the fault IS catalogued.var ErrMasked = errors.New("khaos refuses this DNS fault because Docker's embedded resolver would rewrite it",)@@ -199,8 +130,8 @@ var ErrNoHost = errors.New("this DNS fault needs a name to act on")var ErrBadAddress = errors.New("that is not an IP address")-// Trap is one armed fault, and it travels through the journal, so every field-// has to be enough to re-describe the fault from a cold start.+// Trap travels through the journal, so every field has to be enough to+// re-describe the fault from a cold start.type Trap struct {Kind Kind `json:"kind"`Host string `json:"host"`@@ -211,16 +142,11 @@ type Trap struct {// Address is WrongAddress's answer.Address string `json:"address,omitempty"`- // Inert is the negative control. An inert trap arms the resolver with- // nothing, so every observable this fault is confirmed by must disappear.- // Without it a confirmation that reads the trap RECORD rather than the- // SERVED answer passes against a resolver that is doing nothing, which is- // the bug the PKI tier's inert authority caught three times.+ // An inert trap arms nothing, so every observable must disappear.Inert bool `json:"inert,omitempty"`}-// Kinds names every fault in the catalogue, including the two khaos refuses, so-// a census over the catalogue covers them and cannot quietly lose one.+// Kinds names every fault in the catalogue, including the two khaos refuses.func Kinds() []string {return []string{string(NXDomain),@@ -238,10 +164,7 @@ func Kinds() []string {}}-// Deliverable reports whether khaos can actually produce this fault as asked-// through Docker's embedded resolver. It is derived from one list so the-// catalogue, the refusal and the gate's census cannot disagree about which-// faults are masked.+// Deliverable reports whether khaos can produce this fault as asked.func Deliverable(kind Kind) bool {return !slices.Contains(masked, kind)}@@ -260,15 +183,12 @@ func MaskedReason(kind Kind) string {}}-// Known reports whether this is a catalogued fault at all, which is separate-// from whether it can be delivered.+// Known reports whether this is a catalogued fault, separate from deliverable.func Known(kind Kind) bool {return kind == PassThrough || slices.Contains(Kinds(), string(kind))}-// Describe says what the fault does to the target, in the operator's words. It-// is the only place the wording lives, so `khaos catalog`, `khaos plan` and the-// run record cannot describe the same fault three different ways.+// Describe is the only place the operator-facing wording lives.func (t Trap) Describe(target string) string {switch t.Kind {case NXDomain:@@ -302,10 +222,7 @@ func (t Trap) Describe(target string) string {}}-// Validate refuses a trap that cannot be armed, BEFORE it reaches the journal.-// A record khaos cannot arm is one `khaos reclaim` would retry forever, and a-// masked fault refused here is refused once with a reason rather than halfway-// through a run.+// Validate refuses a trap that cannot be armed, BEFORE the journal sees it.func (t Trap) Validate() error {if err := t.ValidateShape(); err != nil {return err@@ -318,14 +235,8 @@ func (t Trap) Validate() error {return nil}-// ValidateShape checks everything except whether khaos will deliver the fault at-// all, and the split exists because the two refusals belong at different moments.-//-// A delay above the ceiling is an operator typing a number, so it is refused-// here, at build time. A MASKED fault is not a mistake: it is a catalogued-// experiment whose answer is an explanation, so it has to build, plan and-// describe like any other entry, and Validate refuses it only when khaos is-// asked to arm one.+// ValidateShape skips deliverability, because a masked fault still has to+// build, plan and describe like any other entry.func (t Trap) ValidateShape() error {if !Known(t.Kind) {return fmt.Errorf(@@ -377,9 +288,8 @@ func (t Trap) address() string {return t.Address}-// ttl is the lifetime this trap puts on an answer it synthesizes. Every kind-// that answers at all goes through here, so a new kind cannot forget to carry-// one and serve a zero TTL by accident, which would look exactly like TTLZero.+// ttl routes every kind that answers, so a new one cannot serve a zero TTL by+// accident and look exactly like TTLZero.func (t Trap) ttl() uint32 {switch t.Kind {case TTLZero:diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.goindex f163d62e..926d8a9e 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go@@ -143,10 +143,9 @@ func (c *Client) Paused(ctx context.Context, containerID string) (bool, error) {return result.Container.State != nil && result.Container.State.Paused, nil}-// ContainerEnv reads a container's environment. khaos uses it to learn where a-// 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.+// ContainerEnv reads where a target is ALREADY addressing its dependency.+// Environment is fixed at creation, so the container is the only authority on+// what it will dial.func (c *Client) ContainerEnv(ctx context.Context,containerID string,@@ -199,11 +198,9 @@ func (c *Client) NetworkAddress(return settings.IPAddress.String(), nil}-// BridgeGateway is the address a container reaches the host on. It is the DEFAULT-// bridge's gateway and that is measured, not assumed: `host-gateway` resolves-// there, a listener on a user-defined network's own gateway is unreachable from-// 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.+// BridgeGateway is the address a container reaches the host on: the DEFAULT+// bridge's gateway, discovered rather than assumed, since it is not 172.17.0.1+// on every host and a user-defined network's own gateway is not reachable.func (c *Client) BridgeGateway(ctx context.Context) (string, error) {result, err := c.api.NetworkInspect(ctx,@@ -223,20 +220,13 @@ func (c *Client) BridgeGateway(ctx context.Context) (string, error) {return "", errors.New(errNoBridge)}-// classify turns a daemon NotFound into ErrContainerGone, which callers treat as-// "the fault went with the target" and record as successfully reverted.+// classify turns a daemon NotFound into ErrContainerGone, so it is only valid+// where the MISSING THING IS THE CONTAINER; NetworkConnect returns NotFound for+// a missing NETWORK, so see classifyNetwork.//-// It must therefore only be used where the MISSING THING IS THE CONTAINER. A-// 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.+// classifyNetwork: wrapping would let callers match on the Docker SDK's own+// error taxonomy, which is the coupling this translation exists to remove.func (c *Client) classify(err error) error {if errdefs.IsNotFound(err) {//nolint:errorlint // %v is deliberate: see above@@ -245,13 +235,9 @@ func (c *Client) classify(err error) error {return err}-// classifyNetwork is the same question for an operation that names two-// resources. A NotFound here can mean either one is missing, and only the-// container's absence makes the fault moot — a missing network leaves the-// container detached and khaos still owing a restore.-//-// It resolves the ambiguity by ASKING: if the container still exists, the-// network was the missing resource and the failure stays a failure.+// classifyNetwork resolves the ambiguity by ASKING, because only the+// container's absence makes the fault moot: if the container still exists, the+// network was the missing resource and khaos still owes a restore.func (c *Client) classifyNetwork(ctx context.Context,containerID string,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.goindex 485d8510..ddd65bfb 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/client.go@@ -67,11 +67,9 @@ func Connect(ctx context.Context, endpoint Endpoint) (*Client, error) {c := &Client{api: api, endpoint: endpoint, version: ping.APIVersion}- // The daemon's own ID, read once. It is what the journal records so khaos- // can tell its own faults from another machine's, and it has to come from- // the daemon rather than from the endpoint string: the same daemon is- // reachable as a socket path, a TCP address and an SSH context, and all- // three are the same place.+ // The daemon's own ID, read from the daemon rather than derived from the+ // endpoint string: one daemon is reachable as a socket path, a TCP address+ // and an SSH context, and all three are the same place.if info, err := api.Info(ctx, client.InfoOptions{}); err == nil {c.daemon = info.Info.ID}@@ -79,9 +77,9 @@ func Connect(ctx context.Context, endpoint Endpoint) (*Client, error) {return c, nil}-// Daemon is a stable identity for the daemon this client is attached to. It is-// empty when the daemon would not say, which callers must treat as unknown-// rather than as a match.+// Daemon is a stable identity for the daemon this client is attached to, empty+// when the daemon would not say, which callers must treat as unknown rather+// than as a match.func (c *Client) Daemon() string {return c.daemon}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.goindex 798ae89d..13791789 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/doctor.go@@ -38,18 +38,10 @@ const (checkTargets = "consenting targets"// checkDNSTier is the one check whose subject is khaos's OWN binary rather- // than the operator's Docker. `khaos resolver up` imports that binary as a- // one-layer container image with no base, so a dynamically linked build- // cannot CREATE a resolver — and it finds out at run time, with an error- // about a loader path the operator never typed. `doctor` is where khaos is- // supposed to turn that into a named cause and a fix.- //- // It does NOT lose the family, and the first wording of this check said it- // did. Arming is independent of importing: a dynamically linked khaos drives- // a resolver that already exists perfectly well, including the range's own,- // which was measured by running `dns.nxdomain` from such a build and getting- // a real verdict. Saying otherwise would have sent an operator to rebuild- // over a limit they were not hitting.+ // than the operator's Docker: `khaos resolver up` imports that binary as a+ // one-layer image with no base, so a dynamically linked build cannot CREATE+ // a resolver. It does not lose the family, because arming a resolver that+ // already exists is independent of importing one.checkDNSTier = "dns tier"fixNoEndpoint = "install Docker, or set DOCKER_HOST to a reachable daemon"@@ -160,19 +152,13 @@ func DiagnoseWith(}// dnsTierCheck reports whether khaos can stand its chaos resolver up at all,-// and how many it already has.-//-// The linkage half is checked here rather than discovered during a run, because-// the failure is otherwise invisible until the worst moment: `khaos run dns.*`-// imports an image, creates a container, starts it, and the container dies-// looking for `/lib64/ld-linux-x86-64.so.2`. The operator sees an exec error-// about a path they never typed. One line in `doctor` turns that into the build-// flag that fixes it.+// and how many it already has. The linkage half is checked here because+// otherwise the container only dies at run time, looking for a loader path the+// operator never typed.func dnsTierCheck(ctx context.Context, cli *Client) Check {- // Counted first, because it changes what a dynamic build's refusal MEANS.- // A failure to list is not a failure of the tier: khaos can still stand a- // resolver up, it just cannot say what is already there, and reporting that- // as a broken tier would send an operator to rebuild a binary that is fine.+ // Counted first, because a failure to LIST is not a failure of the tier:+ // khaos can still stand a resolver up, and calling that a broken tier would+ // send an operator to rebuild a binary that is fine.running := -1if resolvers, err := cli.Resolvers(ctx); err == nil {running = len(resolvers)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.goindex d2151a3d..c9de8a22 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/endpoint.go@@ -67,17 +67,10 @@ func ResolveEndpoint(return Endpoint{Host: host, Source: SourceEnvHost}, nil}- // An explicit DOCKER_CONTEXT=default SELECTS the default endpoint. It does- // not mean "unset", and treating it as unset is a divergence from the CLI- // that `khaos range` shells out to.- //- // Measured: with a saved current context of `ag-server` and DOCKER_CONTEXT- // set to `default`, the Docker CLI uses the LOCAL daemon while khaos used- // ag-server. khaos would then inject on one machine while `docker compose`- // acted on another, which is the worst shape this resolver can take.- //- // DOCKER_HOST outranks DOCKER_CONTEXT, measured on docker 29.1.3, which is- // why it is checked first above.+ // An explicit DOCKER_CONTEXT=default SELECTS the default endpoint rather+ // than meaning "unset". Treating it as unset diverges from the CLI, so+ // khaos would inject on one machine while `docker compose` acted on+ // another. DOCKER_HOST outranks DOCKER_CONTEXT, hence the order here.if name := environ(EnvDockerContext); name == defaultContext {return defaultEndpoint(environ)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/resolver.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/resolver.goindex 24dcbaac..f003bdd4 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/resolver.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/resolver.go@@ -24,33 +24,23 @@ import ()const (- // ResolverLabel marks a container khaos created to serve DNS, and- // ResolverNetworkLabel records which network it serves. Both exist so an- // orphan survives khaos's death and is reclaimable by label rather than by- // khaos remembering what it started, which is the same rule the netem- // sidecar tier is held to.+ // These labels let an orphan survive khaos's death and be reclaimed by+ // label rather than by khaos remembering what it started.ResolverLabel = "khaos.resolver"ResolverNetworkLabel = "khaos.resolver.network"ResolverNonceLabel = "khaos.resolver.nonce"ResolverValue = "true"- // ResolverImagePrefix tags the image khaos imports from its own binary. The- // tag carries a digest of that binary, so a rebuilt khaos imports a new- // image instead of silently running the previous build's resolver — which- // would be a resolver whose code does not match the khaos interpreting it.+ // The tag carries a digest of khaos's binary, so a rebuilt khaos imports a+ // new image instead of running the previous build's resolver.ResolverImagePrefix = "khaos-dnsrv"- // ResolverEntrypoint is where khaos's own binary lands inside the image, and- // ResolverCommand is the hidden subcommand it is started with.ResolverEntrypoint = "/khaos"ResolverCommand = "serve-resolver"- // EnvResolverNonce is where the control nonce travels. See resolverArgs for- // why it is not a flag.+ // Where the control nonce travels; see resolverArgs for why not a flag.EnvResolverNonce = "KHAOS_RESOLVER_NONCE"- // resolverBinaryMode is executable and not writable. The image has exactly- // one file in it and nothing in the container can replace it.resolverBinaryMode = 0o555digestLength = 12@@ -69,9 +59,6 @@ const (errListResolvers = "list khaos's resolver containers: %w"errResolverExists = "%w: %s already serves DNS for %s"- // A dynamically linked khaos cannot BUILD a resolver image, and drives one- // that already exists perfectly well, so the refusal says which of the two- // it is.dynamicSelfFix = "`khaos resolver up` imports khaos's own binary as a one-layer container image with no base, because an unprivileged process cannot bind port 53 and Docker's --dns carries an address with no port, so the binary has to be statically linked. This one is dynamically linked and would fail to exec with no shared libraries to find. Rebuild with CGO_ENABLED=0 (the justfile and the release builds both do), or install the released binary. Running `dns.` experiments against a resolver that already exists, including the range's, does not need this"filterLabelKey = "label"@@ -96,42 +83,27 @@ type Resolver struct {// ResolverSpec is what khaos needs to stand one up.type ResolverSpec struct {- // Network is the target's network. The resolver joins it so the target can- // reach it by address with no published host port at all.Network string- // Name is the container name, which carries the network so two resolvers on- // two networks cannot collide.+ // Carries the network, so two resolvers on two networks cannot collide.Name string- // Nonce authorises the resolver's control surface and is stored as a LABEL- // as well as passed as an argument, so khaos reads it back off the container- // rather than remembering what it chose.+ // Stored as a LABEL as well as passed in, so khaos reads it back off the+ // container rather than remembering what it chose.Nonce string- // Zone is the names the resolver is authoritative for, each mapped to its- // honest address, passed as `name=address` arguments.Zone map[string]string- // Control is the zone name no fault ever touches.Control string}-// SelfStatic refuses a khaos binary that cannot be its own container image.-//-// The check is on the ELF rather than on a build tag, because what matters is-// the artifact: `go build` with cgo available links libc for `net`, and the-// resulting binary in a base-less image dies looking for-// `/lib64/ld-linux-x86-64.so.2`. Measured on this host before the tier was-// built.+// SelfStatic refuses a khaos binary that cannot be its own container image. The+// check is on the ELF rather than a build tag because what matters is the+// artifact: cgo links libc for `net`, and that dies in a base-less image.func SelfStatic() error {return staticELF(selfExe)}-// staticELF is split out from SelfStatic so it can be given a two-sided-// control. A guard that decides whether a whole command works needs an input it-// MUST reject, and `/proc/self/exe` inside a test is whatever `go test` built,-// which is not a value a test gets to choose.func staticELF(path string) error {file, err := elf.Open(path)if err != nil {@@ -148,18 +120,9 @@ func staticELF(path string) error {return nil}-// ImportResolverImage builds a single-layer image out of khaos's own binary and-// imports it, with no base image, no registry and no network.-//-// This is what keeps the DNS tier keyless. The alternative shapes were all-// worse: a published image needs a registry and drifts out of step with the CLI-// that drives it, and building one needs the source tree, which a curl-installed-// khaos does not have. A one-file tar through the import endpoint needs nothing-// that is not already on the machine.-//-// The image is khaos's ENTIRE binary, around 24 MB, so the resolver container-// carries the whole CLI as its entrypoint. That is the price of there being no-// second artifact to build, version and keep in step with the CLI driving it.+// ImportResolverImage builds a single-layer image out of khaos's own binary,+// with no base image, no registry and no network, because a published image+// needs a registry and building one needs a source tree khaos may not have.func (c *Client) ImportResolverImage(ctx context.Context) (string, error) {if err := SelfStatic(); err != nil {return "", err@@ -174,8 +137,7 @@ func (c *Client) ImportResolverImage(ctx context.Context) (string, error) {tag := ResolverImagePrefix + ":" +hex.EncodeToString(digest[:])[:digestLength]- // Tagged by content, so a khaos that has run before reuses its image and a- // rebuilt khaos cannot run the previous build's resolver.+ // Tagged by content, so a rebuilt khaos cannot run the previous resolver.if have, err := c.hasImage(ctx, tag); err == nil && have {return tag, nil}@@ -203,10 +165,9 @@ func (c *Client) ImportResolverImage(ctx context.Context) (string, error) {}defer func() { _ = result.Close() }()- // The import endpoint streams progress and reports failures in the BODY- // rather than in the status, so an import that is never drained can fail- // invisibly and leave khaos creating a container from an image that does not- // exist.+ // The import endpoint reports failures in the BODY rather than the status,+ // so an undrained import fails invisibly and leaves khaos creating a+ // container from an image that does not exist.body, err := io.ReadAll(result)if err != nil {return "", fmt.Errorf(errImportImage, tag, err)@@ -216,29 +177,16 @@ func (c *Client) ImportResolverImage(ctx context.Context) (string, error) {return "", fmt.Errorf(errImportDrain, tag, firstLine(body))}- // Every superseded resolver image is removed now, because nothing else ever- // would. The tag carries a digest of khaos's binary, so each rebuild of- // khaos creates a NEW image and leaves the previous one behind: measured at- // 24.4MB each, and khaos is rebuilt on every `just build`. On a machine that- // also serves live traffic, litter khaos creates and never collects is- // khaos's problem rather than the operator's.- //- // Failures are deliberately ignored. An image somebody else is using is- // refused by the daemon, which is the behaviour wanted, and a resolver that- // imported correctly must not fail because tidying up afterwards did not.+ // Superseded images are removed now because nothing else ever would, and+ // failures are ignored since an image in use is refused by the daemon.c.pruneResolverImages(ctx, tag)return tag, nil}-// pruneResolverImages removes khaos's own resolver images except the one just-// imported.-//-// Three guards, because this deletes images. Only tags under-// ResolverImagePrefix are candidates, so nothing khaos did not create can be-// reached; the tag in use is excluded by name; and removal is not forced, so the-// daemon refuses any image a container still references rather than khaos-// deciding it is safe.+// pruneResolverImages has three guards, because it deletes images: only tags+// under ResolverImagePrefix, never the tag in use, and removal is not forced so+// the daemon refuses anything still referenced.func (c *Client) pruneResolverImages(ctx context.Context, keep string) {result, err := c.api.ImageList(ctx, client.ImageListOptions{})if err != nil {@@ -272,14 +220,9 @@ func (c *Client) hasImage(ctx context.Context, tag string) (bool, error) {return false, nil}-// RunResolver creates and starts a chaos resolver on a network and reads its-// address back out of the daemon.-//-// The address is read back rather than chosen, because Docker refuses `--ip` on-// a network whose subnet it picked: "user specified IP address is supported only-// when connecting to networks with user configured subnets". That measurement is-// also why arming is in band — a resolver that had to be recreated to be armed-// would move the address the target was created to dial.+// RunResolver reads the address back out of the daemon rather than choosing+// one, because Docker refuses `--ip` on a network whose subnet it picked, which+// is also why arming happens in band instead of by recreating the container.func (c *Client) RunResolver(ctx context.Context,spec ResolverSpec,@@ -311,9 +254,8 @@ func (c *Client) RunResolver(},},HostConfig: &container.HostConfig{- // Nothing is published. The resolver listens on 53 inside its own- // network namespace, which is the entire reason khaos holds no- // capability: an unprivileged host process cannot bind 53 at all.+ // Nothing is published: the resolver listens on 53 inside its own+ // namespace, which is why khaos needs no capability.RestartPolicy: container.RestartPolicy{Name: container.RestartPolicyDisabled,},@@ -333,9 +275,8 @@ func (c *Client) RunResolver(created.ID,client.ContainerStartOptions{},); err != nil {- // A container that will not start is removed rather than left behind.- // The daemon accepts a DNS entry it will later refuse at start time, so- // this path is reachable by an operator mistake and not only by a bug.+ // The daemon accepts a DNS entry it later refuses at start time, so an+ // operator mistake reaches here and must not leave a container behind._ = c.RemoveResolver(ctx, created.ID)return Resolver{}, fmt.Errorf(errStartResolve, ShortID(created.ID), err)}@@ -355,12 +296,8 @@ func (c *Client) RunResolver(}, nil}-// FindResolver looks for a resolver khaos already has on a network, by LABEL.-//-// By label and not by name, because reclaim has to work from a cold start where-// khaos remembers nothing, and because an operator who renamed one would-// otherwise get a second resolver on the same network with the target pointed at-// whichever one it was created against.+// FindResolver matches by LABEL and not by name, because reclaim works from a+// cold start and a renamed resolver would otherwise be duplicated.func (c *Client) FindResolver(ctx context.Context,networkName string,@@ -379,20 +316,12 @@ func (c *Client) FindResolver(return Resolver{}, fmt.Errorf(errNoMatch, networkName)}-// Resolvers lists every chaos resolver on this daemon, which is what `khaos-// reclaim` sweeps and what `khaos doctor` reports.+// Resolvers lists every chaos resolver on this daemon.func (c *Client) Resolvers(ctx context.Context) ([]Resolver, error) {// label=KEY=VALUE, not label=KEY. moby's MatchKVList splits on the first- // `=` and never compares the value when there is none, so the key-only- // filter matched every container carrying the label whatever it said —- // demonstrated with `com.docker.compose.project`, which returned 135- // containers across every distinct project value.- //- // That mattered because `RemoveResolver` FORCE-removes what this returns. A- // container labelled `khaos.resolver=false`, or labelled by somebody else- // entirely, was listed, adopted as khaos's own authority, and removable.- // The consent label has `checkConsentNotTrue` for exactly this reason;- // this tier took the loose filter and skipped the compensating check.+ // `=` and never compares a missing value, so a key-only filter matches+ // every container carrying the label — and RemoveResolver force-removes+ // whatever this returns.result, err := c.api.ContainerList(ctx, client.ContainerListOptions{All: true,Filters: make(client.Filters).Add(@@ -416,9 +345,8 @@ func (c *Client) Resolvers(ctx context.Context) ([]Resolver, error) {Nonce: summary.Labels[ResolverNonceLabel],}- // The address comes from the daemon rather than from the summary,- // because a created-but-never-started resolver has none and has to- // report empty rather than a stale value from somewhere else.+ // From the daemon, not the summary: a created-but-never-started+ // resolver has no address and must report empty.if address, err := c.NetworkAddress(ctx,summary.ID,@@ -433,10 +361,8 @@ func (c *Client) Resolvers(ctx context.Context) ([]Resolver, error) {return out, nil}-// RemoveResolver takes the container away. A missing container is success: the-// resolver provably went with it, and reporting that as a failure would wedge a-// journal record forever and, because `khaos reap` stops on a sweep error,-// disable the dead man's switch for every other fault on the machine.+// RemoveResolver treats a missing container as success: the resolver went with+// it, and an error would wedge a journal record and stop `khaos reap` sweeping.func (c *Client) RemoveResolver(ctx context.Context, containerID string) error {_, err := c.api.ContainerRemove(ctx,@@ -453,22 +379,10 @@ func (c *Client) RemoveResolver(ctx context.Context, containerID string) error {return err}-// resolverArgs is the command line the container runs, and the NONCE is-// deliberately not on it.-//-// Everything else is an argument, because `docker inspect` then shows exactly-// what the resolver was told and that is how khaos reads its own configuration-// back instead of remembering it. The nonce is the one field that is a secret,-// and a command line is the leakiest place to put one: measured on this host,-// `/proc/<pid>/cmdline` is mode 444 and readable by every local user, while-// `/proc/<pid>/environ` is 400. Both are equally visible through `docker-// inspect`, which already needs socket access that is root-equivalent anyway,-// so the environment satisfies the read-back reason without the leak.-//-// What the leak buys an attacker is not academic: the nonce is the sole-// authorisation for arming and disarming khaos's DNS faults, so any local user-// could `POST /disarm` after khaos confirmed a fault and khaos would measure an-// unfaulted window and report a verdict it never earned.+// resolverArgs keeps the NONCE off the command line. Everything else is an+// argument so `docker inspect` shows what the resolver was told, but+// `/proc/<pid>/cmdline` is mode 444 and readable by every local user while+// `/proc/<pid>/environ` is 400, and the nonce authorises arming and disarming.func resolverArgs(spec ResolverSpec) []string {args := []string{ResolverCommand,@@ -482,8 +396,7 @@ func resolverArgs(spec ResolverSpec) []string {return args}-// resolverEnv carries the one field that must not appear in the host's process-// table.+// resolverEnv carries the one field that must not appear in the process table.func resolverEnv(spec ResolverSpec) []string {return []string{EnvResolverNonce + "=" + spec.Nonce}}@@ -537,18 +450,14 @@ func tarSingleFile(name string, content []byte) ([]byte, error) {return buffer.Bytes(), nil}-// ResolverControlName is the confirmation control khaos generates when the-// operator did not name one. It is in `.invalid`, which RFC 2606 reserves, so-// it can never collide with a real name the target needs and can never resolve-// anywhere but khaos's own resolver.+// ResolverControlName is generated when the operator named no control. It is in+// `.invalid`, reserved by RFC 2606, so it can never collide with a real name.func ResolverControlName(networkName string) string {return "control." + networkName + ".khaos.invalid."}-// ResolverControlURL is the resolver's control surface on its own container-// address. Nothing is published to the host; the host simply routes to-// container addresses on a bridge network, which is what lets khaos arm its-// resolver without a single host port.+// ResolverControlURL is on the container's own address, which the host routes+// to directly, so nothing is ever published.func ResolverControlURL(address string) string {return fmt.Sprintf("http://%s:%d", address, dnsrv.ControlPort)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.goindex 4518892d..52b13e96 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go@@ -25,7 +25,7 @@ const (NameDependencyOutage = "network.dependency_outage"// Not a signed token in any format, so a target that honours it is not- // verifying anything.+ // verifying anything at all.DefaultInvalidToken = "khaos.invalid.credential.not.a.signed.token"probeValidName = "valid-credential"@@ -45,22 +45,18 @@ 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 come from the declaration instead, so-// a builder cannot disagree with the catalogue about what it is.+// Shape is the part of an experiment that depends on the operator's parameters;+// identity, polarity, fault kind and timing come from the declaration instead.type Shape struct {Condition stringTarget stringProbes probe.Pair- // The experiment owns the magnitude because the operator declares it as a- // parameter, so the CLI never has to infer a fault from a kind.ProxyFault *proxy.FaultProxyListen stringProxyUpstream string- // Built by the builder because its probes mint out of it.IdP *idp.ProviderIdPTrap *idp.Trap@@ -71,19 +67,17 @@ type Shape struct {ResolverNetwork stringDNSHost string- // AuthorityBase is the URL the TARGET reaches the CRL and OCSP endpoints by,- // AuthorityListen where khaos binds them. They are separate because the- // target addresses khaos by a name khaos cannot see from its own listener.+ // Separate fields because the target addresses khaos by a name khaos cannot+ // see from its own listener, so neither can be derived from the other.AuthorityBase stringAuthorityListen stringAuthorityTLS string- Defect string+ Defect string+HeldCaveat string- // Consulted reads how many times the target has reached the faulted endpoint,- // and ConsultedWhat names it; together they are the liveness guard for a fault- // whose landing the probe streams cannot see.+ // The liveness guard for a fault whose landing the probe streams cannot see.Consulted func() (int64, error)ConsultedWhat string@@ -91,11 +85,10 @@ type Shape struct {CacheRequired stringDeliveredWhat string- // IdleFor asks the engine for the idleness discriminator.IdleFor time.Duration// Act is the change khaos makes at an authority once the target can no longer- // reach it, and ActDetail is what the operator is told about it.+ // reach it.Act func(context.Context) errorActDetail string}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dns.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dns.goindex aa705822..5122396d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dns.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dns.go@@ -5,19 +5,9 @@ package experimentimport "github.com/CarterPerez-dev/khaos/internal/dnsrv"-// The `dns.` family. Each entry is a row of research 05 section 9's injectable-// fault matrix, and the two khaos cannot deliver are entries as well, so that-// asking for one gets the mechanism and a fault to run instead rather than-// silence.-//-// What this family tests that no other one can: the dependency is HEALTHY and-// the target cannot find it, or finds something else. A paused container and a-// severed path both make a dependency unreachable, and a broken certificate-// makes it unverifiable. Name resolution failing is a third branch, and research-// 05 section 10 is the argument for why the fail-open lives there: a control-// whose allowlist entry is a hostname has to resolve that name to make a-// decision, which moves its trust boundary into DNS, which nobody operating it-// controls.+// The `dns.` family, where the dependency is HEALTHY and the target cannot find+// it, or finds something else. The two faults khaos cannot deliver are entries+// as well, so asking for one gets the mechanism instead of silence.const (NameDNSNXDomain = "dns.nxdomain"NameDNSServFail = "dns.servfail"@@ -59,8 +49,6 @@ const (summaryTimeout = "a dropped query through Docker's embedded resolver, which khaos refuses to approximate; the resolver answers SERVFAIL itself at a measured 4.001s and a client never sees a socket timeout")-// dnsCatalogue is the whole family in one list, so a census can walk it and the-// catalogue, the refusals and the gate cannot disagree about what exists.var dnsCatalogue = []dnsSpec{{name: NameDNSNXDomain,@@ -135,8 +123,7 @@ func init() {}}-// DNSNames is the family, in catalogue order, for a census that has to prove it-// ran every one.+// DNSNames is the family in catalogue order.func DNSNames() []string {out := make([]string, 0, len(dnsCatalogue))for _, spec := range dnsCatalogue {@@ -146,8 +133,7 @@ func DNSNames() []string {}// DNSDeliverable splits the family into the faults khaos serves and the ones it-// refuses by name, derived from the resolver's own list so the catalogue cannot-// drift from what the resolver will actually accept.+// refuses, derived from the resolver's own list so the two cannot drift.func DNSDeliverable() (deliverable, refused []string) {for _, spec := range dnsCatalogue {if dnsrv.Deliverable(spec.fault) {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dnstier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dnstier.goindex cc5ef193..3769daf0 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dnstier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/dnstier.go@@ -14,23 +14,14 @@ import (const (FamilyDNS = "dns"- // ParamDNSHost is the dependency's NAME, and it is the parameter that makes- // this family work at all.- //- // It has to be a name khaos's resolver is authoritative for, and a name the- // target's own embedded resolver cannot answer. A container name or network- // alias is answered locally out of the embedded resolver's own table and- // never forwarded, so a fault aimed at one would be armed, never seen, and- // reported as a clean survival.+ // Has to be a name khaos's resolver is authoritative for AND one the target's+ // embedded resolver cannot answer: a container name or alias is answered+ // locally and never forwarded, so a fault aimed at one is never seen.ParamDNSHost = "dns-host"- // ParamResolverNetwork is the Docker network khaos's resolver serves, which- // must be the target's own. khaos finds the resolver there by label rather- // than being told where it is.+ // Must be the target's own network; khaos finds the resolver there by label.ParamResolverNetwork = "resolver-network"- // ParamDNSAddress is the address the redirect faults answer with, and- // ParamDNSDelay is how long the slow fault holds a lookup.ParamDNSAddress = "dns-address"ParamDNSDelay = "dns-delay"@@ -43,44 +34,18 @@ const (dnsResponse = "continuing to refuse credentials it would have refused anyway, rather than letting them through because it could not find its dependency"- // ConsultsResolver is the endpoint the liveness guard names, as an operator- // reads it in a verdict.ConsultsResolver = "khaos's chaos resolver"- // cacheRequiredTTL is what the TTL faults declare they need. A target with- // no cached answer has no lifetime to honour or ignore, so the TTL khaos- // serves governs nothing it does.cacheRequiredTTL = "the lifetime of a cached DNS answer"- // caveatRedirectUnseen is what khaos says instead of claiming the target- // verified the host it reached. khaos has no instrument at the far end of an- // operator-chosen address.caveatRedirectUnseen = "khaos served the redirect and measured that the target re-resolved, and it did NOT observe which host the target then connected to: the redirect address is an operator parameter and khaos has nothing listening at the far end of it. So this HELD means the target's control was not disturbed, and it does not establish that the target verified who it reached. If the address you redirected to answers at all, check its own logs for the target's requests before reading this as a pass"- // deliveredResolve is what the target has to DO for a DNS fault to reach it,- // phrased as the operator reads it in a verdict.deliveredResolve = "re-resolve its dependency's name")-// dnsPolarity is PERMITTED alone, and the two directions it leaves out are-// deliberate.-//-// DENIED is the correct outcome with an availability cost. A target that cannot-// resolve its identity provider and therefore refuses everything has failed-// closed; research 05 section 10 calls that bad in a different way -- DNS-// becomes a single point of failure and anyone who can break it can deny the-// service -- but it is not a security defect and khaos will not report it as-// one.-//-// HELD is not a defect either, and that is the opposite of the `tls.` family's-// polarity for a reason worth stating. There, carrying on unchanged means the-// target USED a certificate khaos deliberately broke. Here, carrying on-// unchanged means the target's control was not disturbed by its dependency-// moving or vanishing, which is what a correct control does. The case where-// carrying on hides something -- the target connected to the address khaos-// redirected it to and that address approved everything -- does not surface as-// HELD at all: it surfaces as the invalid credential being accepted, which is-// PERMITTED.+// dnsPolarity omits two directions deliberately: DENIED is correct with an+// availability cost, and HELD means the control was not disturbed -- the+// opposite of the `tls.` family.var dnsPolarity = Polarity{Defects: []Direction{Permitted},Rationale: "a control that stops rejecting invalid credentials because it could not resolve its dependency has moved its trust boundary into DNS, which nobody operating it controls; refusing to serve while continuing to enforce is the correct outcome with an availability cost, not a defect",@@ -117,25 +82,18 @@ var dnsDelayParam = Param{Default: dnsrv.DefaultDelay.String(),}-// dnsSpec is one DNS experiment's declaration. Everything not derived from a-// parameter lives here, so a builder cannot restate its own name or forget its-// polarity.type dnsSpec struct {name stringsummary stringfault dnsrv.Kind- // needsCache marks the two experiments whose question only applies to a- // target that caches. It turns a target re-resolving per request into- // UNSUPPORTED rather than a clean survival it never earned.+ // needsCache turns a target re-resolving per request into UNSUPPORTED rather+ // than a clean survival it never earned.needsCache boolextra []Param}-// dnsDefinition turns one declaration into a catalogue entry. Every DNS-// experiment goes through here, so none of them can forget the liveness guard-// that makes its verdict interpretable.func dnsDefinition(spec dnsSpec) Definition {return Definition{Name: spec.name,@@ -160,12 +118,8 @@ func buildDNS(spec dnsSpec) func(*Params) (Shape, error) {return Shape{}, err}- // SHAPE only. A delay above the measured ceiling is refused here,- // because that is an operator typing a number and they should hear it- // immediately. Whether khaos will DELIVER the fault is not checked here:- // the two masked faults are catalogued in order to be explained, so they- // build, plan and describe like any other entry and are refused when- // khaos is asked to arm one.+ // Shape only: the two masked faults still build and describe like any+ // other entry, and are refused when khaos is asked to arm one.if err := trap.ValidateShape(); err != nil {return Shape{}, err}@@ -183,51 +137,16 @@ func buildDNS(spec dnsSpec) func(*Params) (Shape, error) {DNSHost: host,Defect: spec.summary,- // The proof-of-arrival control, and it is not optional. Research 05- // section 12 states the reason: without it khaos cannot tell "the- // control failed closed" from "the fault never reached the target",- // and the second is the likely one, because `--dns` is fixed at- // container creation and Docker offers no way to change it on a- // running container. A target that was not recreated against khaos's- // resolver never sends it a single query.+ // The proof-of-arrival control: `--dns` is fixed at container+ // creation, so a target not recreated against khaos's resolver+ // never sends it a single query.ConsultedWhat: ConsultsResolver,- // The caveat on a HELD verdict for the two REDIRECT faults, and it- // is load-bearing rather than hedging.- //- // khaos measures that it served the wrong address and that the- // target re-resolved. It does NOT measure which host the target- // then connected to, because the redirect address is an operator- // parameter and khaos has no instrument at the far end of it.- //- // That gap decides the polarity. Against the default documentation- // address, with nothing listening, HELD honestly means the target- // held through an unreachable dependency, which is correct- // behaviour. Against an address that ANSWERS and mirrors the real- // dependency's decisions, the same HELD means the target moved its- // trust to a host nobody approved and khaos cleared it -- which is- // the `tls.` family's rule one domain over, where carrying on- // unchanged means the target USED the thing khaos broke.- //- // A blanket defect declaration would be wrong for the first case- // and silence would be wrong for the second, so khaos states what- // it did not observe.HeldCaveat: heldCaveatFor(spec),- // The DELIVERY guard, which no other tier needs. Every other- // fault acts on a path the target cannot avoid using; a DNS- // answer is one it can simply not ask for again, and a target- // holding a kept-alive connection does exactly that.- //- // The TTL pair is EXEMPT and that is not an oversight. For every- // other fault, a target that did not re-resolve never met the- // fault. For these two, not re-resolving is the measurement: the- // experiment is about how long a cached answer is honoured, so a- // target that re-asks less is a target that cached more. Applying- // the guard there aborted the only run the experiment exists for,- // and its own remediation ("run this against a service that- // re-resolves") contradicted cacheNotObserved's four lines- // earlier in the same verdict.+ // The delivery guard, which no other tier needs: a DNS answer is the+ // one fault a target can simply not ask for again. The TTL pair is+ // exempt, because there not re-resolving IS the measurement.DeliveredWhat: deliveredFor(spec),}@@ -239,9 +158,8 @@ func buildDNS(spec dnsSpec) func(*Params) (Shape, error) {}}-// readDNSMagnitude reads whichever parameter this experiment declared. Params-// refuses a read of a name the experiment never declared, so this cannot read a-// flag that is not there.+// readDNSMagnitude reads whichever parameter this experiment declared, since+// Params refuses a read of a name it never declared.func readDNSMagnitude(params *Params,spec dnsSpec,@@ -269,11 +187,8 @@ func readDNSMagnitude(return nil}-// heldCaveatFor returns the qualification a HELD verdict needs, or none.-//-// Only the two faults that MOVE the dependency's address carry one, because-// they are the only two where carrying on unchanged might mean the target-// reached somewhere khaos cannot see.+// heldCaveatFor qualifies HELD for the faults that MOVE the dependency's+// address, where carrying on might mean reaching somewhere khaos cannot see.func heldCaveatFor(spec dnsSpec) string {if spec.fault != dnsrv.WrongAddress && spec.fault != dnsrv.CNAMEChain {return ""@@ -282,10 +197,8 @@ func heldCaveatFor(spec dnsSpec) string {return caveatRedirectUnseen}-// deliveredFor returns the delivery question this experiment asks, or none.-//-// It is derived from the same `needsCache` declaration that turns on the cache-// reading, so the two cannot disagree about which faults are about caching.+// deliveredFor is derived from the same needsCache declaration that turns on the+// cache reading, so the two cannot disagree about which faults are about caching.func deliveredFor(spec dnsSpec) string {if spec.needsCache {return ""@@ -294,8 +207,8 @@ func deliveredFor(spec dnsSpec) string {return deliveredResolve}-// DNSDelayCeiling is the measured bound an operator sees in a refusal, exported-// so the CLI and the gate name the same number the resolver enforces.+// DNSDelayCeiling is exported so the CLI's refusal names the same number the+// resolver enforces.func DNSDelayCeiling() time.Duration {return dnsrv.MaxDelay}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.goindex 92cb50e3..d1b93c5d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/engine.go@@ -40,9 +40,8 @@ const (detailIdle = "a credential leaked; pausing traffic for %s to see whether the cache is being re-armed"detailResume = "resuming traffic with the fault still applied"- // Jitter breaks aliasing against periodic target behaviour: cache TTLs,- // token refresh and crons are exactly what these experiments measure, and- // a probe locked to a fixed period can sit in phase with them.+ // Breaks aliasing against the periodic target behaviour these experiments+ // measure: cache TTLs, token refresh and crons.jitterFraction = 0.2)@@ -54,8 +53,8 @@ type Event struct {type Reporter func(Event)-// Injector is whatever can apply, confirm and undo the fault. The engine never-// talks to Docker, so the whole lifecycle is testable without a daemon.+// Injector keeps the engine away from Docker, so the lifecycle is testable+// without a daemon.type Injector interface {Inject(ctx context.Context, kind, target string) errorConfirm(ctx context.Context) (string, error)@@ -72,13 +71,9 @@ 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.+// abandon reverts the fault and then concludes. The cause is joined with the+// rollback error, not replaced by it: the caller maps a rollback failure to its+// own exit code.func (e Engine) abandon(ctx context.Context,spec Experiment,@@ -97,16 +92,8 @@ func (e Engine) abandon()}-// 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.+// measureBaseline counts the dependency consultations while the target is still+// healthy: zero means it never used the dependency khaos is about to break.func (e Engine) measureBaseline(ctx context.Context,spec Experiment,@@ -131,10 +118,8 @@ func (e Engine) measureBaseline(observation.CacheRequired = spec.CacheRequiredobservation.Consulted = after - before- // EITHER end failing voids the count, and a negative delta is impossible- // from a monotonic counter so it can only mean khaos misread one end. Both- // are recorded rather than silently absorbed, because the guards downstream- // read zero as a statement about the TARGET.+ // Recorded rather than absorbed: the guards downstream read zero as a+ // statement about the TARGET.if beforeErr != nil || afterErr != nil || observation.Consulted < 0 {observation.CounterUnreadable = errors.Join(beforeErr, afterErr)observation.Consulted = 0@@ -143,11 +128,8 @@ func (e Engine) measureBaseline(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.+// injectionFailed concludes without judging, because a fault that never landed+// leaves no behaviour to have a direction.func (e Engine) injectionFailed(ctx context.Context,result Result,@@ -165,22 +147,11 @@ func (e Engine) injectionFailed(}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.+// act runs after the fault is confirmed because the ordering is forced: the bug+// only exists when the cache holds an ALLOW as the authority goes away.func (e Engine) act(ctx context.Context,spec Experiment,@@ -204,14 +175,8 @@ func (e Engine) act(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.+// restore runs uncancellable: an operator's Ctrl-C must not skip the rollback,+// nor the evidence that it worked.func (e Engine) restore(ctx context.Context,spec Experiment,@@ -316,17 +281,9 @@ func (e Engine) Run(ctx context.Context, spec Experiment) (Result, error) {return e.conclude(result, observation, spec.Polarity, revertErr)}-// measureFault samples under the fault and records whether the target ever MET-// it, which is a different question from whether khaos armed it.-//-// The baseline's count asks whether the target uses the thing khaos faulted at-// all; this asks whether it went back to it WHILE the fault was armed. A DNS-// fault is the case that forced the distinction: it can be armed, confirmed at-// khaos's own resolver, and reach nothing, because Go's HTTP transport resolves-// a name once per kept-alive connection. Measured on the range's own gateway at-// two lookups across forty-six requests. Every other tier collapses the two-// questions safely, because a severed path or a broken certificate sits on a-// route the target cannot avoid using.+// measureFault records whether the target ever MET the fault, not just whether+// khaos armed it: Go's HTTP transport resolves a name once per kept-alive+// connection, so a DNS fault can be armed, confirmed, and reach nothing.func (e Engine) measureFault(ctx context.Context,spec Experiment,@@ -361,16 +318,8 @@ func (e Engine) measureFault(return observation}-// discriminate is the idleness phase: stop sending traffic for longer than any-// plausible cache lifetime, with the fault still applied, then resume and measure-// again.-//-// It runs ONLY when the fault window actually leaked. The two causes it separates-// are both causes of a PERMITTED credential, so on a target that held there is-// nothing to diagnose and the pause would spend a minute of the operator's run-// learning what khaos already knows. It also runs only when the experiment asks-// for it, because the pause is meaningless without a cache lifetime to outlast-// and khaos cannot invent one.+// discriminate pauses traffic past any plausible cache lifetime with the fault+// still applied, then resumes, and only when the fault window actually leaked.func (e Engine) discriminate(ctx context.Context,spec Experiment,@@ -431,15 +380,8 @@ func (e Engine) conclude(return result, err}-// consulted reads the experiment's endpoint counter, or zero when it declares-// none.-// consulted reads the experiment's counter, and a FAILURE to read is reported-// rather than folded into zero.-//-// Zero is the sentinel three separate guards branch on, so a swallowed error-// becomes "the target never did it" and khaos blames the target for khaos's own-// unreachable instrument. An experiment with no counter is a different thing-// again and returns zero with no error, because it declared no question.+// consulted reports a FAILURE to read rather than folding it into zero, which is+// the sentinel three separate guards read as a statement about the target.func (e Engine) consulted(spec Experiment) (int64, error) {if spec.Consulted == nil {return 0, nil@@ -452,10 +394,8 @@ func markInterrupted(observation Observation) Observation {return observation}-// sample fires both probes on a true period: the time the probes themselves-// 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.+// sample fires both probes on a true period: probe time comes out of the wait,+// so a slow target cannot collapse the sample count below a verdict's floor.func (e Engine) sample(ctx context.Context,pair probe.Pair,@@ -498,8 +438,6 @@ 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 secretreturn time.Duration(rand.Float64() * span)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.goindex 1d1507b1..216345b2 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go@@ -28,8 +28,7 @@ const ()// Polarity declares which directions of breakage are defects for this control.-// It is a set, not one direction: failing open is not universally a defect, so-// each control declares its own.+// It is a set, not one direction: failing open is not universally a defect.type Polarity struct {Defects []DirectionRationale string@@ -105,13 +104,9 @@ type Experiment struct {// A non-nil ProxyFault is what tells the run to stand a fault proxy up at all.ProxyFault *proxy.Fault- // ProxyListen is where the run binds the proxy, ProxyUpstream what it- // forwards to.ProxyListen stringProxyUpstream string- // The provider is built by the catalogue rather than the run, because the- // probes mint credentials out of it and minting needs no listener.IdP *idp.ProviderIdPTrap *idp.Trap@@ -123,52 +118,36 @@ type Experiment struct {AuthorityListen stringAuthorityTLS string- // There is no resolver object here, only the fault and where to find one: an- // unprivileged process cannot bind port 53, so the resolver runs in a- // container on the target's network and the run attaches a client to it by- // label. DNSHost is the name under fault.+ // No resolver object, only the fault and where to find one: an unprivileged+ // process cannot bind port 53, so it runs in a container on the target's+ // network and the run attaches a client to it by label.DNSTrap *dnsrv.TrapResolverNetwork stringDNSHost string- // Defect names what khaos did to the credential, in words, for the verdict.Defect string- // HeldCaveat qualifies a HELD verdict where the absence of a finding covers- // less than it appears to.HeldCaveat string- // Consulted and ConsultedWhat are the liveness guard for an experiment that- // faults an ENDPOINT rather than a credential, where the probe streams cannot- // see whether the fault ever landed.+ // The liveness guard for an experiment that faults an ENDPOINT rather than a+ // credential, where the probe streams cannot see whether the fault landed.Consulted func() (int64, error)ConsultedWhat string- // Unsupportable names the check whose ABSENCE is itself the finding, which- // turns a never-consulted endpoint into UNSUPPORTED instead of a void run.- // Nothing in a request count distinguishes the two readings, so only an- // experiment that declares this gets the second one: no mainstream TLS stack- // checks revocation by default and Go's does not check it at all, so a target- // that never asked has no revocation check that could have failed.+ // Nothing in a request count separates the two readings of a never-consulted+ // endpoint, so only an experiment declaring this treats silence as a finding.Unsupportable string- // CacheRequired names the behaviour this experiment can only measure in a- // target that caches, which turns a target re-resolving per request into- // UNSUPPORTED rather than a clean survival.CacheRequired string- // DeliveredWhat names what the target would have had to DO for the fault to- // reach it, which turns an armed-and-confirmed fault the target never met- // into an aborted run rather than a clean survival.DeliveredWhat string// IdleFor must exceed the target's own decision-cache lifetime, which khaos// cannot discover, so the experiment declares it.IdleFor time.Duration- // Act runs once, after the fault is confirmed and before anything is measured- // under it, for the one thing fault injection cannot express: making a change- // at an authority the target can no longer reach.+ // Act is for the one thing fault injection cannot express: making a change at+ // an authority the target can no longer reach.Act func(context.Context) errorActDetail string}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.goindex 67581871..c929f29b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/forgery.go@@ -12,22 +12,10 @@ import (const caveatOneKeyForm = "this run keyed the forged MAC on the %s serialization only, and the same bug is unreachable under the wrong one; a target that loaded its key differently is not ruled out until each of %s has been tried"-// The forgery experiments. Each one makes khaos's own identity provider mint a-// credential that is wrong in EXACTLY ONE named way, leaves everything else-// correct, and asks whether the target notices.-//-// Every one of them is anchored to a published CVE or a normative rule, and-// every one has a different fix. That is why they are ten entries in the-// catalogue rather than one experiment with a `--trap` flag: an operator reading-// `khaos catalog` is reading a list of bugs to go and fix, and "accepts an-// unsigned token" and "ignores the expiry claim" are not two settings of one-// bug.-//-// The forged stream's baseline expectation is ACCEPTED for all ten, and that is-// not a formality. khaos's provider mints correctly until the trap is armed, so-// a target that refuses even those credentials is not pointed at khaos's-// provider at all, and without the guard every one of these experiments would-// report a clean survival against a target it never actually tested.+// Each forgery experiment mints a credential wrong in EXACTLY ONE named way and+// leaves everything else correct. The forged stream's baseline expectation is+// ACCEPTED for all ten, because khaos's provider mints correctly until the trap+// is armed: a target refusing even those is not pointed at khaos's provider.const (NameAlgNone = "identity.alg_none"NameAlgConfusion = "identity.alg_confusion"@@ -76,8 +64,6 @@ const (conditionSignatureWeakKey = "%s being offered a token signed under an undersized key")-// The defect phrase goes into the verdict, so it has to read as a sentence-// fragment naming what was wrong with the credential the target accepted.const (defectAlgNone = "no signature at all and a header saying so"defectAlgConfusion = "an HMAC keyed on its issuer's own public key"@@ -92,9 +78,7 @@ const ()// forged declares a forgery experiment. The wiring is identical across all ten-// 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.+// because the shape is.func forged(name, summary, condition, defect string,trap idp.Kind,@@ -115,10 +99,8 @@ func forged(spec.magnitude = claimShiftMagnitudecase idp.AlgConfusion:spec.magnitude = keyFormMagnitude- // Research 07's T2 is explicit that this bug is UNREACHABLE under the- // wrong serialization, and khaos tries one per run. An unqualified- // "no bypass was observed" would be khaos claiming it ruled out- // algorithm confusion when it ruled out one of four ways to express it.+ // This bug is unreachable under the wrong key serialization and khaos+ // tries one per run, so a HELD rules out one expression, not the bug.spec.heldCaveat = func(params *Params) string {return sprintf(caveatOneKeyForm,@@ -129,9 +111,6 @@ func forged(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 specdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.goindex 757aa63b..05760a01 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/identity.go@@ -28,9 +28,8 @@ const (usageAuthority = "khaos's OWN address for the identity provider, which it keeps while the target loses its path to it; this is what makes the revocation real and unreachable at the same time"usageRevocable = "a credential the target is honouring and that khaos revokes once the target can no longer reach the authority"- // Six seconds outlasts the range's own two second decision cache by a wide- // margin. Against anything else the operator sets it, because khaos cannot- // discover a cache lifetime it is probing from outside.+ // Clears the range's own decision cache; against anything else the operator+ // sets it, because khaos cannot discover a cache lifetime from outside.defaultIdleFor = "6s"revokePath = "/revoke"@@ -44,10 +43,6 @@ const (actDetail = "revoking a credential at the authority, which the target can no longer reach"- // The phrase the verdict uses to say what khaos did. It is per experiment- // because the three experiments with a revoked stream invalidate their- // credential three different ways, and only this one does it at an authority- // the target cannot see.defectIDPOutage = "revoking it at an authority the target could no longer reach"idpOutageSummary = "sever the target from its identity provider, revoke a credential there, and find out WHY the target still honours it: a decision cache being re-armed by every failed check, or one that never expires at all"@@ -57,21 +52,13 @@ const (idpOutageResponse = "refusing the credential khaos revoked, and letting any cached decision lapse on schedule rather than on idleness")-// The research calls this the highest-value single experiment in its archive, and-// the reason is the extra phases rather than the fault. Severing a target from its-// identity provider is something several tools can do. Making a change at that-// provider which the target cannot see, and then telling a cache that is being-// RE-ARMED from one that has NO EXPIRY, from outside, with no access to the-// target's source, is what no other tool does. The two have different fixes.var idpOutagePolarity = Polarity{Defects: []Direction{Permitted},Rationale: "a control that keeps honouring a credential while the authority that could revoke it is unreachable has stopped being a control, and the longer it does so the wider the exposure",}-// The fault is a PROXY fault and not a pause, and that is forced. A paused-// provider is unreachable by khaos too, so the revocation could not be made at-// all. khaos severs the target's path with its own in-process proxy and keeps its-// own direct path to the authority.+// A PROXY fault and not a pause, which is forced: a paused provider would be+// unreachable by khaos too, so the revocation could not be made at all.func buildIDPOutage(params *Params) (Shape, error) {target := params.Get(ParamTarget)probeURL := params.Get(ParamURL)@@ -85,11 +72,8 @@ func buildIDPOutage(params *Params) (Shape, error) {pair := probePair(params)- // The third stream. It carries a credential the target is honouring, and its- // acceptance AFTER khaos revokes it is the finding. It is deliberately not- // unique per request: the whole question is whether the target's cached- // decision for THIS credential outlives the authority, and a fresh identity- // every time would never reach that cache.+ // NOT unique per request: the question is whether the target's cached+ // decision for THIS credential outlives the authority.pair.Revoked = probe.NewHTTP(probe.HTTPOptions{Name: probeRevokedName,URL: probeURL,@@ -113,9 +97,8 @@ func buildIDPOutage(params *Params) (Shape, error) {}, nil}-// revokeAt asks the authority to revoke one credential. A non-2xx answer is a-// FAILED revocation, not a quiet success: the engine voids the run on it, because-// a credential nobody revoked is one the target is correct to keep honouring.+// revokeAt treats a non-2xx as a FAILED revocation and voids the run, because a+// credential nobody revoked is one the target is correct to keep honouring.func revokeAt(authority, credential string) func(context.Context) error {return func(ctx context.Context) error {endpoint, err := url.Parse(authority + revokePath)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.goindex 29865b3a..07e8b20a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/idptier.go@@ -23,34 +23,14 @@ const (probeForgedName = "forged-credential"- // The identity tier's own response. It is not the proxy tier's wording,- // because the dependency here is reachable and answering: the question is- // whether the target believes what it says.idpResponse = "refusing a credential its own identity provider should never have produced"- // Generous against the range, for the same reason the proxy tier's delay- // default is: the hold has to exceed the target's own upstream timeout or the- // trap is not expressible at all. A caller whose timeout is longer than the- // hold sees a slow SUCCESS, which is correct behaviour and not a finding.defaultIdPDelay = "2s"- // How far a corrupted claim is moved. Far enough that no clock skew- // tolerance a sane verifier carries can absorb it: the reference verifier- // allows 60 seconds and real ones allow more.defaultClaimShift = "1h"- // The floor, and it is not decoration. Measured: a 30 second shift against a- // verifier allowing the textbook 60 seconds of skew reported `PERMITTED`,- // defect, exit 2 against a target doing exactly what RFC 7519 section 4.1.4- // permits. Five minutes clears the generous configurations as well as the- // typical ones.claimShiftFloor = 5 * time.Minute- // The same hazard for a hold. A hold a target's timeout absorbs produces a- // slow SUCCESS, which is correct behaviour, so khaos can only report HELD- // and teaches the operator nothing. One second clears the sub-second- // timeouts that are common and is far above the jitter the differential- // confirmation has to see through.idpDelayFloor = time.SecondbecauseClockSkew = "a claim moved less than that sits inside the clock-skew allowance RFC 7519 permits a verifier to carry, so a correct target may accept it and khaos would report that as a bypass"@@ -58,33 +38,21 @@ const (becauseTimeout = "a hold shorter than that is absorbed by most callers' timeouts, so the target sees a slow success rather than a failure and the experiment can only ever report that it held")-// idpPolarity is the identity tier's default. Honouring a credential the-// provider marked wrong is the defect; refusing one is the control working.var idpPolarity = Polarity{Defects: []Direction{Permitted},Rationale: "a verifier that accepts a credential its own issuer declared defective has stopped being a verifier, and every credential it will ever be shown reaches it the same way",}-// rotationPolarity is the ONE inversion in the family, and it is why khaos-// carries a directional axis at all. An overlapping key rotation is the-// availability-preserving operation every provider is supposed to perform, so-// refusing a correctly signed token under the new key is the failure and-// accepting it is correct. Reporting that as a bypass would be backwards.-// BOTH directions, and the second is the point. An overlapping rotation is-// supposed to break nothing, so refusing a correctly signed new-key token is the-// failure this experiment is named for. But a target that started accepting-// credentials it had been refusing is a defect under every experiment khaos-// ships, and declaring only DENIED made khaos print "this experiment declares-// PERMITTED to be acceptable for this control" over a target that failed wide-// open, and exit 0.+// rotationPolarity is the one inversion in the family: an overlapping rotation+// should break nothing, so refusing a correctly signed new-key token is the+// failure. PERMITTED stays a defect too.var rotationPolarity = Polarity{Defects: []Direction{Denied, Permitted},Rationale: "an overlapping rotation publishes both keys precisely so nothing breaks, so a verifier that refuses a correctly signed token under the new key has turned a routine key rotation into an outage",}-// idpParams is the identity tier's parameter set. It needs no --token: the valid-// credential is minted by khaos's own provider, so there is nothing for the-// operator to supply and nothing for the range to issue.+// idpParams needs no --token: khaos's own provider mints the valid credential,+// so there is nothing for the operator to supply.func idpParams(extra ...Param) []Param {return append([]Param{{Name: ParamTarget, Usage: usageTarget, Required: true},@@ -117,8 +85,6 @@ var claimShiftParam = Param{}const (- // The two endpoints an identity experiment can fault, as they read in the- // refusal an operator sees.ConsultsJWKS = "khaos's key set endpoint"ConsultsIntrospection = "khaos's introspection endpoint"@@ -126,60 +92,24 @@ const (usageClaimShift = "how far into the past or future to move the claim khaos corrupts")-// streams is how one experiment wires its probe streams. Each field is a choice-// the experiment makes, and they are not interchangeable: the research found the-// SAME hazard pointing in OPPOSITE directions for two experiments that look-// alike, so none of this is defaulted.type streams struct {- // validTrapped mints the valid stream under the armed trap instead of- // honestly. Only the rotation experiment wants it, because there the question- // is whether the target accepts a correctly signed token under a NEW key.validTrapped bool- // validStable mints the valid stream under a key that is always published and- // never rotated, so proving the target is serving does not disturb what the- // experiment is measuring. See Provider.StableToken.validStable bool- // validOpaque gives the valid stream an OPAQUE credential, so it travels the- // introspection path and never touches key resolution at all.- //- // The rollover experiment requires it, and the requirement is forced rather- // than chosen. Research 07 section 2.3: the eviction of a retired key is a- // side effect of the refetch that a token under the NEW key triggers. A valid- // stream minting JWTs supplies exactly that traffic, so khaos was causing the- // recovery it then reported.- //- // Measured with the range verifier's key cache set to an hour, so its timer- // could not fire inside a six-second fault window: the run still returned- // `passed / HELD`. Nothing but khaos's own valid stream could have evicted- // the retired key. There is no JWT that avoids this — the retired key is- // withdrawn and any new-key token IS the contaminating traffic — so the- // stream has to leave the key path entirely.+ // A JWT valid stream would supply the new-key traffic whose refetch evicts a+ // retired key, so khaos would cause the recovery it then reports.validOpaque bool- // forged declares a forged stream and what it must do during the baseline.- // Empty means no forged stream.forged probe.Expectation- // forgedFixed mints the forged credential ONCE, before the fault, instead of- // per sample. The traps whose credential has to predate the fault need it:- // a token minted after a rotation is signed by the new key and proves- // nothing about the old one.forgedFixed func(*idp.Provider) (string, error)- // revoked declares a revoked stream, which carries a credential that was- // legitimately accepted and that the fault takes away.revoked func(*idp.Provider) (string, error)}-// idpPair builds the probe streams for one identity-tier experiment.-//-// The valid stream MINTS PER SAMPLE rather than carrying a token captured at-// build time. That is not a convenience: the provider's state changes mid-run,-// 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.+// idpPair mints the valid stream per sample rather than freezing a token at+// build time, because the provider's state changes mid-run.func idpPair(params *Params,provider *idp.Provider,@@ -203,11 +133,9 @@ func idpPair(}if wiring.validOpaque {- // Fixed and NOT unique per request. An opaque credential is a grant the- // provider holds, so a fresh one per sample would be a credential the- // target has never been told about. It is also deliberately NOT the- // revocable one, or the mutator would revoke the stream that proves the- // target is still serving.+ // Fixed and NOT unique: an opaque credential is a grant the provider+ // holds. Not the revocable one either, or the mutator would revoke the+ // stream that proves the target is still serving.valid = probe.HTTPOptions{Name: probeValidName,URL: url,@@ -242,11 +170,8 @@ func idpPair(return probe.Pair{}, err}- // Deliberately NOT unique per request. The whole question is whether the- // target's cached decision for THIS credential outlives its revocation,- // and a fresh identity every time would never reach that cache. The- // invalid control above is the opposite: it must be unique, or a cached- // refusal answers every probe. Same hazard, opposite directions.+ // NOT unique per request, unlike the invalid control above: the question+ // is whether the cached decision for THIS credential outlives revocation.pair.Revoked = probe.NewHTTP(probe.HTTPOptions{Name: probeRevokedName,URL: url,@@ -283,9 +208,7 @@ func forgedProbe(return probe.NewHTTP(options), nil}-// 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.+// mintEvery ignores the context because minting is local arithmetic with no I/O.func mintEvery(mint func() (string, error),) func(context.Context) (string, error) {@@ -294,16 +217,12 @@ func mintEvery(}}-// idpSpec is everything one identity-tier experiment declares beyond its name.type idpSpec struct {name stringsummary stringcondition stringdefect string- // heldCaveat qualifies a HELD verdict. It is per experiment because only- // some of them measure less than an unqualified "no bypass was observed"- // implies.heldCaveat func(*Params) stringtrap idp.Kindpolarity Polarity@@ -311,18 +230,12 @@ type idpSpec struct {extra []Param// consults names the provider endpoint the target has to have been using for- // this experiment's fault to reach it. Empty means the fault lands on a- // credential khaos presents, which the probe streams see directly.+ // this fault to reach it; empty means the probe streams see it directly.consults string- // magnitude reads the operator's parameter into the trap. Only the traps- // that carry one set it.magnitude func(*Params, *idp.Trap) error}-// idpDefinition turns one declaration into a catalogue entry. Every identity-// experiment goes through here so none of them can forget to build a provider,-// pin the issuer, or carry its polarity through.func idpDefinition(spec idpSpec) Definition {polarity := spec.polarityif len(polarity.Defects) == 0 {@@ -351,13 +264,9 @@ func buildIdP(spec idpSpec) func(*Params) (Shape, error) {return Shape{}, err}- // The issuer is pinned to what the TARGET was configured to trust, not to- // where khaos happens to be listening. khaos binds the bridge gateway's- // numeric address while the target addresses `host.docker.internal`, so- // minting under khaos's own listener address would get every credential- // refused on `iss` for a reason that has nothing to do with the trap, and- // a refusal for the wrong reason reads exactly like a target that caught- // it.+ // Pinned to what the TARGET trusts, not to where khaos listens: minting+ // under khaos's own bridge address would get every credential refused on+ // `iss` for a reason that has nothing to do with the trap.provider.SetIssuer(issuer)trap := idp.Trap{Kind: spec.trap}@@ -386,20 +295,11 @@ func buildIdP(spec idpSpec) func(*Params) (Shape, error) {shape.HeldCaveat = spec.heldCaveat(params)}- // The liveness guard for a fault applied to an endpoint. Both halves are- // set together, because a declared endpoint with no counter is a guard- // that can never fire and a counter with no name is a refusal that- // cannot say what to check.if spec.consults != "" {shape.ConsultedWhat = spec.consultsshape.Consulted = counterFor(provider, spec.consults)}- // Derived from the DECLARATION rather than from a second field. A- // separate flag saying "read --idle-for" sat next to the parameter that- // declares it and carried a duration of its own that nothing used, so it- // read like the default while the real default lived in the Param. The- // two could disagree and one of them would have been silently dead.if spec.wantsIdleness() {idle, err := params.Duration(ParamIdleFor)if err != nil {@@ -412,9 +312,6 @@ func buildIdP(spec idpSpec) func(*Params) (Shape, error) {}}-// wantsIdleness reports whether this experiment declared the idleness pause,-// which is the only thing that makes reading the parameter legal: Params refuses-// a read of a name the experiment never declared.func (s idpSpec) wantsIdleness() bool {for _, param := range s.extra {if param.Name == ParamIdleFor {@@ -424,16 +321,8 @@ func (s idpSpec) wantsIdleness() bool {return false}-// claimShiftMagnitude and holdMagnitude both read --delay and differ only in-// their floor, because the two faults are absorbed by different tolerances.-// counterFor maps the declared endpoint onto the provider's own measurement of-// it. The two endpoint names are constants rather than free text so a typo is a-// compile error and not a silently absent guard.-// The error is always nil, for the same reason revocationCounter's is: this-// counter lives in khaos's own process and there is no read that can fail. The-// signature carries one because the DNS tier's counter lives in another-// container, where a failed read used to be indistinguishable from a target-// that never asked.+// counterFor always returns a nil error; the signature carries one for the DNS+// tier, whose counter lives in another container.func counterFor(provider *idp.Provider,endpoint string,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/introspection.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/introspection.goindex a9cd49b2..c2fa6fe0 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/introspection.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/introspection.go@@ -7,21 +7,9 @@ import ("github.com/CarterPerez-dev/khaos/internal/idp")-// The introspection experiments. All four leave khaos's provider REACHABLE and-// ANSWERING, which is what separates them from `identity.idp_outage` and from-// every `network.` experiment.-//-// That distinction is the point, not a detail. A caller's `err != nil` branch is-// never taken here, so only its status handling, its decoder's error branch or-// its timeout decides what happens. Those are different lines of code from the-// outage path, reached by different bugs, and taxonomy row F20 is explicit that-// collapsing a denial into an unknown is its own fail-open: returning 401 in one-// phase and 503 in another and getting identical caller behaviour IS the-// finding.-//-// None of the four needs a forged stream. The generic invalid control already-// carries a credential no provider would call active, so a target that accepts-// it while introspection is useless has invented a value RFC 7662 never gave it.+// These leave khaos's provider REACHABLE and ANSWERING, so a caller's+// `err != nil` branch is never taken: only its status handling, its decoder's+// error branch or its timeout decides what happens.const (NameIntrospectionError = "identity.introspection_error"NameIntrospectionMalformed = "identity.malformed_response"@@ -46,19 +34,10 @@ const (conditionRevokedToken = "%s holding a credential its provider has revoked and can be asked about")-// The provider is reachable and will answer `active: false` on request. That-// contrast with the outage experiment is the finding's whole point, so the-// phrase has to carry it.const caveatHoldAbsorbed = "khaos held introspection for %s; a target whose own timeout is longer than that saw a slow success rather than a failure, so this run does not rule out a fail-open on a longer hold"const defectRevokedToken = "revoking it at a provider the target can still reach and ask"-// The idleness discriminator applies here too, and this is where the contrast-// with `identity.idp_outage` becomes a teaching point rather than a nuance. There-// the authority is unreachable, so a stale decision is at least explicable. Here-// the authority is answering `active: false` and the target is simply not-// asking, and the pause tells a cache being re-armed from one with no expiry at-// all.const defaultRevokeIdleFor = "6s"func init() {@@ -88,9 +67,8 @@ func init() {wiring: streams{validOpaque: true},magnitude: holdMagnitude,extra: []Param{idpDelayParam},- // A hold the target's timeout absorbs is a slow SUCCESS, which is- // correct behaviour. khaos cannot discover a timeout it is probing- // from outside, so a HELD here has to say which hold it used.+ // khaos cannot discover a timeout it is probing from outside, so a+ // HELD here has to say which hold it used.heldCaveat: func(params *Params) string {return sprintf(caveatHoldAbsorbed, params.Get(ParamDelay))},@@ -101,16 +79,8 @@ func init() {condition: conditionRevokedToken,defect: defectRevokedToken,trap: idp.Revoke,- // The revoked stream carries an OPAQUE credential, because a locally- // validated JWT cannot be revoked at all: research 07's asymmetry is- // that local validation does not fail open during a provider outage,- // it fails INVISIBLE, and revocation is a no-op until `exp`. Asking- // this question of a JWT would measure nothing.- // The valid control is opaque too. This experiment revokes an opaque- // credential and asks whether the target re-checks it, so the target- // must be one that introspects at all — and a JWT control would be- // validated locally, prove the target is serving, and prove nothing- // about the path under test.+ // Both streams are OPAQUE, because revocation is a no-op on a locally+ // validated JWT until `exp`.wiring: streams{revoked: revocableCredential, validOpaque: true},extra: []Param{{Name: ParamIdleFor, Usage: usageIdleFor, Default: defaultRevokeIdleFor}},},@@ -120,10 +90,8 @@ func init() {}}-// revocableCredential issues the opaque grant this run will revoke and records-// it on the provider as such. The mutator reads it back at inject time, because-// the trap cannot carry a credential that does not exist when the experiment is-// built.+// revocableCredential is read back by the mutator at inject time, because the+// trap cannot carry a credential that does not exist when the experiment builds.func revocableCredential(provider *idp.Provider) (string, error) {return provider.Revocable(), nil}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/keys.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/keys.goindex 52d950c6..9d02564c 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/keys.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/keys.go@@ -8,15 +8,8 @@ import ("github.com/CarterPerez-dev/khaos/internal/probe")-// The key experiments. These three change what khaos's provider SERVES rather-// than what it mints, and between them they cover the two halves of key rotation-// plus the trap research 07 calls the highest-value one in its archive.-//-// They need almost no new machinery, and that is a result rather than a-// coincidence: `kid_rollover` is a credential that was legitimately accepted and-// then taken away, which is exactly what the revoked stream already means, and-// `key_rotation` is a correctly signed credential the target may refuse, which-// is exactly what the directional axis already measures.+// The key experiments change what khaos's provider SERVES rather than what it+// mints.const (NameJWKSUnreachable = "identity.jwks_unreachable"NameKidRollover = "identity.kid_rollover"@@ -39,16 +32,12 @@ const (const (defectJWKSUnreachable = "a signature that does not verify under any published key"- // A withdrawal, not a revocation call, and the provider stays reachable- // throughout. Saying "while the authority was unreachable" here would be- // false.+ // A withdrawal, not a revocation call: the provider stays reachable.defectKidRollover = "withdrawing the key that signed it from a key set the target can still fetch")-// The idleness discriminator applies to the rollover, and it is the same-// question in a different place: a target still honouring a withdrawn key either-// re-arms its key cache on every failed refetch, or never expires it at all.-// Those are two different fixes.+// A target still honouring a withdrawn key either re-arms its key cache on every+// failed refetch or never expires it, and those are two different fixes.const defaultKeyIdleFor = "6s"func init() {@@ -61,12 +50,8 @@ func init() {trap: idp.JWKSUnreachable,consults: ConsultsJWKS,wiring: streams{- // REJECTED, the opposite of every forgery experiment, and the- // reason the expectation is declared rather than derived. This- // credential is malformed from the moment it is minted, so a- // target that did not refuse it while the key set was reachable- // was never checking signatures and its acceptance during the- // fault proves nothing changed.+ // REJECTED, the opposite of every forgery experiment: this+ // credential is malformed from the moment it is minted.forged: probe.ExpectRejected,forgedFixed: corruptedToken,},@@ -77,23 +62,9 @@ func init() {condition: conditionKidRollover,defect: defectKidRollover,trap: idp.KidRollover,- // The revoked stream, not the forged one. This credential was- // LEGITIMATE when it was issued and the rotation is what took it- // away, which is the revoked stream's exact meaning, and it brings- // the idleness discriminator with it for free.- //- // The valid stream is a JWT under a key that is NEVER rotated, and- // this experiment is not correct without that. A valid stream under- // the current signing key supplies the new-key traffic that evicts- // the retired one, so khaos caused the recovery it then reported:- // measured with the verifier's key cache set to an hour, the run- // still returned `passed / HELD` against a target with an unbounded- // stale window.- //- // An opaque credential also avoids that and was the first fix, but it- // demands the target support introspection — a JWT-only verifier- // cannot establish a baseline at all, which trades one blind spot for- // another.+ // The valid stream must use a key that is never rotated: one under the+ // current signing key would supply the new-key traffic that evicts+ // the retired one, so khaos would cause the recovery it reports.wiring: streams{revoked: honestToken, validStable: true},extra: []Param{{Name: ParamIdleFor, Usage: usageIdleFor, Default: defaultKeyIdleFor}},},@@ -103,10 +74,8 @@ func init() {condition: conditionKeyRotation,trap: idp.KeyRotation,polarity: rotationPolarity,- // No forged stream and no revoked one. The VALID stream mints under- // the armed trap, so it carries the new key's token during the fault,- // and a target that refuses it registers on the directional axis as- // DENIED. There is nothing forged anywhere in this experiment.+ // The VALID stream mints under the armed trap, so a target that+ // refuses the new key's token registers as DENIED. Nothing is forged.wiring: streams{validTrapped: true},},} {@@ -115,22 +84,15 @@ func init() {}}-// honestToken mints the credential the rollover will orphan. It is minted at-// BUILD time, which is before the fault by construction, so it is signed by the-// key the rotation is about to withdraw. A credential minted after the rotation-// would be signed by the new key and would prove nothing.+// honestToken mints the credential the rollover will orphan, at BUILD time, so+// it is signed by the key the rotation is about to withdraw.func honestToken(provider *idp.Provider) (string, error) {return provider.HonestToken()}-// corruptedToken mints a correct credential and then breaks one bit of its-// signature. Everything else about it is right: the header, the kid, the claims-// and the signature's length, so the only thing a verifier can refuse it for is-// the signature itself.-//-// That precision is the whole experiment. A garbage string would be refused by-// anything, including a verifier that skipped signature verification entirely,-// so it could never distinguish the two.+// corruptedToken breaks one bit of a correct credential's signature and leaves+// everything else right, so only the signature can be refused: a garbage string+// would be refused even by a verifier that never checks one.func corruptedToken(provider *idp.Provider) (string, error) {honest, err := provider.HonestToken()if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.goindex c04a9992..f89eb008 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/network.go@@ -21,14 +21,8 @@ const (ParamDelay = "delay"ParamBytes = "bytes"- // Where khaos binds its fault proxy, and what that proxy forwards to.- //- // They are declared PARAMETERS rather than something startProxy discovers,- // because discovery made every proxy experiment require the bundled range.- // khaos's own refusal text invited the opposite — "or point khaos at your- // own stack instead" — and then failed when an operator did.- //- // The range answers both, so a run against it still takes no flags.+ // Declared PARAMETERS rather than something startProxy discovers, because+ // discovery made every proxy experiment require the bundled range.ParamProxyListen = "proxy-listen"ParamProxyUpstream = "proxy-upstream"@@ -38,14 +32,12 @@ const (usageDelay = "how long khaos's proxy holds each exchange with the dependency"usageBytes = "how many bytes of the dependency's answer to deliver before closing"- // Two seconds is past the range gateway's own upstream timeout, so the- // default reaches the branch the experiment exists to test rather than- // producing a slow success.+ // Past the range gateway's own upstream timeout, so the default reaches the+ // branch the experiment exists to test rather than producing a slow success.defaultDelay = "2s"// Enough for a status line and the start of a body, so the target receives a- // well-formed beginning and a truncated end. That is the shape that finds a- // parser treating a short read as an empty-but-successful answer.+ // well-formed beginning and a truncated end.defaultBytes = "16"hangCondition = "%s accepting connections and never answering them"@@ -85,7 +77,6 @@ func proxyParams(extra ...Param) []Param {}, extra...)}-// proxyEndpoint reads the two addresses every proxy-tier experiment needs.func proxyEndpoint(params *Params) (string, string) {return params.Get(ParamProxyListen), params.Get(ParamProxyUpstream)}@@ -102,8 +93,7 @@ var bytesParam = Param{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.+// plainProxyShape covers the three faults that carry no magnitude.func plainProxyShape(kind proxy.Kind,condition string,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.goindex 760d0fd4..05351687 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/params.go@@ -31,10 +31,8 @@ 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-// validates against, so an experiment can neither be handed an input it never-// asked for nor be given one it silently ignores.+// Param declares one input an experiment needs, and is the single place the CLI+// registers flags from and Bind validates against.type Param struct {Name stringUsage string@@ -42,9 +40,8 @@ type Param struct {Default string}-// Params is the bound, validated parameter set for one build. Get records every-// read so Build can reject a builder reaching for a name nobody declared, which-// is otherwise an empty string with no symptom.+// Params records every read, so Build can reject a builder reaching for a name+// nobody declared, which is otherwise an empty string with no symptom.type Params struct {values map[string]stringread map[string]bool@@ -78,11 +75,8 @@ func Bind(declared []Param, supplied map[string]string) (*Params, error) {stray: map[string]bool{},}- // Presence decides whether the default applies, not emptiness. An operator who- // explicitly asked for an empty value has asked for something meaningful: an- // empty credential is sent as no Authorization header, which is the- // unauthenticated negative control. Overwriting it with the default makes that- // control impossible to express.+ // Presence decides whether the default applies, not emptiness: an empty+ // credential is the unauthenticated negative control, sent as no header.for _, param := range declared {value, given := supplied[param.Name]if !given {@@ -133,10 +127,8 @@ func sorted[V any](m map[string]V) []string {return out}-// Duration and Count parse a declared parameter and refuse a value the fault-// cannot use. The refusal names the flag and what was typed, because a fault-// whose magnitude failed to parse would otherwise fall back to zero, and a zero-// delay or a zero byte budget is indistinguishable from no fault at all.+// Duration and Count refuse a value the fault cannot use, because a magnitude+// that failed to parse would fall back to zero: no fault at all.func (p *Params) Duration(name string) (time.Duration, error) {raw := p.Get(name)@@ -153,18 +145,7 @@ func (p *Params) Duration(name string) (time.Duration, error) {}// AtLeast is Duration with a floor, for the magnitudes where a value the target-// is ALLOWED to tolerate is not a smaller fault but a different and false-// finding.-//-// Measured: `identity.claim_expired --delay 30s` against a textbook verifier-// that allows 60 seconds of clock skew, which RFC 7519 section 4.1.4 explicitly-// permits, produced `deviated / PERMITTED`, defect, exit 2. khaos confirmed the-// trap honestly — the token really was expired — and then reported a correct-// target as broken, because an expiry inside the skew allowance is one a correct-// verifier is supposed to accept.-//-// 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.+// is ALLOWED to tolerate is not a smaller fault but a false finding.func (p *Params) AtLeast(name string,floor time.Duration,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.goindex b21b0e1b..d3029255 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.go@@ -5,19 +5,13 @@ package experimentimport "github.com/CarterPerez-dev/khaos/internal/pki"-// FamilyTLS is the family name every certificate experiment carries, which-// `khaos catalog` groups by.+// FamilyTLS is the family name every certificate experiment carries.const FamilyTLS = "tls"-// The `tls.` family. One experiment per certificate trap, named for what khaos-// does rather than for what it hopes to find.-//-// The summaries say what the fault CATCHES, because that is the only thing that-// makes an entry in `khaos catalog` worth reading. Several of them catch the-// same client-side error and are told apart only by what khaos knows it served:-// self-signed, untrusted-CA and missing-intermediate all produce-// `x509: certificate signed by unknown authority`, and the two extended-// key-usage faults both produce Reason 4, measured on go1.26.5.+// One experiment per certificate trap. The summaries say what the fault CATCHES,+// because several produce byte-identical client errors: self-signed, untrusted-CA+// and missing-intermediate all give `x509: certificate signed by unknown+// authority`.const (NameLeafExpired = "tls.leaf_expired"NameLeafNotYetValid = "tls.leaf_not_yet_valid"@@ -63,9 +57,8 @@ const (NameClientCertExpired = "tls.mtls_client_expired"NameClientCertAbsent = "tls.mtls_client_absent"- // Shares the revoked-via-crl TRAP, because the fault khaos injects really- // is revocation. What differs is the finding: whether a session established- // before the revocation outlives it.+ // Shares the revoked-via-crl TRAP; what differs is the finding, whether a+ // session established before the revocation outlives it.NameResumptionAfterRevocation = "tls.resumption_after_revocation")@@ -116,24 +109,13 @@ const (sumResumption = "establish a session while the certificate is good and revoke it afterwards, which a resumed connection never notices: crypto/tls does not run VerifyPeerCertificate on a resumed handshake, so an application whose pinning or revocation check lives in that hook enforces it once and skips it for the ticket's lifetime, which Go caps at seven days")-// caSwapPolarity is the one experiment in the family whose acceptance is not a-// finding about the target at all.-//-// Once the anchor is replaced the chain is genuinely valid, and no client-side-// check can see it. Declaring HELD a defect here would accuse every correct TLS-// implementation in existence of a bug. The experiment is worth running anyway,-// because the lesson is what it takes to detect this -- pinning, or certificate-// transparency -- and khaos can show that neither is in crypto/x509.+// caSwapPolarity is the one experiment whose acceptance is not a finding: once+// the anchor is replaced the chain is genuinely valid and no client can see it.var caSwapPolarity = Polarity{Defects: []Direction{Permitted},Rationale: "a replaced trust anchor makes the chain genuinely valid and no client-side check can detect it, so accepting it is correct behaviour rather than a defect; only dropping enforcement would be one",}-// The definitions are split by group rather than listed in one block, because-// the groups are how research 04 organises the fault table and how every other-// file in this family reads. certificateExperiments covers the faults in the-// certificate itself; revocationExperiments covers the ones in what an-// authority SAYS about it.func init() {groups := [][]Definition{subjectExperiments(),@@ -150,8 +132,7 @@ func init() {}}-// subjectExperiments are the faults in WHEN a certificate is valid and WHO it-// is for.+// subjectExperiments are the faults in WHEN a certificate is valid and WHO for.func subjectExperiments() []Definition {return []Definition{// Validity.@@ -195,14 +176,9 @@ func subjectExperiments() []Definition {// chainExperiments are the faults in the path from leaf to trusted root, plus// the two in how it is signed and what it may be used for.-//-// Five of these produce byte-identical client errors in two groups: the first-// three all give `x509: certificate signed by unknown authority`, and the two-// extended key-usage faults both give Reason 4. Nothing a target logs can tell-// them apart, which is why khaos reports what it SERVED.func chainExperiments() []Definition {return []Definition{- // The chain. The first three are the byte-identical group.+ // The chain.tlsDefinition(tlsSpec{name: NameSelfSigned,summary: sumSelfSigned,@@ -234,7 +210,7 @@ func chainExperiments() []Definition {trap: pki.PathLengthExceeded,}),- // Signing and usage. The last two are the second identical group.+ // Signing and usage.tlsDefinition(tlsSpec{name: NameSHA1Signature,summary: sumSHA1,@@ -254,11 +230,9 @@ func chainExperiments() []Definition {}// policyExperiments are the faults crypto/x509 ACCEPTS, so none of them tests-// the library at all: they test whether the target imposed a policy of its own.-// An acceptance here is the absence of a floor, not a bypassed check.+// the library: they test whether the target imposed a policy of its own.func policyExperiments() []Definition {return []Definition{- // Policy: the faults crypto/x509 accepts.tlsDefinition(tlsSpec{name: NameWeakKey,summary: sumWeakKey,@@ -277,9 +251,8 @@ func policyExperiments() []Definition {trap: pki.KeyUsageWithoutDigitalSignature,}),- // The trust store. It sits with the certificate faults rather than the- // revocation ones because nothing about revocation is involved: the- // chain is impeccable under an anchor khaos replaced.+ // The trust store, which sits here because the chain is impeccable under+ // an anchor khaos replaced.tlsDefinition(tlsSpec{name: NameCASwap,summary: sumCASwap,@@ -290,12 +263,7 @@ func policyExperiments() []Definition {}// revocationExperiments are the faults in what an authority SAYS about a-// certificate rather than in the certificate.-//-// Every one of them declares its endpoint, and that declaration is what turns-// on the UNSUPPORTED reading: a target that never asked has no revocation check-// that could have failed, and reporting its acceptance as a bypass would-// accuse it of skipping something it never had.+// certificate, each declaring the endpoint that turns on the UNSUPPORTED reading.func revocationExperiments() []Definition {return []Definition{// By CRL.@@ -319,7 +287,7 @@ func revocationExperiments() []Definition {consults: ConsultsCRL,}),- // Revocation by OCSP.+ // By OCSP.tlsDefinition(tlsSpec{name: NameOCSPRevoked,summary: sumOCSPRevoked,@@ -386,14 +354,8 @@ func revocationExperiments() []Definition {}}-// mutualExperiments are the two faults in the TARGET's own identity, plus the-// one whose finding is about a session rather than a certificate.-//-// The mutual TLS pair does not test khaos's server, which refuses both-// correctly. It tests whether the target NOTICES being refused, and under TLS-// 1.3 that comes down to whether it reads: research 04 measured every row of-// the ClientAuth matrix returning a successful tls.Dial even where the server-// served nothing at all.+// mutualExperiments test whether the target NOTICES being refused, which under+// TLS 1.3 comes down to whether it reads: the dial succeeds either way.func mutualExperiments() []Definition {return []Definition{tlsDefinition(tlsSpec{@@ -408,14 +370,8 @@ func mutualExperiments() []Definition {trap: pki.ClientCertAbsent,}),- // The SAME trap as tls.revoked_via_crl, deliberately. khaos injects- // revocation either way; this experiment exists because the question- // "does a session established beforehand outlive it" is a different- // finding from "does the target check revocation at all", and a target- // can pass the first and fail this one.- //- // It declares the endpoint for the same reason the revocation group- // does: a target that never asks has no check to skip on resumption.+ // The same trap as tls.revoked_via_crl, deliberately: a target can check+ // revocation and still never notice it on a resumed session.tlsDefinition(tlsSpec{name: NameResumptionAfterRevocation,summary: sumResumption,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.goindex f93b7587..67cf0270 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go@@ -11,17 +11,9 @@ import ()const (- // Where khaos binds its certificate authority, and the URL the TARGET- // reaches it by.- //- // They are two parameters and not one, and that is the identity provider's- // most expensive bug stated as a design rule. khaos binds the Docker bridge- // gateway's numeric address while the target addresses- // `host.docker.internal`, so a URL derived from khaos's own listener is- // unreachable from inside the target's network namespace. Every revocation- // fetch would then fail for a reason that has nothing to do with the trap,- // and the run would report the target as fail-closed when khaos had simply- // pointed it at nowhere.+ // Two parameters, not one: khaos binds the bridge gateway's address while the+ // target addresses `host.docker.internal`, so a URL derived from khaos's own+ // listener is unreachable from the target's network namespace.ParamAuthorityListen = "authority-listen"ParamAuthorityTLS = "authority-tls"ParamAuthorityBase = "authority-base"@@ -46,43 +38,21 @@ const (tlsResponse = "declining to use a dependency whose identity it cannot verify, rather than talking to it anyway"- // ConsultsCRL and ConsultsOCSP are the revocation endpoints, as they read- // in the verdict an operator sees.ConsultsCRL = "khaos's CRL distribution point"ConsultsOCSP = "khaos's OCSP responder"- // unsupportableRevocation is what the UNSUPPORTED verdict names. It is a- // property of the CHECK, not of any one language: no mainstream TLS stack+ // A property of the CHECK, not of any one language: no mainstream TLS stack// checks revocation by default and Go's does not check it at all.unsupportableRevocation = "revocation checking")-// tlsPolarity is the first polarity in khaos where HELD is a defect, and the-// reasoning is worth stating because it reads backwards at first glance.-//-// khaos presents a certificate that is wrong in one specific way. A target that-// carries on exactly as before has ACCEPTED it: valid traffic served, invalid-// traffic refused, nothing disturbed. That is HELD, and it means the target-// talked to a dependency whose identity it could not verify. On the other side-// of a certificate it should have refused there could be anything.-//-// A target that refuses the certificate cannot reach its dependency, and then-// the ordinary question applies: if it keeps enforcing but stops serving, that-// is DENIED, and for a certificate fault that is the CORRECT outcome with an-// availability cost. If it stops enforcing, that is PERMITTED and it is the-// worst of the three.-//-// So two directions are defects here and the pass is DENIED.+// tlsPolarity is the one polarity where HELD is a defect: carrying on unchanged+// means the target ACCEPTED a certificate khaos broke. DENIED is the pass here.var tlsPolarity = Polarity{Defects: []Direction{Held, Permitted},Rationale: "a target that carries on unchanged has accepted a certificate khaos deliberately broke, which means it will talk to anything presenting one; refusing the dependency and declining to serve is the correct outcome, and refusing it and then letting invalid credentials through is the worst",}-// policyPolarity is for the faults crypto/x509 ACCEPTS. The target is not being-// caught out by its TLS library, because the library never objected: it either-// imposed a policy of its own or it did not.-//-// PERMITTED is still a defect, because dropping enforcement is always one.var policyPolarity = Polarity{Defects: []Direction{Held, Permitted},Rationale: "crypto/x509 accepts this certificate, so a target that carries on unchanged has no policy of its own rather than a bypassed check; the finding is the absence of the floor, not a skipped verification",@@ -127,29 +97,20 @@ var certDaysParam = Param{Default: "2000",}-// tlsSpec is one certificate experiment's declaration. Everything that is not-// derived from a parameter lives here, so a builder cannot restate its own name-// or forget its polarity.type tlsSpec struct {name stringsummary stringtrap pki.Kind- // polarity defaults to tlsPolarity, or policyPolarity for the faults Go- // accepts, which is derived rather than restated per experiment.polarity Polarity- // consults names the revocation endpoint this fault acts on. Setting it- // turns on the UNSUPPORTED reading, which is the whole point of the- // revocation group: a target that never asked has no check that failed.+ // consults turns on the UNSUPPORTED reading: a target that never asked has no+ // revocation check that could have failed.consults stringextra []Param}-// tlsDefinition turns one declaration into a catalogue entry. Every certificate-// experiment goes through here, so none of them can forget to build an-// authority, pin its base URL, or carry its polarity through.func tlsDefinition(spec tlsSpec) Definition {polarity := spec.polarityif len(polarity.Defects) == 0 {@@ -211,15 +172,10 @@ func buildTLS(spec tlsSpec) func(*Params) (Shape, error) {Defect: spec.summary,}- // Both halves together. A declared endpoint with no counter is a guard- // that can never fire, and a counter with no name is a verdict that- // cannot say what to check.if spec.consults != "" {shape.ConsultedWhat = spec.consultsshape.Consulted = revocationCounter(authority, spec.consults)- // The same observation that would void an endpoint-aimed fault is- // the ANSWER here, so this experiment asks for the second reading.shape.Unsupportable = unsupportableRevocation}@@ -227,9 +183,8 @@ func buildTLS(spec tlsSpec) func(*Params) (Shape, error) {}}-// readMagnitude reads whichever parameter this experiment declared. Only the-// traps that carry a magnitude declare one, and Params refuses a read of a name-// the experiment never declared, so this cannot read a flag that is not there.+// readMagnitude reads whichever parameter this experiment declared, since Params+// refuses a read of a name it never declared.func readMagnitude(params *Params,spec tlsSpec,@@ -270,15 +225,8 @@ func readMagnitude(return nil}-// revocationCounter reads how many times the TARGET reached the endpoint this-// experiment faults. khaos's own confirmation probes are already subtracted by-// the authority, because a count that included them would make "the target-// checked revocation" true for every run and the UNSUPPORTED verdict would-// never fire.-// The error is always nil, and that is the point of the wrapper rather than a-// shortcut. This counter lives in khaos's own process, so there is no read that-// can fail; the DNS tier's counter lives in another container and can, which is-// why the signature carries one at all.+// revocationCounter counts the TARGET's fetches only; khaos's own confirmation+// probes are subtracted by the authority, or every run would look like a check.func revocationCounter(authority *pki.Authority,endpoint string,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.goindex bb67b19f..e26d1091 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go@@ -20,25 +20,9 @@ const (Interrupted Epistemic = "interrupted"Errored Epistemic = "error"- // Unsupported is a clean, well-measured run whose QUESTION does not apply- // to the target. It is not a pass, not a defect, and not a measurement- // failure, and conflating it with any of the three is a lie in a different- // direction each time.- //- // It exists because of revocation. Go's crypto/x509 performs no revocation- // checking of any kind and has no option to turn it on, so a Go target- // handed a certificate revoked in a valid, in-date, correctly signed CRL- // from its own issuer accepts it with a nil error. Calling that PERMITTED- // would accuse the target of skipping a check it never had; calling it- // PASSED would be worse, because the certificate really was revoked and- // really was used. Research 04 is explicit: a revoked assertion must report- // unsupported, never pass.- //- // khaos decides this by MEASUREMENT, not by being told the target's- // language. The authority counts what the target fetched, so "it never- // asked about revocation" is an observation rather than an assumption, and- // a target that DID ask and then used the certificate anyway is a genuine- // defect that still reports as one.+ // Unsupported is a clean run whose QUESTION does not apply to the target:+ // not a pass, not a defect, not a measurement failure. It is decided by+ // counting what the target actually did, never by assuming its language.Unsupported Epistemic = "unsupported")@@ -52,66 +36,37 @@ const (Undetermined Direction = "UNDETERMINED")-// Cause is a THIRD axis, and it is deliberately not a value on the directional-// one. Direction answers which way the target broke; cause answers why it is-// still broken, and the two are orthogonal. `PERMITTED` has two causes that look-// identical from outside under steady traffic and need completely different-// fixes, so collapsing them into the direction would lose the distinction khaos-// exists to draw here.+// Cause is a third axis rather than a value on the directional one: direction+// answers which way the target broke, cause answers why it is still broken.type Cause stringconst (- // Undiagnosed is the honest default. Nothing ran that could tell the causes- // apart, so khaos says so rather than guessing one.+ // Undiagnosed means nothing ran that could tell the causes apart.Undiagnosed Cause = "UNDIAGNOSED"- // TTLExtension is the decision cache being re-armed on every failed check.- // Research 07 section 3.3 pins it to one line inside an error branch:- // `cache.Set(tok, stale, ttl)`. The TTL stops bounding staleness and starts- // bounding IDLENESS, so a cached allow becomes permanent exactly when the- // authority that could revoke it is unreachable. It survives any amount of- // steady traffic and dies the moment traffic pauses.+ // TTLExtension is a cache re-armed by every failed check, so its lifetime+ // bounds idleness rather than staleness: it survives any amount of steady+ // traffic and dies the moment traffic pauses.TTLExtension Cause = "TTL-EXTENSION"- // LapsedOnPause is enforcement returning after the pause, with khaos unable- // to say WHY. It is the honest middle between the two diagnoses.- //- // TTL-EXTENSION claims the cache was being re-armed by traffic. That only- // follows if steady traffic kept the credential alive for at least as long- // as the pause then killed it: otherwise an ordinary fixed expiry explains- // the same observation, and khaos would prescribe removing a cache write- // that does not exist.+ // LapsedOnPause is enforcement returning after the pause with khaos unable+ // to say why, because an ordinary fixed expiry between the steady window and+ // the pause produces the same observation as re-arming.LapsedOnPause Cause = "LAPSED-ON-PAUSE"- // StalePastPause is a cached state the traffic pause did not let lapse.- //- // It is NOT called NO-EXPIRY, and the rename is a correctness fix rather than- // a wording preference. Research 07's open question 5 is explicit: khaos- // cannot tell a cache with no expiry from one whose lifetime simply exceeds- // the experiment, "not without running longer than the TTL", and the- // experiment "should report an observed lower bound on the stale window and- // label it as a bound, never as 'caches forever'".- //- // A label asserting an unbounded cache cannot be earned from a window of- // seconds: any cache whose lifetime exceeds the observation looks identical- // to one that never expires, and a bounded cache is a defensible design- // rather than a defect.+ // StalePastPause is a cached state the pause did not let lapse. It is not+ // called NO-EXPIRY because a lifetime merely longer than the observation is+ // indistinguishable from an absent one.StalePastPause Cause = "STALE-PAST-PAUSE")-// Recovery is what khaos saw after it reverted the fault. It is three-valued-// because "not observed" and "observed healthy" are different facts, and-// collapsing them let an empty recovery window read as a clean comeback.+// Recovery is what khaos saw after reverting the fault. Three-valued because an+// unobserved recovery window is not an observed healthy one.type Recovery stringconst (- // Recovered is a healthy run of consecutive pairs after the revert.- Recovered Recovery = "recovered"-- // Degraded is measured and NOT healthy: the target did not come back.- Degraded Recovery = "degraded"-- // Unobserved is no usable evidence either way. It is not a pass.+ Recovered Recovery = "recovered"+ Degraded Recovery = "degraded"Unobserved Recovery = "unobserved")@@ -125,25 +80,19 @@ const ()const (- // A single accepted credential that the target had already rejected is- // PROOF of a bypass, so PERMITTED needs n=1. The absence of one is not- // proof of its absence, so HELD needs a sample-size argument. The- // asymmetry is deliberate.+ // The evidence bar is asymmetric on purpose. One accepted credential the+ // target had already rejected PROVES a bypass; the absence of one does not+ // prove there is none, so a clean hold needs a sample-size argument.MinimumToProveOpen = 1MinimumToClaimClosed = 30MinimumPaired = 5- // queriesPerLookup is how many queries one hostname lookup puts on khaos's- // resolver, measured rather than assumed: Go fires A and AAAA in parallel- // per name, and under a negative fault the forced `search` domain doubles- // the names tried. Four is the figure the 16.003s dropped-query measurement- // in research 05 section 14.6 is built from.+ // Go fires A and AAAA in parallel per name, so one hostname lookup is two+ // queries at khaos's resolver.queriesPerLookup = 2- // cacheLookupGrace is how many whole lookups a target is allowed inside the- // baseline before khaos will say it holds no cached answer. One would be- // exact; two leaves room for a retry or a second name without khaos- // claiming more than it saw.+ // Whole lookups allowed inside the baseline before khaos will say the target+ // holds no cached answer.cacheLookupGrace = 2RecoveryRunLength = 2crashFraction = 0.5@@ -240,14 +189,9 @@ type Observation struct {// about to apply is one the target cannot experience.Consulted int64 `json:"consulted,omitempty"`- // CounterUnreadable is khaos failing to read its OWN instrument, which is a- // different thing from the target not having used it and must never be- // reported as the second.- //- // Three guards branch on a count of zero -- checkNotImplemented,- // cacheNotObserved and endpointNeverConsulted -- and each of them makes a- // statement about the TARGET. A swallowed read error reaching them produces- // a paragraph blaming the target's connection pool for khaos's own timeout.+ // CounterUnreadable is khaos failing to read its OWN instrument. Three+ // guards read a count of zero as a statement about the TARGET, so a failed+ // read must never reach them as one.CounterUnreadable error `json:"-"`ConsultedWhat string `json:"consulted_what,omitempty"`@@ -262,66 +206,30 @@ type Observation struct {Delivered int64 `json:"delivered,omitempty"`DeliveredWhat string `json:"delivered_what,omitempty"`- // CacheRequired names the behaviour an experiment can only measure in a- // target that CACHES, and it is the INVERSE of Unsupportable rather than a- // variation on it.- //- // Unsupportable reads a count of ZERO as the answer: the target never- // performed the check, so there was none to fail. This reads a count of ONE- // PER PROBE as the answer: the target re-resolved every single time, so it- // holds no cached answer and the lifetime this experiment manipulates- // governs nothing it does.- //- // It is declared rather than derived because the same observation is a- // finding for one experiment and noise for another. A target that- // re-resolves per request is exactly correct for every other DNS fault, and- // only the two TTL faults have nothing left to measure in it. Go has no- // answer cache and ignores TTL entirely, proven against a 604800 TTL, so- // against a Go target this is the honest verdict every time -- and khaos- // MEASURES it rather than inferring it from a language it was never told.+ // CacheRequired is the INVERSE of Unsupportable: that reads a count of zero+ // as the answer, this reads a count that scales with traffic. Declared per+ // experiment, because a target re-resolving per request is correct for every+ // DNS fault except the two about a cached answer's lifetime.CacheRequired string `json:"cache_required,omitempty"`- // MintedByKhaos records that the valid credential came from khaos's own- // identity provider rather than from the operator. It changes only the- // wording of one refusal, and that wording is the difference between telling- // an operator their target is down and telling them what to check.+ // MintedByKhaos changes the wording of one refusal: whether the operator is+ // told their target is down or told what to check.MintedByKhaos bool `json:"minted_by_khaos,omitempty"`- // HeldCaveat qualifies a HELD verdict for the experiments whose absence of a- // finding covers less than it appears to. An unqualified "no bypass was- // observed" from a probe that tried one of four key serializations, or a- // hold the target's timeout may simply have absorbed, is khaos claiming more- // than it measured.+ // HeldCaveat qualifies a HELD verdict whose absence of a finding covers less+ // than it appears to.HeldCaveat string `json:"held_caveat,omitempty"`- // Defect names what khaos DID to the credential the finding is about, in- // words, so the verdict can state the actual observation.- //- // It is per experiment rather than a constant because the three experiments- // with a revoked stream invalidate their credential in three different ways,- // and one constant said all of them happened "while that authority was- // unreachable". That is true only of the outage experiment: a key rollover- // and a plain revocation both leave the provider fully reachable and- // answering, so the constant had khaos asserting something false about its- // own run on two of the three.+ // Defect names what khaos DID to the credential, in words, per experiment:+ // the three experiments with a revoked stream invalidate it three different+ // ways and a shared constant would describe two of them falsely.Defect string `json:"defect,omitempty"`}-// Judge resolves two independent axes. The epistemic one answers whether the-// 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.-// 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.+// epistemic answers whether the run can be believed at all, checked in the order+// that lets the most fundamental finding win. The bool is whether the caller may+// go on to ask which way the target broke.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}if observation.RollbackFailed {@@ -399,18 +307,10 @@ func epistemic(observation Observation) (Verdict, bool) {return verdict, false}- // AFTER confirmation, which is now true of the CODE and not only of an- // invariant in another file. The comment claimed this ordering while the- // check sat above the confirmation test; it was unreachable out of order- // through Engine.Run, because DeliveredWhat is only set inside measureFault,- // but Judge is exported and the verdict tests call it directly, so the- // sentence was one refactor away from lying.- //- // The two claims are genuinely different. Confirmed means khaos really armed- // the fault; delivered means the target really met it. Every other tier- // collapses them safely, because a severed path or a broken certificate sits- // on a route the target cannot avoid. A DNS answer is one it can simply not- // ask for again.+ // After confirmation, because the two are different claims: confirmed means+ // khaos armed the fault, delivered means the target met it. They only come+ // apart for a fault on a route the target can avoid using, such as a DNS+ // answer it need not ask for again.if reason, undelivered := faultNeverDelivered(observation); undelivered {verdict.Epistemic = Abortedverdict.Reasons = append(verdict.Reasons, reason)@@ -418,9 +318,8 @@ func epistemic(observation Observation) (Verdict, bool) {return verdict, false}- // A failed mid-run action is NOT a clean run. The credential khaos measured- // was never revoked, so every acceptance of it is correct behaviour and the- // finding this experiment exists to produce was unreachable.+ // A failed mid-run action leaves the credential un-revoked, so every+ // acceptance of it was correct and the finding was unreachable.if observation.ActFailed {verdict.Epistemic = Abortedverdict.Reasons = append(verdict.Reasons, reasonActFailed)@@ -437,15 +336,8 @@ func Judge(observation Observation, polarity Polarity) Verdict {}// A proven bypass is reported even on thin evidence, because one leaked- // request is a proof. Everything else waits for the sample floor.- //- // The three streams make three DIFFERENT claims and every one that fired is- // stated. "A credential khaos revoked at the authority was still accepted"- // is not "a credential the target had already rejected was accepted", and- // neither is "a credential khaos minted with a deliberate defect was- // accepted". Reporting one claim when a different stream carried the finding- // would be khaos describing an observation it never made, and returning on- // the first one would drop the others from a run where several are true.+ // request is a proof. Every stream that fired is stated, because the three+ // make three different claims and a run can carry several at once.if leaks := leaked(observation); len(leaks) > 0 {verdict.Epistemic = Deviatedverdict.Direction = Permitted@@ -465,15 +357,11 @@ func Judge(observation Observation, polarity Polarity) Verdict {return verdict}- // The stream that carries THIS experiment's hypothesis has to have produced- // usable decisions too. Paired() counts only the valid and invalid streams,- // so a run where every forged probe failed or timed out still cleared the- // floor above and fell through to HELD — reporting that the target refused a- // credential it was never successfully shown.- //- // This sits AFTER the leak checks on purpose: one observed acceptance of a- // credential khaos proved defective is a finding on its own, and must not be- // discarded for thin evidence.+ // Paired() counts only the valid and invalid streams, so the stream carrying+ // this experiment's own hypothesis is checked separately or a run whose+ // forged probes all failed reads as the target refusing something it was+ // never shown. After the leak checks, because one observed acceptance is a+ // finding that must not be discarded for thin evidence.if reason, thin := requiredStreamThin(observation); thin {verdict.Epistemic = ProbeErrorverdict.Warnings = append(verdict.Warnings, WarningThinEvidence)@@ -537,23 +425,9 @@ func finish(verdict.Reasons = append(verdict.Reasons, observation.HeldCaveat)}- // EVERY direction is put to the polarity, including HELD.- //- // This used to skip Held, on the assumption that a control which held is- // never a defect. That is the same mistake the design document warns about- // in the other direction -- "above all, that failing open is always a- // defect" -- hard-coded one layer BELOW the mechanism that exists to stop- // it being hard-coded. An experiment could declare Held a defect and the- // declaration was inert.- //- // The `tls.` family is where it bites. khaos presents a certificate it- // deliberately broke; a target that carries on unchanged has ACCEPTED it,- // and "nothing looks wrong" is precisely the finding. Reported as HELD with- // no defect, that run exited 0 and cleared a target that will talk to- // anything presenting a certificate.- //- // Undetermined is unaffected: no polarity lists it, so IsDefect is false- // for it either way.+ // EVERY direction is put to the declared polarity, including HELD. For a+ // certificate fault a target that carries on unchanged has ACCEPTED the+ // broken certificate, so "nothing looks wrong" is the finding.verdict.Defect = polarity.IsDefect(verdict.Direction)verdict.Reasons = append(verdict.Reasons,@@ -580,11 +454,8 @@ func leaked(observation Observation) []string {),)- // 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.- // Research 07 section 2.2 calls this `stale_accept_window`, "the real- // exposure window of a leaked key", and it is explicitly a lower bound:- // khaos stopped looking when the run ended.+ // The exposure as a number, and explicitly a lower bound: khaos+ // stopped looking when the run ended.if span := staleWindow(observation); span > 0 {reasons = append(reasons,@@ -613,32 +484,14 @@ func leaked(observation Observation) []string {return reasons}-// Leaking reports whether ANY mechanism found a bypass. It is exported because-// the ENGINE needs the answer mid-run: the idleness discriminator costs a traffic-// pause and a second measurement window, and there is nothing to diagnose on a-// target that never leaked.-//-// It has to cover every stream. Keyed on the monotonicity count alone, a-// revocation experiment's finding sat entirely in the revoked stream and the-// discriminator never ran, so the cause came back UNDIAGNOSED on a run that had-// just proved a bypass.+// Leaking reports whether ANY stream found a bypass. The engine needs it+// mid-run, because the idleness discriminator costs a traffic pause and there is+// nothing to diagnose on a target that never leaked. It must cover every stream:+// keyed on monotonicity alone it misses a finding carried by the revoked one.func Leaking(observation Observation) bool {return len(leaked(observation)) > 0}-// forgedAccepted counts acceptances of a credential khaos minted with one-// deliberate defect.-//-// There is no monotonicity test here and that is deliberate, but the reason it-// is sound differs by experiment and the shared sentence used to overstate it.-// For the ten forgery traps the oracle reads the minted token back and inspects-// the wrongness, so the credential is PROVED malformed before it is presented.-// For `identity.jwks_unreachable` the confirmed observable is the key set-// answering non-200 and nothing inspects the credential at all; its-// defectiveness comes from CorruptSignature plus the ExpectRejected baseline-// guard, which is adequate evidence but not the evidence the sentence named.-// The reason now states only what is true of both, and the per-trap confirm line-// carries the specific evidence.// staleWindow is the span from the first acceptance of the invalidated// credential to the last, across the fault window and the resumed one.func staleWindow(observation Observation) time.Duration {@@ -691,56 +544,28 @@ func leakedMonotonic(observation Observation) int {// revokedHonoured counts acceptances of a credential khaos invalidated at the// authority that were never followed by a refusal.//-// Order-sensitive, for the same reason the DENIED test is. A target with a-// correct BOUNDED cache serves the invalidated credential for exactly its cache-// lifetime and then refuses it forever, which is the defensible bounded-stale-// pattern research 07 section 3.3 lists as a PASS. Counting every acceptance in-// the window reported that as a bypass.-//-// The outage experiment only escaped it by accident: its proxy confirmation-// spends two seconds measuring both paths, which happens to be the range's cache-// lifetime, so the stale allow had lapsed before the window opened. The identity-// tier's confirmation is two local HTTP calls, so the same experiment shape-// would have reported a false finding against a correct target.+// Order-sensitive on purpose: a target with a correct BOUNDED cache serves the+// invalidated credential for its cache lifetime and then refuses it forever,+// which is a defensible design. Counting every acceptance in the window reports+// that as a bypass.func revokedHonoured(observation Observation) int {return observation.Fault.Revoked.AcceptedDespiteLapse()}// diagnose separates the two causes of a permitted credential. Both look-// identical under steady traffic; they separate completely across a pause.-//-// The test is order-sensitive for the same reason the monotonicity rule is. The-// fault window already established that the target accepts a credential it had-// rejected. The only question left is whether it STILL accepts one once traffic-// has stopped for longer than any plausible cache lifetime.+// identical under steady traffic and separate completely across a pause, so the+// question is whether the credential is STILL accepted once traffic has stopped+// for longer than any plausible cache lifetime.func diagnose(observation Observation, reasons []string) (Cause, []string) {- // An experiment that never ran the pause has nothing to say on this axis,- // and saying nothing is the correct answer.- //- // Without this guard every PERMITTED verdict in the families that do not use- // the discriminator -- `network.`, `tls.` and `dns.` -- carried "the resumed- // window produced 0 usable samples in 0s and never a refusal, so khaos saw- // nothing that could tell a cache being re-armed from one that outlasts the- // pause". Every clause of that is true of the data and the sentence as a- // whole is not: it describes a measurement khaos declined to attempt as one- // it attempted and learned nothing from. The causal axis exists to answer- // WHY a credential is still honoured, and the idleness pause is the only- // instrument that answers it.+ // An experiment that never ran the pause has nothing to say on this axis.+ // The idleness pause is the only instrument that answers it.if observation.IdleFor <= 0 {return Undiagnosed, reasons}- // Deliberately NOT gated on Resumed.Paired(). That counts only the valid and- // invalid streams, so a resumed window full of decisions about the REVOKED- // credential — the stream that actually leaked — read as no evidence at all- // and skipped the diagnosis entirely. resolveCause below decides from the- // stream that carried the finding, and says so when that stream is empty.-// A forged credential getting through is not a caching bug, so there is no- // cause to diagnose. No experiment pairs a forged stream with the idleness- // pause today, and this guard is what stops the next one that does from- // being diagnosed off the INVALID stream's resumed window, which is a stream- // that never leaked.+ // cause to diagnose — and without this guard it would be diagnosed off the+ // invalid stream's resumed window, which never leaked.if forgedAccepted(observation) > 0 &&revokedHonoured(observation) == 0 &&leakedMonotonic(observation) == 0 {@@ -752,11 +577,6 @@ func diagnose(observation Observation, reasons []string) (Cause, []string) {// wrong one would report the pause's effect on something that never leaked.//// It is read with the same order-sensitive test the fault window uses, and- // for the same reason. The question is whether the credential is STILL being- // honoured once the pause has had its chance, so a window that starts- // accepted and settles into refusal is a cache that lapsed, however long it- // 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,@@ -775,19 +595,9 @@ func diagnose(observation Observation, reasons []string) (Cause, []string) {}// resolveCause reads one resumed stream and refuses to diagnose from a window-// that contains no evidence.-//-// Both halves are needed, and the second one was missing. `Resumed.Paired()`-// ignores the revoked stream entirely, and AcceptedSinceLastRefusal returns zero-// for a window that is ALL timeouts, because a timeout is neither an acceptance-// nor a refusal. So a run whose resumed probes could not reach the target at all-// fell through to TTL-EXTENSION and asserted that "pausing traffic restored-// enforcement" — of a target that had stopped answering.-//-// That is reachable: `identity.idp_outage` severs the upstream with a proxy-// 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.+// with no evidence in it. A window of pure timeouts contains neither an+// acceptance nor a refusal, which is reachable whenever the fault wedges the+// path, and must not read as enforcement having returned.func resolveCause(resumed probe.Stream,steady, idle time.Duration,@@ -806,10 +616,9 @@ func resolveCause(resumed.Countable(), idle))}- // The soundness condition for the causal claim. A fixed, never-re-armed cache- // whose lifetime sits between the fault window and the pause produces exactly- // this observation, so without a steady-traffic window at least as long as- // the pause khaos cannot separate re-arming from ordinary expiry.+ // The soundness condition for the causal claim: a fixed, never-re-armed+ // cache whose lifetime sits between the fault window and the pause produces+ // this same observation.if steady < idle {return LapsedOnPause, append(reasons,@@ -842,23 +651,17 @@ func baselineUnmet(}if !baseline.Valid.Any(probe.Accepted) {- // The identity tier gets its own wording, because the generic sentence is- // misleading there in the most likely failure case. A target whose key+ // Its own wording for a khaos-minted credential: a target whose key// cache never expires is serving perfectly well and simply does not know- // khaos's keys, which khaos regenerates every run: measured against the- // range's forever-cache gateway, a second consecutive run could not- // establish a baseline and the generic reason said the target was not- // serving.+ // khaos's keys, which are regenerated every run.if minted {return reasonNoServiceMinted, true}return reasonNoService, true}- // An experiment that revokes a credential mid-run needs the target to have- // 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.+ // A mid-run revocation needs the target to have been HONOURING the+ // credential first, or there is nothing to take away.if baseline.Revoked.Countable() > 0 &&!baseline.Revoked.Any(probe.Accepted) {return reasonNothingToRevoke, true@@ -868,13 +671,9 @@ func baselineUnmet(}// checkNotImplemented reports that the target never performed the check this-// experiment probes, for an experiment that declared the check optional.-//-// This is the measured half of the UNSUPPORTED verdict. khaos is not told the-// target's language; it counts what the target fetched from the authority, so-// "it never asked about revocation" is an observation. A target that DID ask-// and then used the certificate anyway falls through to the ordinary-// directional reading and is reported as the defect it is.+// experiment probes, for an experiment that declared the check optional. It+// counts what the target fetched rather than assuming its language, so a target+// that DID ask and then proceeded anyway falls through to the ordinary reading.func checkNotImplemented(observation Observation) (string, bool) {if observation.Unsupportable == "" || observation.Consulted > 0 {return "", false@@ -888,13 +687,8 @@ func checkNotImplemented(observation Observation) (string, bool) {}// faultNeverDelivered reports a fault that was armed and confirmed and that the-// target never met.-//-// It is ABORTED rather than HELD, and that distinction is the whole value of it.-// HELD would say the target withstood the fault; aborted says khaos could not-// put the fault in front of it. The second is true and the first is a clean-// survival khaos never earned, which is the single failure mode this project-// treats as a blocker every time it appears.+// target never met. Aborted rather than HELD: HELD would say the target+// withstood the fault, which is a survival khaos never earned.func faultNeverDelivered(observation Observation) (string, bool) {if observation.DeliveredWhat == "" || observation.Delivered > 0 {return "", false@@ -904,41 +698,19 @@ func faultNeverDelivered(observation Observation) (string, bool) {}// cacheNotObserved reports that the target holds no cached answer, for an-// experiment whose whole subject is how long a cached answer is honoured.+// experiment whose subject is how long a cached answer is honoured.//-// The threshold is one query per PAIRED BASELINE SAMPLE, which is deliberately-// generous toward "no cache": a target that caches for the TTL khaos serves-// asks once for the entire baseline, so the two populations are an order of-// magnitude apart rather than adjacent. A target somewhere in between -- a-// short cache, a pool that re-resolves occasionally -- falls through to the-// ordinary reading, which is correct, because the experiment can then observe-// the difference the TTL makes.+// Measured against the LIFETIME khaos served, not against how many requests+// khaos made. A target's DNS lookups do not scale with khaos's traffic — a+// target that caches its own decisions calls its dependency less often than+// khaos probes it — so any denominator built from khaos's request count+// measures the wrong cache. The baseline runs for seconds against a ten-minute+// TTL, so a target honouring it resolves once for the whole window.func cacheNotObserved(observation Observation) (string, bool) {if observation.CacheRequired == "" {return "", false}- // Measured against the TTL khaos itself served, not against how many- // requests khaos made.- //- // khaos cannot scale this by its own traffic, because the target's DNS- // lookups do not scale with it: the range's gateway caches its DECISIONS- // for two seconds, so it calls its dependency fewer times than khaos probes- // it, and a DNS lookup happens only when it does call. Any denominator- // built from khaos's request count therefore measures the target's decision- // cache rather than its DNS cache.- //- // What khaos does control is the lifetime it served. The baseline runs for- // seconds against an honest TTL of HonestTTL, so a target honouring that- // TTL resolves ONCE for the whole window. Go fires A and AAAA in parallel- // per name, so one lookup is queriesPerLookup queries; more than that means- // it resolved repeatedly inside a window orders of magnitude shorter than- // the lifetime it was given, which is the definition of not holding the- // answer.- //- // The margin is deliberately generous in the direction of NOT making this- // claim: at twice one lookup, the target has to have resolved at least- // twice before khaos says it caches nothing.if observation.Consulted < queriesPerLookup*cacheLookupGrace {return "", false}@@ -964,17 +736,11 @@ func endpointNeverConsulted(observation Observation) (string, bool) {}// forgedBaselineUnmet applies the guard the experiment DECLARED for its forged-// stream. The two expectations point in opposite directions and both are-// liveness guards rather than findings.-//-// ExpectAccepted catches the single most likely misconfiguration in the whole-// family: a target that is not pointed at khaos's identity provider at all. It-// refuses every credential khaos mints, for reasons that have nothing to do with-// any trap, and without this guard a run against it reports a clean HELD for-// every one of the forgery experiments.-//-// 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.+// stream. Both expectations are liveness guards and they point in opposite+// directions: ExpectAccepted catches a target not pointed at khaos's provider at+// all, which refuses everything khaos mints for reasons unrelated to any trap,+// and ExpectRejected catches a target that was not checking the thing the fault+// is about to break.func forgedBaselineUnmet(baseline probe.Window,expect probe.Expectation,@@ -1035,14 +801,9 @@ func unanswered(window probe.Window) (int, int) {return down, total}-// recoveryOf requires a run of consecutive healthy pairs, because declaring a-// state transition on a single lucky sample is how a flaky recovery reads as a-// clean one.-//-// An empty window is UNOBSERVED rather than recovered. Returning true there-// meant a run that collected no recovery evidence at all — an interrupted run,-// a target that stopped answering, a recovery window too short to pair —-// reported that the target came back, and exited 0.+// recoveryOf requires a run of consecutive healthy pairs, because a state+// transition declared on one lucky sample is how a flaky recovery reads as a+// clean one. An empty window is UNOBSERVED, never recovered.func recoveryOf(recovery probe.Window) Recovery {if recovery.Paired() == 0 {return Unobserveddiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.goindex 51256b2d..16d15c32 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/jwk.go@@ -23,11 +23,8 @@ const (var ErrNoSuchKey = errors.New("that key is not in the published JWK Set")-// JWK is the published form of one key: the thumbprint-derived `kid`, the-// algorithm it is bound to, and the public material. The `alg` member is present-// deliberately, because RFC 8725 rule 2 says a verifier MUST cross-check it-// against the token header, and a provider that omits it denies the verifier the-// means to comply.+// JWK is the published form of one key. The `alg` member is deliberate:+// RFC 8725 rule 2 says a verifier MUST cross-check it against the header.type JWK struct {Kid string `json:"kid"`Kty string `json:"kty"`@@ -88,9 +85,8 @@ func joinKids(kids []string) string {return out}-// PublicJWK is the published form. It carries the full member set a verifier-// needs, which is a superset of the required members the thumbprint is computed-// over, so the two forms are built separately on purpose.+// PublicJWK is the published form. It is a superset of the members the+// thumbprint covers, so the two forms are built separately.func (k *Key) PublicJWK() JWK {out := JWK{Kid: k.ID,@@ -116,17 +112,10 @@ func (k *Key) PublicJWK() JWK {return out}-// RSAPublicKey rebuilds a verifiable key from a published JWK, and refuses-// 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())`-// is documented as undefined on overflow, which measured as `"e":"AQAAAAAAAAAB"`-// (2^64 + 1) silently becoming e = 1 — the one exponent that makes the signature-// and the encoded message the same bytes.+// RSAPublicKey rebuilds a verifiable key from a published JWK. Both guards are+// load-bearing: decodeBigInt("") yields zero with a nil error, and+// big.Int.Int64 is undefined on overflow, where 2^64 + 1 truncates to e = 1,+// the one exponent that makes the signature and the encoded message identical.func (j JWK) RSAPublicKey() (*rsa.PublicKey, error) {if j.N == "" || j.E == "" {return nil, fmt.Errorf(errIncompleteJWK, ErrNoSuchKey, j.Kid, "n and e")@@ -151,10 +140,6 @@ func (j JWK) RSAPublicKey() (*rsa.PublicKey, error) {}// ECPublicKey rebuilds an EC key, and refuses a curve khaos does not serve.-//-// It used to ignore `crv` entirely and always build a P-256 key, so a P-224 JWK-// came back labelled P-256 with a zero-padded coordinate, which is a different-// key under a different thumbprint.func (j JWK) ECPublicKey() (*ecdsa.PublicKey, error) {if j.Crv != curveP256 {return nil, fmt.Errorf(@@ -211,7 +196,5 @@ func bigFromBytes(raw []byte) *big.Int {return new(big.Int).SetBytes(raw)}-// UseSignature is RFC 7517's `use` value for a signing key. It is exported so-// the range's verifier can check it against the same constant khaos publishes,-// rather than against a string literal that could drift from it silently.+// UseSignature is RFC 7517's `use` value for a signing key.const UseSignature = useSignaturediff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.goindex 07b6263b..d8a0b97a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/key.go@@ -18,9 +18,7 @@ import ("math/big")-// Algorithm is the JWS `alg` header value. khaos needs to mint tokens under-// algorithms a correct provider would refuse to use at all, so this is the set-// khaos can SIGN with rather than a set it endorses.+// Algorithm is a JWS `alg` khaos can SIGN with, not one it endorses.type Algorithm stringconst (@@ -28,9 +26,6 @@ const (ES256 Algorithm = "ES256"HS256 Algorithm = "HS256"- // None is RFC 7515's "No digital signature or MAC performed". It exists here- // because a verifier that routes on it is trap T1, and khaos cannot test for- // that without being willing to emit it.None Algorithm = "none")@@ -42,31 +37,19 @@ const (useSignature = "sig"- // The modulus size khaos signs its honest tokens with. 2048 is what a real- // provider uses and it is comfortably above the floor crypto/rsa enforces.strongBits = 2048- // Deliberately below that floor. Measured on go1.26.5: crypto/rsa refuses a- // key this size at GenerateKey, at SignPKCS1v15 AND at VerifyPKCS1v15, all- // three through checkKeySize, so a token signed under it cannot be produced- // or checked by the standard library at all. That is the whole point of the- // weak-key probe, and it is why khaos carries its own PKCS#1 v1.5 path below.+ // Below crypto/rsa's floor, which refuses a key this size at GenerateKey,+ // at SignPKCS1v15 and at VerifyPKCS1v15 alike, hence the raw path below.weakBits = 512- // Each prime is half the modulus. Assembling the key by hand is what lets- // khaos hold one crypto/rsa will not generate.weakPrimeBits = weakBits / 2- // crypto/rsa's own floor, read from the source rather than remembered:- // checkKeySize returns nil at or above this and an error below it unless the- // rsa1024min GODEBUG is set. khaos never sets that GODEBUG, because doing so- // to enable one probe would weaken every other thing khaos does with RSA.+ // crypto/rsa's floor, waived only by the rsa1024min GODEBUG khaos never sets.libraryFloorBits = 1024primeAttempts = 64- // ES256 signatures are the fixed-width concatenation of r and s, each padded- // to the curve's coordinate size. RFC 7518 section 3.4.p256CoordinateBytes = 32errNoPrime = "khaos could not find a %d-bit prime for its deliberately weak signing key after %d attempts"@@ -85,10 +68,7 @@ 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-// rather than from a counter khaos increments: two providers holding the same-// key agree on its name, and a `kid` cannot be reused for different bytes.+// Key is one signing key, whose RFC 7638 thumbprint is its `kid`.type Key struct {ID stringAlg Algorithm@@ -97,16 +77,11 @@ type Key struct {ecKey *ecdsa.PrivateKey}-// NewRSAKey mints a key a real provider would use.func NewRSAKey() (*Key, error) {return newRSAKey(strongBits)}-// NewWeakRSAKey mints a key below the size crypto/rsa will accept, by assembling-// the struct from primes khaos finds itself. Nothing in crypto/rsa validates a-// PrivateKey on construction, so the value is well-formed and usable right up to-// the moment a crypto/rsa function is called with it, which is exactly the-// position a verifier that reimplements RSA puts itself in.+// Built by hand: crypto/rsa validates no PrivateKey on construction.func NewWeakRSAKey() (*Key, error) {key, err := weakRSAPrivateKey()if err != nil {@@ -136,9 +111,6 @@ func keyFromRSA(key *rsa.PrivateKey) (*Key, error) {return out, nil}-// NewECKey mints khaos's ES256 key. The curve is P-256 because ES256 is defined-// over it, and the surrounding code derives its widths from the curve rather-// than from that fact, so adding ES384 later is a constructor and not a hunt.func NewECKey() (*Key, error) {key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)if err != nil {@@ -157,17 +129,10 @@ func NewECKey() (*Key, error) {return out, nil}-// Weak reports whether this key is below the size crypto/rsa accepts. It is-// derived from the modulus rather than remembered from construction, so a key-// cannot claim to be strong while carrying weak material.func (k *Key) Weak() bool {return k.rsaKey != nil && k.rsaKey.N.BitLen() < libraryFloorBits}-// PublicDER is the SPKI encoding of the public key. It is what the algorithm-// confusion probe uses as its HMAC secret, because an RSA public key loaded from-// a PEM file is these bytes and a verifier that hands them to an HMAC function-// is trap T2.func (k *Key) PublicDER() ([]byte, error) {return x509.MarshalPKIXPublicKey(k.public())}@@ -179,10 +144,6 @@ func (k *Key) public() crypto.PublicKey {return &k.ecKey.PublicKey}-// Sign produces the JWS signature over the signing input. It refuses an-// algorithm the key cannot carry rather than silently producing a signature-// nothing can check, because a probe that fails for the wrong reason reads-// exactly like a target that refused it.func (k *Key) Sign(alg Algorithm, signingInput []byte) ([]byte, error) {switch alg {case RS256:@@ -205,10 +166,6 @@ func (k *Key) Sign(alg Algorithm, signingInput []byte) ([]byte, error) {}}-// signRSA uses the standard library wherever the standard library will accept-// the key, and khaos's own PKCS#1 v1.5 path only where it will not. The two are-// pinned to agree byte for byte at a legal key size, so the weak-key path is-// exercised against a known-good reference rather than trusted on its own.func (k *Key) signRSA(signingInput []byte) ([]byte, error) {digest := sha256.Sum256(signingInput)@@ -234,10 +191,7 @@ func (k *Key) signEC(signingInput []byte) ([]byte, error) {return out, nil}-// Thumbprint is the RFC 7638 JWK thumbprint: the required members only, in-// lexicographic order, with no whitespace, SHA-256, base64url with no padding.-// It is implemented from the specification text and pinned by the worked example-// in RFC 7638 section 3.1.+// Thumbprint is the RFC 7638 JWK thumbprint, which khaos uses as the `kid`.func (k *Key) Thumbprint() (string, error) {canonical, err := k.canonicalJWK()if err != nil {@@ -259,10 +213,8 @@ func (k *Key) canonicalJWK() ([]byte, error) {return nil, fmt.Errorf(errBadAlg, ErrUnsupportedAlgorithm, k.Alg)}-// canonicalRSAJWK is the required-members-only RSA form. The member order is-// e, kty, n, which is lexicographic, and it is written literally rather than-// marshalled, because encoding/json orders struct fields by declaration and a-// field reorder would silently change every kid khaos derives.+// Written literally rather than marshalled, because encoding/json orders+// fields by declaration and a reorder would change every kid khaos derives.func canonicalRSAJWK(pub *rsa.PublicKey) []byte {return []byte(fmt.Sprintf(`{"e":%q,"kty":%q,"n":%q}`,@@ -272,16 +224,11 @@ func canonicalRSAJWK(pub *rsa.PublicKey) []byte {))}-// exponentBytes is the base64url-ready form of the public exponent: big-endian,-// with no leading zero octets. RFC 7518 section 6.3.1.2 calls for the-// "base64urlUInt-encoded value", and a leading zero would change the thumbprint-// for the same key.+// Big-endian with no leading zero octets, which would change the thumbprint.func exponentBytes(e int) []byte {return new(big.Int).SetInt64(int64(e)).Bytes()}-// canonicalECJWK is the required-members-only EC form, in the lexicographic-// order crv, kty, x, y.func canonicalECJWK(pub *ecdsa.PublicKey) []byte {name, size := curveShape(pub.Curve)x, y := coordinates(pub, size)@@ -295,14 +242,8 @@ func canonicalECJWK(pub *ecdsa.PublicKey) []byte {))}-// curveShape is the curve's JWK name and its coordinate width, DERIVED from the-// curve rather than hardcoded.-//-// Hardcoding P-256 in three places made a larger curve PANIC inside the `jwks`-// HTTP handler — math/big's FillBytes refuses a buffer too small for the value —-// and made a smaller one serialize as a zero-padded 28-byte coordinate labelled-// P-256, which is a different key under a different thumbprint. Neither was-// reachable through NewECKey, which is why neither was noticed.+// Derived from the curve rather than hardcoded: FillBytes panics on a buffer+// too small, and a padded short coordinate is a different key.func curveShape(curve elliptic.Curve) (string, int) {switch curve {case elliptic.P384():@@ -314,9 +255,6 @@ func curveShape(curve elliptic.Curve) (string, int) {}}-// coordinates is the fixed-width big-endian pair RFC 7518 section 6.2.1.2 calls-// for. The width comes from the curve, so a short coordinate is padded and a-// long one cannot overflow the buffer.func coordinates(pub *ecdsa.PublicKey, size int) ([]byte, []byte) {x := make([]byte, size)y := make([]byte, size)@@ -335,9 +273,6 @@ func b64(raw []byte) string {return base64.RawURLEncoding.EncodeToString(raw)}-// weakRSAPrivateKey assembles a key crypto/rsa will not generate. It is built-// the long way round rather than with GenerateKey because GenerateKey enforces-// the same floor as the signing and verifying paths.func weakRSAPrivateKey() (*rsa.PrivateKey, error) {exponent := big.NewInt(defaultExponent)@@ -361,9 +296,6 @@ func weakRSAPrivateKey() (*rsa.PrivateKey, error) {continue}- // Carmichael's totient, which is what PKCS#1 actually requires. Using- // Euler's would also work but produces a larger private exponent for no- // benefit.pMinus := new(big.Int).Sub(p, one)qMinus := new(big.Int).Sub(q, one)totient := new(@@ -393,22 +325,14 @@ const defaultExponent = 65537var one = big.NewInt(1)-// sha256DigestInfo is the DER-encoded DigestInfo prefix for SHA-256, from-// RFC 8017 section 9.2 note 1. PKCS#1 v1.5 signs this prefix followed by the-// digest, so the value is fixed and not computed.+// RFC 8017's DER DigestInfo prefix for SHA-256: fixed, not computed.var sha256DigestInfo = []byte{0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,}-// signPKCS1v15Raw is RFC 8017's RSASSA-PKCS1-v1_5 over a modulus crypto/rsa-// refuses to touch. It exists for exactly one probe and it is pinned against-// rsa.SignPKCS1v15 at a legal key size, so the arithmetic is verified against-// the standard library rather than asserted.-//-// There is no constant-time concern here: the key is a throwaway khaos generated-// to be weak on purpose, published in khaos's own JWK Set, and discarded with the-// run.+// RFC 8017's RSASSA-PKCS1-v1_5 over a modulus crypto/rsa refuses. No+// constant-time concern: the key is a throwaway, weak on purpose.func signPKCS1v15Raw(key *rsa.PrivateKey, digest []byte) ([]byte, error) {size := (key.N.BitLen() + 7) / 8framed := len(sha256DigestInfo) + len(digest)@@ -437,21 +361,9 @@ func signPKCS1v15Raw(key *rsa.PrivateKey, digest []byte) ([]byte, error) {return out, nil}-// verifyPKCS1v15Raw is the mirror, and it is here rather than in the range-// fixture because the confirmation oracle needs it: khaos has to be able to-// prove the token it just minted really does verify under the weak key it-// published, or "the target accepted it" says nothing about what khaos sent.func verifyPKCS1v15Raw(pub *rsa.PublicKey, digest, signature []byte) bool {- // The exponent is validated because this function is EXPORTED with a comment- // inviting reuse, and a caller who built the key from an attacker-supplied- // JWK can hand it anything.- //- // Measured: with e = 1 the modular exponentiation is the identity, so the- // signature IS the encoded message and khaos accepted a forgery that- // rsa.VerifyPKCS1v15 refused. The standard library's FIPS path rejects e < 2- // and even exponents; this path rejected neither. An `"e":"AQAAAAAAAAAB"`- // (2^64+1) also truncated to 1 through big.Int.Int64, whose behaviour is- // documented as undefined on overflow.+ // Load-bearing: with e = 1 the exponentiation is the identity, so the+ // signature IS the encoded message. crypto/rsa's FIPS path rejects e < 2.if pub.N == nil || pub.E < 3 || pub.E%2 == 0 {return false}@@ -499,23 +411,12 @@ func verifyPKCS1v15Raw(pub *rsa.PublicKey, digest, signature []byte) bool {return true}-// VerifyPKCS1v15Raw is khaos's own PKCS#1 v1.5 verification, exported for the-// range's reference verifier. The fixture needs it to express the one bug Go's-// standard library makes unreachable: crypto/rsa enforces a 1024-bit floor, so a-// verifier that accepts an undersized key has to have reimplemented RSA, which-// is what most libraries in other ecosystems have done.-//-// It is pinned against rsa.SignPKCS1v15 at a legal key size by this package's-// own tests, in both directions.+// VerifyPKCS1v15Raw verifies under a modulus crypto/rsa refuses to touch.func VerifyPKCS1v15Raw(pub *rsa.PublicKey, digest, signature []byte) bool {return verifyPKCS1v15Raw(pub, digest, signature)}-// SPKIPEMBytes is the serialization a verifier is overwhelmingly holding when it-// was handed "the issuer's public key": a PEM file read off disk. It is exported-// because the algorithm-confusion bug is only reachable when the forged MAC and-// the verifier's secret are the SAME bytes, so khaos and the fixture have to-// agree on which bytes those are.+// The bytes a verifier handed "the issuer's public key" is usually holding.func SPKIPEMBytes(pub *rsa.PublicKey) ([]byte, error) {der, err := x509.MarshalPKIXPublicKey(pub)if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.goindex 44411405..3f2c6cf9 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go@@ -15,22 +15,17 @@ import ("time")-// KeyForm is how a verifier loaded the issuer's public key, which decides what-// bytes the algorithm-confusion attack has to use as its HMAC secret. Research 07-// is explicit that this varies by target and that khaos should be able to try-// each, because the same bug is unreachable under the wrong serialization.+// KeyForm is how a verifier loaded the key, and so what bytes the forged MAC+// has to be keyed on.type KeyForm stringconst (- // SPKIPEM is the default because it is overwhelmingly how an RSA public key- // reaches a verifier: a `.pem` file read off disk and passed through as a- // string.+ // SPKIPEM is the default: a `.pem` file read off disk.SPKIPEM KeyForm = "spki-pem"SPKIDER KeyForm = "spki-der"PKCS1PEM KeyForm = "pkcs1-pem"- // Modulus is the raw big-endian modulus, which is what a verifier that- // reconstructed the key from the JWK's `n` member is holding.+ // Modulus is what a verifier that rebuilt the key from `n` is holding.Modulus KeyForm = "modulus")@@ -62,32 +57,15 @@ func KeyForms() []string {}}-// grantRequest is what a token is minted for. The provider fills it from its own-// configuration so a caller never chooses the issuer or audience: a probe that-// could pick its own `aud` would make the wrong-audience trap meaningless.type grantRequest struct {subject stringlifetime time.Duration}-// mintToken produces one credential under the currently armed trap. Every branch-// corrupts EXACTLY ONE property and leaves the rest correct, which is what makes-// a 2xx isolate a single missing check rather than report that something,-// somewhere, is wrong.-//-// `typ` is the property that keeps each trap isolated: every token khaos mints-// carries `at+jwt`, including the forged ones, so a verifier that implements-// RFC 8725 section 3.11's explicit typing refuses each forgery for its OWN-// defect rather than for its type. Setting `typ: JWT` on the three header traps,-// which is what a careless forger would do, would get them refused on the type-// instead, and a token rejected for the wrong reason reads exactly like a target-// that caught the trap.-//-// An earlier version of this comment claimed that refusal had been OBSERVED. It-// had not: the explicit-typing check did not exist anywhere in the repository at-// the time, so the property this defends was inert against khaos's own fixture-// and the comment described a measurement nobody took. The check is now-// implemented in internal/verifier and `TestEveryTrapIsCaught...` exercises it.+// mintToken produces one credential under the armed trap. Every branch+// corrupts EXACTLY ONE property, and every token carries `typ: at+jwt` so a+// verifier implementing RFC 8725's explicit typing refuses each forgery for+// its OWN defect rather than for its type.func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {p.mu.RLock()defer p.mu.RUnlock()@@ -105,10 +83,6 @@ 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)@@ -121,17 +95,13 @@ func (p *Provider) mintToken(trap Trap, request grantRequest) (string, error) {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.+ // The endpoint traps act on the provider, so honest is correct here.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.+// mintHeaderTrap 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,@@ -169,13 +139,10 @@ func (p *Provider) mintHeaderTrap(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,@@ -185,9 +152,6 @@ func (p *Provider) mintClaimTrap() (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 - lifetime))claims.NotBefore = unix(now.Add(-trap.Delay - lifetime))claims.Expires = unix(now.Add(-trap.Delay))@@ -203,10 +167,7 @@ func (p *Provider) mintClaimTrap(return p.serialize(header, claims, nil, nil)case ClaimForeignIssuer:- // Signed by a key khaos DOES publish, in the same JWK Set. That is the- // multi-tenant shape, and the teaching point is that the key set is not- // the trust boundary: the signature verifies and only the `iss` check- // can refuse it.+ // Signed by a key khaos DOES publish, so only `iss` can refuse it.if p.foreign == nil {return "", fmt.Errorf(errNoKey, ErrNoSigningKey, "second issuer")}@@ -215,13 +176,10 @@ func (p *Provider) mintClaimTrap(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,@@ -256,13 +214,11 @@ func (p *Provider) mintSignatureTrap(return p.serialize(header, claims, p.weak, nil)default:- // Unreachable: mintToken routes only the signature group here.return p.serialize(header, claims, nil, nil)}}-// serialize marshals, signs and assembles. A nil key means the provider's-// current signing key; a nil signer means the key's own algorithm.+// A nil key means the current signing key; a nil signer means the key's alg.func (p *Provider) serialize(header Header,claims Claims,@@ -338,10 +294,7 @@ func (p *Provider) produceSignature(return key.Sign(alg, input)}-// publicKeyBytes is the bytes a verifier is holding for this key, under one of-// the four serializations research 07 says to try. It is the HMAC secret for the-// algorithm-confusion probe, and it is the whole reason that probe needs a-// parameter: the bug is unreachable if khaos guesses the wrong form.+// The HMAC secret for the confusion probe, unreachable under the wrong form.func publicKeyBytes(key *Key, form KeyForm) ([]byte, error) {der, err := key.PublicDER()if err != nil {@@ -378,10 +331,7 @@ func publicKeyBytes(key *Key, form KeyForm) ([]byte, error) {}}-// corruptSignature replaces a token's signature with bytes no key produced. It-// is not a trap: it is what the JWKS-unreachable experiment presents, because-// that trap asks whether a verifier that cannot fetch keys checks the signature-// at all, and the token has to be one a reachable verifier would refuse.+// CorruptSignature is not a trap: the JWKS-unreachable experiment needs it.func CorruptSignature(raw string) (string, error) {token, err := Parse(raw)if err != nil {@@ -392,10 +342,7 @@ func CorruptSignature(raw string) (string, error) {return "", fmt.Errorf(errNothingToCorrupt, ErrNotAJWS)}- // Flipping a bit of the real signature, rather than substituting random- // bytes, keeps the length and the algorithm exactly right. The only thing- // wrong with the token is that the signature does not verify, which is what- // makes a 2xx mean the verifier never checked it.+ // A bit flip keeps the length and algorithm right; only the MAC is wrong.forged := make([]byte, len(token.Signature))copy(forged, token.Signature)forged[0] ^= 0xff@@ -403,8 +350,6 @@ func CorruptSignature(raw string) (string, error) {return assemble(token.HeaderJSON, token.ClaimsJSON, forged), nil}-// mintSignedBy produces a correct token under a named key rather than under the-// provider's current signing key.func (p *Provider) mintSignedBy(key *Key) (string, error) {p.mu.RLock()defer p.mu.RUnlock()@@ -425,10 +370,7 @@ func (p *Provider) mintSignedBy(key *Key) (string, error) {return p.serialize(header, claims, key, nil)}-// reheader and reclaim mint a correctly signed token with one header or claim-// rewritten. They are the seam the range verifier's tests need to reach the-// checks khaos's own published material can never trip, and they sign properly-// so the token is refused by the check under test rather than by the signature.+// One header or claim rewritten, correctly signed, so only it can be refused.func (p *Provider) reheader(edit func(*Header)) string {return p.remint(edit, nil)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.goindex 085caa0b..c9709f4b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go@@ -21,10 +21,7 @@ const (observeTimeout = 5 * time.SecondobserveBudget = 4- // Slack on a measured hold, for the same reason the fault proxy carries it:- // the threshold is a lower bound with no tolerance otherwise, and on a host- // that also serves real traffic CPU contention routinely shaves a few- // percent off a sleep.+ // Slack: contention routinely shaves a few percent off a measured sleep.slackNumerator = 9slackDenominator = 10@@ -53,15 +50,8 @@ const (errHonestToken = "%w: khaos's own provider cannot mint an honest token (%v), so nothing it mints under a trap can be compared with one")-// Observe confirms the armed trap through the provider's OWN public surface and-// against a control, never by reading the flag that was set.-//-// The discipline is the fault proxy's, and it was expensive to learn: a-// confirmation that can only succeed is not an oracle. Gutting the proxy's-// equivalent to `return true` left every package and the Docker gate green, and-// 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.+// Observe confirms the armed trap through the provider's OWN public surface+// and against a control, never by reading the flag that was set.func (p *Provider) Observe(ctx context.Context,expected Kind,@@ -95,8 +85,7 @@ func (p *Provider) Observe(}// observeForgery mints on BOTH paths and requires them to differ. The honest-// token is the control: if khaos's own provider cannot produce a correct token,-// nothing it produces under a trap can be attributed to the trap.+// token is the control: khaos has to be able to mint a correct one.func (p *Provider) observeForgery(trap Trap) (string, bool, error) {honest, err := p.mintHonestForControl()if err != nil {@@ -108,10 +97,6 @@ func (p *Provider) observeForgery(trap Trap) (string, bool, error) {return "", false, err}- // 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)@@ -124,18 +109,10 @@ func (p *Provider) observeForgery(trap Trap) (string, bool, error) {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,@@ -152,10 +129,6 @@ func (p *Provider) observeHeader(}case AlgConfusion:- // Both halves. The header has to say HS256, and the MAC has to actually- // verify under the bytes a verifier would be holding, or khaos is- // sending a token no target could accept and an acceptance would mean- // something else entirely.if forged.Header.Alg != string(HS256) {return "", false, nil}@@ -182,24 +155,18 @@ func (p *Provider) observeHeader(}default:- // Unreachable: observeForgery routes only the header group here.+ // Kinds from the other groups reach their own observer.}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.+// observeClaims requires the signature to still VERIFY: a claim trap whose+// token also failed that check would be confirmed by the wrong evidence.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}@@ -242,9 +209,6 @@ func (p *Provider) observeClaims(}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 forged.Claims.Issuer != honest.Claims.Issuer &&forged.Claims.Issuer != "" {return sprintf(@@ -255,13 +219,12 @@ func (p *Provider) observeClaims(}default:- // Unreachable: observeForgery routes only the claim group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// observeSignature confirms the traps that corrupt the signature itself.func (p *Provider) observeSignature(trap Trap,honest, forged Token,@@ -288,22 +251,8 @@ func (p *Provider) observeSignature(}case SignatureWeakKey:- // Three assertions, and none of them is redundant. The modulus has to be- // below the library floor, khaos's own arithmetic has to ACCEPT the- // signature, or khaos is sending an unverifiable token and an acceptance- // means something else, and the standard library has to REFUSE it.- //- // That last one looks implied by the first and is not: the floor is a- // GODEBUG. Under `rsa1024min=0` crypto/rsa verifies below it, so khaos's- // 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.- //- // 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".+ // The library REFUSING this is not implied by the bit length: the floor+ // is a GODEBUG, so under `rsa1024min=0` crypto/rsa verifies below it.key, err := p.PublishedSet().Lookup(forged.Header.Kid)if err != nil {return "", false, nil //nolint:nilerr // not confirmed, not an error@@ -328,19 +277,14 @@ func (p *Provider) observeSignature(}default:- // Unreachable: observeForgery routes only the signature group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// mintHonestForControl and mintTrappedForControl mint WITHOUT counting, because-// the mint counter is a measurement and khaos's own confirmation must not move-// the thing it is confirming.-//-// Both are needed. An earlier version had only the honest one and then called-// the counting TrappedToken on the next line, so the comment on this function-// described a property the function beside it broke.+// These mint WITHOUT counting, because the mint counter is a measurement and+// khaos's own confirmation must not move the thing it is confirming.func (p *Provider) mintHonestForControl() (Token, error) {return p.parseMint(Trap{})}@@ -360,9 +304,6 @@ func (p *Provider) parseMint(trap Trap) (Token, error) {return Parse(raw)}-// confusionSecret reads the TRAP's key form, and so does mintToken. They used to-// read two different fields that Arm copied one into the other, which agreed-// only by that copy and which Disarm never cleared.func (p *Provider) confusionSecret(form KeyForm) ([]byte, error) {p.mu.RLock()signing := p.signing@@ -371,11 +312,8 @@ func (p *Provider) confusionSecret(form KeyForm) ([]byte, error) {return publicKeyBytes(signing, form)}-// observeEndpoint confirms the traps that change what the provider SERVES rather-// than what it mints. Every one of them is measured over the provider's own HTTP-// 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.+// observeEndpoint confirms what the provider SERVES. The health route is the+// control: it is never faulted, so an unhealthy one means khaos is broken.func (p *Provider) observeEndpoint(ctx context.Context,trap Trap,@@ -413,17 +351,10 @@ func (p *Provider) observeEndpoint(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.Clientroot string@@ -431,8 +362,6 @@ type probeAt struct {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,@@ -455,16 +384,6 @@ func (p *Provider) observeKeySet(if err != nil {return "", false, err}- // `retired != p.SigningKid()` used to be a third conjunct here and it was- // INERT: it is implied by the other two, because `!Has(retired)` and- // `Has(SigningKid)` cannot both hold when the two are the same kid.- //- // Worse, it ALIBIED the live one. Measured: with it present, replacing- // `!set.Has(retired)` with `true` left both the positive and the inert- // case green and the whole suite passing, because the implied conjunct- // was carrying the negative control on its own. Withdrawing the retired- // key is the entire claim this branch makes, so that assertion has to be- // the one the control exercises.if !set.Has(retired) && set.Has(p.SigningKid()) {return sprintf(observedRollover, retired, p.SigningKid()), true, nil}@@ -478,19 +397,11 @@ func (p *Provider) observeKeySet(if err != nil {return "", false, err}+ // An unchanged kid is no rotation at all, not a confirmed one.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- // negative control: an inert arm never rotates, so retired and signing- // are the same kid.- //- // A fourth, `minted.Header.Kid == p.SigningKid()`, used to follow and was- // unconditionally true: mintToken's default branch always stamps the- // current signing kid and KeyRotation is not a forgery trap. It is gone- // rather than kept for symmetry, because an assertion that cannot fail- // reads in a review as evidence and is not.minted, err := p.mintTrappedForControl()if err != nil {return "", false, err@@ -504,15 +415,13 @@ func (p *Provider) observeKeySet(), true, nildefault:- // Unreachable: observeEndpoint routes only the key-set group here.+ // Kinds from the other groups reach their own observer.}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"+// observeIntrospection needs a control per trap: "inactive" and "no answer"// are also what a provider khaos had broken by accident would say.func (p *Provider) observeIntrospection(ctx context.Context,@@ -556,9 +465,7 @@ func (p *Provider) observeIntrospection(if err != nil || status != http.StatusOK {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.+ // A differential, not a threshold: the health route is never faulted.if took-at.healthTook >= slack(trap.Delay) {return sprintf(observedIntroSlow,@@ -571,23 +478,18 @@ func (p *Provider) observeIntrospection(return p.observeRevocation(ctx, trap, at)default:- // Unreachable: observeEndpoint routes only the introspection group here.+ // Kinds from the other groups reach their own observer.}return "", false, 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.+// Two reads, so a revoked credential differs from a provider that lost all.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(@@ -615,12 +517,7 @@ func (p *Provider) observeRevocation(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. 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.+// Counted as khaos's own, so the exported count measures the TARGET only.func (p *Provider) introspectURL(root, credential string) string {p.ownIntrospects.Add(1)return root + RouteIntrospect + "?" + ParamToken + "=" + credential@@ -673,8 +570,7 @@ func readRoute(return response.StatusCode, body, nil}-// 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.+// Recorded as khaos's own fetch, keeping the exported count the target's.func (p *Provider) fetchSet(ctx context.Context,client *http.Client,@@ -727,9 +623,6 @@ func fetchIntrospection(return out, nil}-// verifiesUnderSet is the control half of every claim trap. A claim trap's whole-// claim is that the SIGNATURE is correct and exactly one claim is not, so a-// token whose signature does not verify is not the token the trap describes.func verifiesUnderSet(set JWKSet, token Token) bool {key, err := set.Lookup(token.Header.Kid)if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.goindex b7e560ab..0510f3ac 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go@@ -28,21 +28,13 @@ const (mimeJSON = "application/json"mimeText = "text/plain"- // DefaultAudience and DefaultSubject are what khaos's provider puts in every- // honest token. They are constants rather than parameters because the target- // has to be configured with the same audience at container creation, and a- // knob on both ends that must agree is a knob that will disagree.+ // Fixed, not configurable: the target is built with this audience too.DefaultAudience = "khaos-range"DefaultSubject = "khaos-operator"- // ForeignAudience and ForeignIssuer are the second tenant. The wrong-audience- // and foreign-issuer traps address tokens to these, and a verifier that- // accepts either has stopped treating its own identity as a constraint.ForeignAudience = "khaos-range-other"ForeignIssuerID = "https://khaos.invalid/second-tenant"- // DefaultLifetime is long enough that no run expires a token it is using and- // short enough to be a plausible access-token lifetime.DefaultLifetime = 10 * time.MinuteopaquePrefix = "khaos-opaque-"@@ -72,46 +64,25 @@ var ErrTrapNotObserved = errors.New(var ErrNoSuchGrant = errors.New("that credential was never issued here")-// armedTrap is the whole mutable fault state, swapped as one value so a handler-// can never read a trap from one revert and a generation from another. It is the-// same discipline the fault proxy uses, and for the same reason: arming has to-// be indivisible or a probe can observe a half-applied fault.+// armedTrap is swapped as one value, so a trap and a generation always agree.type armedTrap struct {trap Trapgeneration uint64}-// keySnapshot is the key state as it stood before a rotating trap was armed.-// Reverting restores it, so the recovery phase measures the provider the-// baseline measured rather than a provider the fault permanently changed.type keySnapshot struct {signing *Keyretired []*Key}-// grant is one opaque credential the provider issued. Introspection answers from-// these, and revoking one flips active rather than deleting it, so a revert can-// put it back and the recovery phase means something.+// Revoking a grant flips active rather than deleting it, so Disarm can undo it.type grant struct {subject stringactive bool}-// Provider is khaos's own OIDC-shaped identity provider: a programmable signing-// oracle with a JWK Set, an introspection endpoint and a kill switch.-//-// It is hand-built rather than adopted, and research 07 section 4.2 is blunt-// about why: ten of the traps need a provider that will deliberately emit a-// malformed token, and four more need it to break its own endpoints on command-// and report how many times it was fetched. A correct provider does none of-// that, and that is not a gap in Keycloak or Dex, it is the definition of their-// being correct.-//-// The cost is stated out loud: this is not a conformance-tested OP and khaos-// must never claim it validates OIDC conformance. It validates VERIFIERS.-//-// Minting needs no listener, which is what lets an experiment build its probes-// before khaos has discovered the address the target is already addressing.+// Provider is khaos's own OIDC-shaped signing oracle, built to emit malformed+// tokens and break its own endpoints on command. It validates VERIFIERS.type Provider struct {audience stringforeignAudience string@@ -130,9 +101,7 @@ type Provider struct {grants map[string]*grantsnapshot *keySnapshot- // revocable is the credential THIS run intends to revoke. The mutator reads- // it at inject time rather than at build time, because the probe that issues- // it has not fired yet when the experiment is built.+ // Read at inject time: the probe that issues it has not fired at build.revocable stringstate atomic.Pointer[armedTrap]@@ -144,22 +113,10 @@ type Provider struct {server *http.Serverwg sync.WaitGroup- // jwksFetches counts every fetch of the key set, and ownFetches counts the- // subset khaos's own confirmation probes made. The accessor reports the- // difference, because this number is the measurement research 07 requirement- // R5 exists for — how often a verifier refetches, which no third-party- // provider exposes — and khaos's instrumentation must not appear in the- // measurement khaos is taking.- //- // Subtracting is used rather than a header the handler skips, because a- // header is spoofable and the arithmetic is not.+ // The accessors report the DIFFERENCE, keeping khaos's probes out of it.jwksFetches atomic.Int64ownFetches atomic.Int64- // The same arrangement for introspection. This counter is not decoration:- // three experiments fault the introspection endpoint, and without a way to- // see that the target ever CALLED it they can only report that the target- // survived a fault it never experienced.introspects atomic.Int64ownIntrospects atomic.Int64@@ -170,14 +127,10 @@ type Config struct {Audience stringLifetime time.Duration- // Now is the clock. Tests control it so a claim trap can be asserted against- // a known instant rather than against whatever the wall clock said.Now func() time.Time}-// New builds a provider with every key it might ever sign with, and no listener.-// All five keys are generated up front so arming a trap is a pointer swap rather-// than a key generation, which keeps the fault indivisible.+// New generates every key up front, so arming a trap is a pointer swap.func New(config Config) (*Provider, error) {if config.Audience == "" {config.Audience = DefaultAudience@@ -199,19 +152,13 @@ func New(config Config) (*Provider, error) {return nil, err}- // Published, and never rotated. It exists so an experiment that measures key- // ROTATION can still prove the target is serving without the proof itself- // disturbing what is being measured: a control token under the current- // signing key becomes new-key traffic the moment the key rotates, and that- // traffic is exactly what evicts the retired key.+ // Published and never rotated: a liveness proof is never new-key traffic.stable, err := NewRSAKey()if err != nil {return nil, err}- // NOT published, ever. The whole claim of the embedded-key trap is that the- // verifier resolved a key the provider never advertised, so publishing this- // one would make an acceptance unremarkable.+ // NOT published, ever: the trap's claim is a key never advertised.attacker, err := NewRSAKey()if err != nil {return nil, err@@ -252,16 +199,10 @@ func (p *Provider) clock() time.Time {return p.now()}-// Listen binds the provider where the target is already looking for it. The-// address is not khaos's choice: the verifier gateway's environment is fixed at-// container creation, so khaos binds the port that container is addressing-// rather than one khaos would have picked.+// Listen binds the address the target was built to address, not khaos's choice.func (p *Provider) Listen(addr string) error {- // The guard and the bind are under ONE lock acquisition. Releasing between- // them let two concurrent calls both pass the guard and both bind, with the- // second orphaning the first listener and its goroutine. Holding the lock- // across net.Listen is fine: it is a local syscall, not a round trip, and- // nothing else can usefully run until the provider has an address.+ // Guard and bind under ONE acquisition, or two callers both bind and the+ // second orphans the first listener and its goroutine.p.mu.Lock()defer p.mu.Unlock()@@ -286,24 +227,13 @@ func (p *Provider) Listen(addr string) error {p.listener = listenerp.server = server- // Only when nothing pinned one. An explicitly set issuer is the string the- // TARGET was configured to trust, and the address khaos listens on is never- // that string: khaos binds the bridge gateway's numeric address while the- // container addresses `host.docker.internal`.- //- // Overwriting it here minted every token with `iss` set to khaos's own- // listener, and the target refused all of them on the issuer check. The- // symptom was `baseline-not-met / "the valid credential was never accepted"`,- // which reads as a broken target rather than as khaos sending the wrong- // thing, and no unit test saw it because a test that reads Issuer() after- // Listen() agrees with itself by construction.+ // Only when nothing pinned one. A pinned issuer is the string the TARGET+ // trusts, and khaos's own listener address is never that string.if p.issuer == "" {p.issuer = "http://" + listener.Addr().String()}- // wg.Add inside the lock, so a Listen racing a Close cannot add to a- // WaitGroup that Close is already waiting on — the one misuse the- // sync.WaitGroup documentation calls out by name.+ // Inside the lock, so a Listen racing Close cannot add to a waited group.p.wg.Add(1)go func() {@@ -314,19 +244,13 @@ func (p *Provider) Listen(addr string) error {return nil}-// Issuer is the `iss` claim and the base of the JWKS URI. Before Listen it is-// whatever SetIssuer was told, because the target is configured with the issuer-// at container creation and khaos has to mint tokens that match it.func (p *Provider) Issuer() string {p.mu.RLock()defer p.mu.RUnlock()return p.issuer}-// SetIssuer pins the issuer khaos mints under, to the value the target was built-// expecting. A token whose `iss` disagrees with the target's configuration is-// rejected for a reason that has nothing to do with the trap under test, which-// reads exactly like a target that caught the trap.+// SetIssuer pins the issuer to the value the target was built expecting.func (p *Provider) SetIssuer(issuer string) {p.mu.Lock()defer p.mu.Unlock()@@ -364,8 +288,7 @@ func (p *Provider) Close() error {return err}-// Arm swaps the trap in as one value and snapshots any key state the trap is-// about to change, so Disarm can put it back.+// Arm swaps the trap in and snapshots the key state Disarm will put back.func (p *Provider) Arm(trap Trap) error {select {case <-p.closed:@@ -377,16 +300,9 @@ func (p *Provider) Arm(trap Trap) error {return err}- // The snapshot is taken whether or not the state change happens, because it- // is what the confirmation oracle compares the published set against. An- // inert arm has to leave the oracle able to say NO, and an oracle with- // nothing to compare cannot say anything.+ // Taken even when the arm is inert, or confirmation has nothing to compare.p.snap()- // Inert skips the state change and nothing else. That is what makes it a- // negative control for the two traps that mutate key material and the one- // that mutates a grant: the trap reads as armed, the observable never- // appears, and confirmation must refuse.if !p.inert.Load() {switch trap.Kind {case KidRollover:@@ -402,8 +318,7 @@ func (p *Provider) Arm(trap Trap) error {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.+ // The token traps hold no provider state; they act at mint time.}}@@ -413,16 +328,7 @@ func (p *Provider) Arm(trap Trap) error {return nil}-// 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.-//-// It OVERWRITES rather than keeping the first snapshot. The previous version-// returned early when one existed, so a second Arm without an intervening-// Disarm left RetiredKid naming the first retired key and made Disarm restore-// the wrong one — the confirmation oracle would then compare the published set-// against a kid two rotations old. No path arms twice today; the mutator arms in-// Apply and disarms in Revert. This is the behaviour that is correct whether or-// not that stays true.+// snap OVERWRITES rather than keeping the first snapshot of a cycle.func (p *Provider) snap() {p.mu.Lock()defer p.mu.Unlock()@@ -433,10 +339,7 @@ func (p *Provider) snap() {}}-// RetiredKid is the key that was signing before the current arming cycle. The-// confirmation oracle asserts against the PUBLISHED SET rather than against this-// value, so reading it here cannot make a failed rotation look like a successful-// one: a rotation that did not happen leaves this kid still published.+// RetiredKid is the key that was signing before the current arming cycle.func (p *Provider) RetiredKid() (string, bool) {p.mu.RLock()defer p.mu.RUnlock()@@ -460,13 +363,7 @@ func (p *Provider) Trap() Trap {return p.state.Load().trap}-// Inert makes the provider behave correctly while a trap is still armed. It-// exists so the confirmation oracle has a negative control.-//-// Without a way to arm a trap that does NOT happen, every test can only assert-// that confirmation SUCCEEDS, and a confirmation gutted to `return true`-// satisfies all of them. The fault proxy paid for that lesson: measured, that-// gut left all seventeen packages and the Docker gate green.+// Inert behaves correctly with a trap armed: the oracle's negative control.func (p *Provider) Inert(inert bool) {p.inert.Store(inert)}@@ -478,11 +375,7 @@ func (p *Provider) effective() Trap {return p.Trap()}-// rotate installs a fresh signing key. With overlap the retired key stays-// published, which is the availability-preserving rotation every provider is-// supposed to perform. Without it the retired key is withdrawn immediately,-// which is what makes a previously valid token unverifiable to anyone who-// refetches and still valid to anyone who caches forever.+// rotate installs a fresh signing key; with overlap the old one stays live.func (p *Provider) rotate(overlap bool) error {fresh, err := NewRSAKey()if err != nil {@@ -516,10 +409,7 @@ func (p *Provider) restoreKeys() {p.snapshot = nil}-// revoke flips a grant inactive. It refuses a credential the provider never-// issued rather than silently succeeding, because a revocation that did not-// happen makes every later acceptance correct behaviour and the run's finding-// unreachable.+// revoke refuses an unknown credential rather than silently succeeding.func (p *Provider) revoke(credential string) error {p.mu.Lock()defer p.mu.Unlock()@@ -543,9 +433,7 @@ func (p *Provider) restoreGrants() {}}-// HonestToken is always a correct token, whatever is armed. The valid stream-// carries it, and a stream that drifted into carrying forged tokens would make-// every verdict read as a crash.+// HonestToken is always a correct token, whatever is armed.func (p *Provider) HonestToken() (string, error) {return p.mintToken(Trap{},@@ -553,10 +441,6 @@ func (p *Provider) HonestToken() (string, error) {)}-// TrappedToken honours whatever is armed. It is what the forged stream carries,-// and it is also what the rotation experiment's VALID stream carries, because-// 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(),@@ -564,19 +448,8 @@ func (p *Provider) TrappedToken() (string, error) {)}-// StableToken is a correct JWT signed by a key that is always published and-// never rotated.-//-// It is the valid-stream credential for the rotation experiments, and the reason-// is an observer effect khaos measured on itself. A valid stream minting under-// the CURRENT signing key supplies new-key traffic after a rotation, and research-// 07 section 2.3 establishes that the eviction of a retired key is a side effect-// of exactly that traffic — so khaos was causing the recovery it then reported.-//-// An opaque credential also avoids it, and was the first fix, but it requires-// the target to support introspection, which a JWT-only verifier does not. This-// one is a JWT, so it works against any verifier, and its kid is in the key set-// from the baseline onwards, so resolving it never forces a refetch.+// StableToken is signed by a key that is always published and never rotated,+// so a valid stream never supplies the traffic that evicts a retired key.func (p *Provider) StableToken() (string, error) {p.mu.RLock()stable := p.stable@@ -585,9 +458,7 @@ func (p *Provider) StableToken() (string, error) {return p.mintSignedBy(stable)}-// Opaque issues a credential that carries no claims, so the only way a verifier-// can decide anything about it is to ask. It is what the introspection traps are-// measured with.+// Opaque issues a credential carrying no claims, so a verifier has to ask.func (p *Provider) Opaque() string {credential := opaquePrefix + rand.Text()@@ -598,10 +469,7 @@ func (p *Provider) Opaque() string {return credential}-// Revocable issues an opaque credential and records it as the one this run-// intends to revoke, so the mutator can find it at inject time. The probe that-// calls this has not fired when the experiment is built, which is why the-// credential cannot travel on the trap from the start.+// Revocable issues an opaque credential and records it as this run's target.func (p *Provider) Revocable() string {credential := p.Opaque()@@ -623,11 +491,7 @@ func (p *Provider) RevocableCredential() (string, error) {return p.revocable, nil}-// PublishedSet is every key a verifier may resolve, which is every key khaos-// signs with EXCEPT the attacker key. The weak and EC keys are always published-// rather than published on arming, so that a forgery trap changes only what the-// provider MINTS and a key trap changes only what it SERVES. Confusing the two-// would make each one's read-back ambiguous.+// PublishedSet is every key khaos signs with except the attacker key.func (p *Provider) PublishedSet() JWKSet {p.mu.RLock()defer p.mu.RUnlock()@@ -661,8 +525,6 @@ func (p *Provider) JWKSFetches() int64 {return p.jwksFetches.Load() - p.ownFetches.Load()}-// Introspections is how many times something OTHER than khaos asked about a-// credential.func (p *Provider) Introspections() int64 {return p.introspects.Load() - p.ownIntrospects.Load()}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.goindex ba739fda..1a99204d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/routes.go@@ -19,17 +19,11 @@ const (fieldToken = "token"fieldSubject = "sub"- // Enough for a token and its form framing, and nowhere near enough to be a- // memory-exhaustion surface on an endpoint that takes unauthenticated- // requests by design.maxFormBytes = 64 << 10)// Introspection is RFC 7662's response. `active` is the only member a verifier-// may decide on, and the specification is explicit that the ABSENCE of a-// response is not `active: false`. A caller that invents one from a timeout or a-// 503 has made up a value the provider never gave it, which is taxonomy row F20-// and which three of this package's traps exist to provoke.+// may decide on, and the ABSENCE of a response is not `active: false`.type Introspection struct {Active bool `json:"active"`Subject string `json:"sub,omitempty"`@@ -47,18 +41,14 @@ func (p *Provider) routes() *http.ServeMux {return mux}-// health is never faulted. A target or an operator has to be able to tell-// "khaos's provider is gone" from "khaos's provider is lying", and a health-// endpoint that participates in the fault destroys that distinction.+// health is never faulted, or "khaos's provider is gone" stops being+// distinguishable from "khaos's provider is lying".func (p *Provider) health(w http.ResponseWriter, _ *http.Request) {w.WriteHeader(http.StatusOK)}-// discovery is the OIDC Discovery document. It is served so a target can be-// pointed at the issuer alone, and it is deliberately NOT faulted: research 07-// found that OIDC Discovery says nothing about rotation, nothing about `kid` and-// nothing about refetching, so every interesting fault lives at the JWK Set-// rather than at the document that points to it.+// discovery is deliberately NOT faulted: OIDC Discovery says nothing about+// rotation, `kid` or refetching, so every fault lives at the JWK Set.func (p *Provider) discovery(w http.ResponseWriter, _ *http.Request) {issuer := p.Issuer()@@ -72,11 +62,8 @@ func (p *Provider) discovery(w http.ResponseWriter, _ *http.Request) {})}-// jwks serves the published key set, and counts every fetch. The count is the-// measurement the refetch-amplification question needs and that no third-party-// provider exposes: an unknown `kid` is an attacker-controlled header field, so-// an unbounded refetch is a denial-of-service amplifier, and the only way to-// know whether a verifier bounds it is to count from the provider's side.+// jwks counts every fetch: `kid` is attacker-controlled, so an unbounded+// refetch is an amplifier only the provider's side can measure.func (p *Provider) jwks(w http.ResponseWriter, _ *http.Request) {p.jwksFetches.Add(1)@@ -88,10 +75,7 @@ func (p *Provider) jwks(w http.ResponseWriter, _ *http.Request) {writeJSON(w, http.StatusOK, p.PublishedSet())}-// token mints under whatever is armed. khaos's own probes call mintToken-// in-process and never come through here; this exists so an operator can point-// their own client at khaos's provider, which is what makes the provider an-// instrument rather than a range fixture.+// token exists for an operator's own client; khaos's probes call mintToken.func (p *Provider) token(w http.ResponseWriter, _ *http.Request) {minted, err := p.TrappedToken()if err != nil {@@ -109,12 +93,8 @@ func (p *Provider) token(w http.ResponseWriter, _ *http.Request) {})}-// introspect answers about an opaque credential, and carries three of the traps.-// Each one leaves the provider REACHABLE and answering, which is the whole-// point: a caller's `err != nil` branch is never taken, so only its status-// handling, its decoder's error branch, or its timeout decides what happens.-// That is a different code path from an outage and it is reached by different-// bugs.+// introspect carries three traps, and each leaves the provider REACHABLE and+// answering, so a caller's `err != nil` branch is never the one that decides.func (p *Provider) introspect(w http.ResponseWriter, r *http.Request) {p.introspects.Add(1)@@ -126,9 +106,7 @@ func (p *Provider) introspect(w http.ResponseWriter, r *http.Request) {returncase IntrospectionMalformed:- // A 200 with a body that starts out looking like the real thing and then- // stops being JSON. A caller whose decode error branch returns "active"- // has invented a value RFC 7662 never provides.+ // A 200 whose body stops being JSON, so the decode branch decides.w.Header().Set(headerContentType, mimeJSON)w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte(malformedBody))@@ -144,10 +122,7 @@ func (p *Provider) introspect(w http.ResponseWriter, r *http.Request) {}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.+ // Every other trap leaves this route's response alone.}credential := credentialFrom(r)@@ -169,9 +144,7 @@ func (p *Provider) introspect(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, body)}-// revokeRoute is the operator-facing revocation. It reports whether it actually-// revoked anything: a 404 for a credential this provider never issued, because-// answering 200 to a revocation that did not happen is how a run goes on to+// A 404 when nothing was revoked: answering 200 is how a run goes on to// measure a credential nobody took away.func (p *Provider) revokeRoute(w http.ResponseWriter, r *http.Request) {credential := credentialFrom(r)@@ -188,26 +161,14 @@ func (p *Provider) revokeRoute(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)}-// credentialFrom reads the token the way the specifications say it is sent, and-// also the way khaos used to send it.-//-// RFC 7662 section 2.1 defines the introspection request as a POST with an-// `application/x-www-form-urlencoded` body, and RFC 7009 section 2.1 says the-// same for revocation. khaos read the token ONLY from the query string, and its-// own client sent it only that way, so the two agreed with each other and with-// nothing else: a conforming external client got `active: false` for a perfectly-// valid credential and could not establish a baseline at all.-//-// The query form is still accepted. It costs nothing, it keeps khaos's own-// read-back probes working, and a provider that is deliberately willing to be-// wrong has no reason to be strict about where it reads an input from.+// RFC 7662 section 2.1 and RFC 7009 section 2.1 put the token in a form body;+// the query string is accepted too, and is what khaos's own probes send.func credentialFrom(r *http.Request) string {if token := r.URL.Query().Get(ParamToken); token != "" {return token}- // Bounded. This is a fixture that accepts unauthenticated requests, so an- // unbounded ParseForm is a trivial way to exhaust its memory.+ // Bounded: the endpoint is unauthenticated, so ParseForm must not be.r.Body = http.MaxBytesReader(nil, r.Body, maxFormBytes)if err := r.ParseForm(); err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.goindex 377a5434..443b2c8e 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go@@ -27,48 +27,24 @@ const (var ErrNotAJWS = errors.New("that is not a JWS compact serialization")-// Header is the JOSE header khaos emits. Every field a trap needs to corrupt is-// here, including the ones a correct provider never sets: `jwk` exists so khaos-// can embed an attacker key, which is trap T2b, and `alg` is a plain string-// rather than an Algorithm so khaos can emit a value it does not itself support.+// Header carries the fields a correct provider never sets, and `alg` is a+// plain string so khaos can emit a value it does not itself support.type Header struct {Alg string `json:"alg"`Typ string `json:"typ,omitempty"`Kid string `json:"kid,omitempty"`- // JWK is RFC 7515's in-token key. khaos sets it only for the key-injection- // probe. A verifier that resolves a key from here instead of from the trusted- // JWK Set has violated RFC 8725 rule 4, and that is the finding.+ // JWK is RFC 7515's in-token key. A verifier that resolves a key from here+ // rather than from the trusted set has violated RFC 8725 rule 4.JWK *JWK `json:"jwk,omitempty"`- // JKU is the in-token key-set URL, and khaos does not set it.- //- // An earlier comment here claimed khaos pointed it at its own provider and- // counted the hit. It did not: nothing in the repository ever assigned this- // field. Research 07's trap T2b does ask for that probe — a verifier that- // FETCHES an attacker-supplied URL is a finding even when the token is then- // rejected — but the fetch is not an outcome in any probe stream, so- // surfacing it needs an observation channel khaos does not have. The- // omission is recorded in the design contract's fault catalogue rather than- // described here as a feature.- //- // The field stays so a verifier's non-following of it is a property khaos can- // express later without reshaping the header.+ // JKU is the in-token key-set URL, and khaos does not set it. The field+ // stays so non-following can be expressed without reshaping the header.JKU string `json:"jku,omitempty"`}-// Claims is the payload. Every time field is a pointer so khaos can emit a token-// with a claim genuinely ABSENT rather than present and zero: a verifier that-// rejects `exp: 0` while accepting a missing `exp` is a different bug, and-// encoding/json cannot express the difference without this.-// Audience is RFC 7519 section 4.1.3's `aud`, which is "an array of-// case-sensitive strings" in the general case and "MAY be a single-// case-sensitive string" when there is one audience.-//-// It is a type rather than a plain string because a plain string made the-// general case fail to unmarshal, and a verifier that dispatched on parse-// success then treated a perfectly legal multi-audience JWT as an opaque-// credential.+// Audience is RFC 7519 section 4.1.3's `aud`: an array of case-sensitive+// strings, which MAY be a single string when there is one audience.type Audience []stringfunc (a *Audience) UnmarshalJSON(raw []byte) error {@@ -88,9 +64,6 @@ func (a *Audience) UnmarshalJSON(raw []byte) error {return nil}-// MarshalJSON emits the single-string form for one audience, because that is-// what a real provider emits and khaos's forged tokens have to be ordinary in-// every respect except the one property each trap corrupts.func (a Audience) MarshalJSON() ([]byte, error) {if len(a) == 1 {return json.Marshal(a[0])@@ -111,6 +84,8 @@ func (a Audience) String() string {return strings.Join(a, ", ")}+// Claims keeps every time field as a pointer, so khaos can emit a claim that+// is genuinely ABSENT rather than present and zero.type Claims struct {Issuer string `json:"iss,omitempty"`Subject string `json:"sub,omitempty"`@@ -122,9 +97,7 @@ type Claims struct {Scope string `json:"scope,omitempty"`}-// Token is a parsed JWS with its segments kept verbatim. The raw signing input-// is retained because re-deriving it from the decoded parts would re-serialize-// the JSON, and a signature is over the bytes that were actually sent.+// Token keeps its segments verbatim: a signature is over the bytes as sent.type Token struct {Raw stringSigningInput []byte@@ -135,9 +108,6 @@ type Token struct {ClaimsJSON []byte}-// assemble builds the compact serialization. It takes the already-marshalled-// 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,@@ -152,9 +122,6 @@ func signingInput(headerJSON, claimsJSON []byte) []byte {return []byte(b64(headerJSON) + segmentSep + b64(claimsJSON))}-// Parse reads a compact JWS without verifying anything. khaos uses it on its own-// confirmation path, where the question is what khaos actually emitted rather-// than whether it is acceptable.func Parse(raw string) (Token, error) {parts := strings.Split(raw, segmentSep)if len(parts) != jwsSegments {@@ -200,9 +167,8 @@ func Parse(raw string) (Token, error) {return out, nil}-// decodeSegment is strict base64url with no padding, which is what RFC 7515-// section 2 specifies. A lenient decoder would let khaos's own confirmation read-// a token a verifier would reject for a different reason.+// Strict base64url with no padding, per RFC 7515 section 2: a lenient decoder+// would read a token a verifier rejects for a different reason.func decodeSegment(encoded string) ([]byte, error) {return base64.RawURLEncoding.DecodeString(encoded)}@@ -216,15 +182,7 @@ func unix(t time.Time) *int64 {return &seconds}-// Retarget rewrites a token's `kid` and nothing else, leaving its signature-// intact and therefore unverifiable under the key it now names.-//-// It exists for the range verifier's own tests rather than for any khaos-// experiment: a header that disagrees with its key about the algorithm is-// forbidden by RFC 8725 rule 2, and no token an attacker could actually forge-// isolates that rule, because anything that trips it also fails the signature-// check. The fixture still has to carry the rule, so the rule still has to be-// exercised.+// Retarget rewrites only the `kid`, so the intact signature stops verifying.func Retarget(token Token, kid string) string {header := token.Headerheader.Kid = kid@@ -237,13 +195,8 @@ func Retarget(token Token, kid string) string {return assemble(headerJSON, token.ClaimsJSON, token.Signature)}-// LooksLikeJWS reports whether a credential has the SHAPE of a compact JWS:-// three dot-separated segments whose first decodes to JSON with an `alg`.-//-// A verifier has to choose between local validation and introspection before it-// can parse anything, and choosing on "did my parser succeed" is wrong in a way-// that matters: a token carrying a legal array `aud` fails a parser whose field-// is a string, and would then be introspected as though it were opaque.+// LooksLikeJWS tests the SHAPE, because choosing on "did my parser succeed"+// rejects a legal array `aud` and then introspects it as though it were opaque.func LooksLikeJWS(credential string) bool {parts := strings.Split(credential, segmentSep)if len(parts) != jwsSegments {@@ -266,17 +219,10 @@ func LooksLikeJWS(credential string) bool {return probe.Alg != ""}-// Retyped re-mints an honest token with a different `typ` and a valid signature.-// It exists so the range verifier's explicit-typing check can be exercised: a-// token whose signature does not verify would be refused before the claim checks-// are reached, and the typ check sits among them.func Retyped(p *Provider, typ string) string {return p.reheader(func(header *Header) { header.Typ = typ })}-// WithoutExpiry re-mints an honest token with no `exp` member at all, correctly-// signed. The pointer field is what makes an ABSENT claim expressible rather-// than a present zero.func WithoutExpiry(p *Provider) string {return p.reclaim(func(claims *Claims) { claims.Expires = nil })}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.goindex 8ccfa375..1c0de484 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/trap.go@@ -10,90 +10,58 @@ import ("time")-// Kind names one way khaos makes its own identity provider wrong. Every kind-// maps to a verifier defect with a traceable anchor in research 07, and the-// mapping is one-to-one with the experiments so `khaos catalog` names the actual-// trap rather than a generic entry.+// Kind names one way khaos makes its own identity provider wrong.type Kind stringconst (- // PassThrough is the zero value: the provider behaves correctly. A provider- // with nothing armed must be indistinguishable from a real one, because every- // experiment's baseline is measured against it.+ // PassThrough is the zero value, and every experiment's baseline.PassThrough Kind = ""- // AlgNone emits `{"alg":"none"}` with an empty signature. Trap T1,- // CVE-2022-23540.+ // AlgNone emits `{"alg":"none"}` with an empty signature. CVE-2022-23540.AlgNone Kind = "alg-none"- // AlgConfusion emits HS256 keyed on the bytes of the published RSA public- // key. Trap T2, CVE-2015-9235 and three others.+ // AlgConfusion emits HS256 keyed on the published RSA key. CVE-2015-9235.AlgConfusion Kind = "alg-confusion"- // EmbeddedJWK emits a token carrying its own signing key in the `jwk` header,- // signed by a key khaos never publishes. Trap T2b, CVE-2018-0114.+ // EmbeddedJWK carries its own unpublished signing key. CVE-2018-0114.EmbeddedJWK Kind = "embedded-jwk"- // ClaimExpired through ClaimForeignIssuer each emit a CORRECTLY SIGNED token- // with exactly one wrong claim. Research 07 calls this the cleanest- // experiment design in the tool: a 2xx isolates precisely which check is- // missing, with no ambiguity about the signature.+ // Each of these is CORRECTLY SIGNED with exactly one wrong claim.ClaimExpired Kind = "claim-expired"ClaimNotYetValid Kind = "claim-not-yet-valid"ClaimWrongAudience Kind = "claim-wrong-audience"ClaimForeignIssuer Kind = "claim-foreign-issuer"- // SignatureTruncated cuts a valid signature to one byte. Trap T6b,- // CVE-2020-28042.+ // SignatureTruncated cuts a valid signature to one byte. CVE-2020-28042.SignatureTruncated Kind = "signature-truncated"- // SignatureZero emits ES256 with an all-zero signature. Trap T6c, the shape- // of CVE-2022-21449. Measured on go1.26.5: ecdsa.Verify rejects r = s = 0, so- // a Go verifier is only vulnerable if it skips the check, which is what the- // range fixture does on purpose.+ // SignatureZero emits ES256 all-zero, the shape of CVE-2022-21449.+ // ecdsa.Verify rejects r = s = 0, so Go is only vulnerable if it skips it.SignatureZero Kind = "signature-zero"- // SignatureWeakKey signs with a modulus below the size crypto/rsa accepts.- // Trap T6a's class, CVE-2022-23539: a key type or size not validated against- // the algorithm.+ // SignatureWeakKey signs below crypto/rsa's floor. CVE-2022-23539's class.SignatureWeakKey Kind = "signature-weak-key"- // JWKSUnreachable stops serving the JWK Set. Trap T3 and taxonomy row F2,- // and research 07 calls it the highest-value trap in the archive because the- // code path is reachable only while the provider is down.+ // JWKSUnreachable stops serving the JWK Set, and nothing else.JWKSUnreachable Kind = "jwks-unreachable"- // KidRollover rotates the signing key and REMOVES the retired one from the- // JWK Set, so a token signed by it is no longer verifiable by anyone who- // refetches. Trap T4 and taxonomy row F3.+ // KidRollover rotates and REMOVES the retired key from the JWK Set.KidRollover Kind = "kid-rollover"- // KeyRotation rotates WITH an overlap window: both keys stay published and- // new tokens carry the new one. This is the availability mirror of- // KidRollover, and it is the one trap in the family where DENIED is the- // defect, because refusing a correctly signed current token is the failure.+ // KeyRotation rotates with both keys published, and is the one trap where+ // DENIED is the defect: refusing a correctly signed current token.KeyRotation Kind = "key-rotation"- // IntrospectionError answers introspection with a 503. It is deliberately not- // an outage: the provider is reachable and answering, so a caller's- // `err != nil` branch is never taken and only its status handling decides.- // Taxonomy row F20, where collapsing deny into unknown is the defect.+ // IntrospectionError answers 503 while staying REACHABLE and answering.IntrospectionError Kind = "introspection-error"- // IntrospectionMalformed answers 200 with a body that is not JSON, so the- // caller's decode-error branch decides. RFC 7662 is explicit that the absence- // of a usable response is not `active: true`.+ // IntrospectionMalformed answers 200 with a body that is not JSON.IntrospectionMalformed Kind = "introspection-malformed"- // IntrospectionSlow holds introspection past the caller's timeout while- // answering everything else promptly. A slow authority is not an unreachable- // one and a caller's code tells them apart.+ // IntrospectionSlow holds that one route past the caller's timeout.IntrospectionSlow Kind = "introspection-slow"- // Revoke revokes a credential at a provider the target can still reach. The- // contrast with `identity.idp_outage` is the whole point: there the authority- // is unreachable, here it is answering `active: false` and the target is- // simply not asking.+ // Revoke revokes at a provider the target can still reach, and is not asking.Revoke Kind = "revoke")@@ -126,23 +94,15 @@ var ErrInvalidTrap = errors.New("that trap cannot be armed as specified")var ErrUnknownTrap = errors.New("khaos's identity provider has no such trap")-// Trap is one armed misbehaviour and its magnitude. It is a value rather than a-// closure so it can be journaled: the provider dies with the process, so the-// journal record is the only durable account of what a run actually did.+// Trap is a value rather than a closure so that it can be journaled.type Trap struct {Kind Kind `json:"kind"`- // Delay is how long IntrospectionSlow holds a call, and how far ClaimExpired- // and ClaimNotYetValid move the claim they corrupt.Delay time.Duration `json:"delay,omitempty"`- // Credential is the opaque token Revoke acts on.Credential string `json:"credential,omitempty"`- // KeyForm is the serialization AlgConfusion keys its HMAC on. It is a- // parameter rather than a fixed choice because research 07 is explicit that- // the same verifier bug is unreachable under the wrong form: the attack has- // to use the exact bytes the target loaded its public key from.+ // KeyForm has to be the exact bytes the target loaded its key from.KeyForm KeyForm `json:"key_form,omitempty"`}@@ -162,7 +122,7 @@ func (t Trap) Validate() error {t.KeyForm, SPKIPEM, SPKIDER, PKCS1PEM, Modulus)}default:- // The remaining traps carry no parameter to validate.+ // The remaining traps carry no magnitude to validate.}if t.Kind != PassThrough && !slices.Contains(Kinds(), string(t.Kind)) {@@ -172,9 +132,7 @@ func (t Trap) Validate() error {return nil}-// Describe states the trap with its actual magnitude. The proxy tier paid for-// this lesson: reading the kind alone and leaving the parameters at zero printed-// a plan line that understated the fault it was asking consent for.+// Describe states the trap WITH its magnitude, or it understates the fault.func (t Trap) Describe(target string) string {switch t.Kind {case AlgNone:@@ -216,10 +174,6 @@ func (t Trap) Describe(target string) string {}}-// Forgery reports whether the trap corrupts what the provider MINTS, as opposed-// to what it serves or how it answers. It decides which probe stream an-// experiment needs, and it is derived here so an experiment cannot disagree with-// the trap about its own shape.func (t Trap) Forgery() bool {switch t.Kind {case AlgNone, AlgConfusion, EmbeddedJWK,@@ -231,7 +185,6 @@ func (t Trap) Forgery() bool {}}-// Kinds is every trap an operator can arm, in a stable order.func Kinds() []string {return []string{string(AlgNone),diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/dnsfault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/dnsfault.goindex bbb65bbc..a5527e65 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/dnsfault.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/dnsfault.go@@ -26,29 +26,15 @@ var ErrNoResolver = errors.New("this mutation needs khaos's chaos resolver, which is not running",)-// DNSKind names the mutation that arms one fault on khaos's chaos resolver. The-// fault kinds and the mutation kinds are one-to-one, so `khaos catalog` names-// the actual defect being provoked rather than a generic "DNS" entry.+// DNSKind is one-to-one with the fault kinds, so the catalogue names the actual+// defect rather than a generic "DNS" entry.func DNSKind(kind dnsrv.Kind) string {return KindDNSPrefix + string(kind)}-// dnsMutator arms a fault on khaos's chaos resolver.-//-// This is a FIFTH tier, and the reason it is its own tier rather than a fourth-// authority is measured rather than architectural taste. Every other authority-// khaos plays — the identity provider, the certificate authority — is a-// goroutine in khaos's own process, bound on a high host port the target was-// told to dial. A DNS resolver cannot be: `--dns` carries an address and no-// port, the daemon rejects one at container start, and an unprivileged process-// gets `bind: permission denied` on port 53 at every address including-// loopback. So this authority lives in a container, which is the only place a-// process can hold port 53 without khaos holding a capability.-//-// The fault it injects is also unlike the others. The dependency is healthy and-// reachable; the target cannot FIND it, or finds something else. That is a third-// branch of the target's code, distinct from both an unreachable dependency and-// one whose certificate will not verify.+// dnsMutator's authority is a CONTAINER, not a goroutine like the others:+// `--dns` carries no port and an unprivileged process cannot bind 53. The+// dependency also stays healthy here; the target simply cannot find it.type dnsMutator struct {kind dnsrv.Kind}@@ -69,12 +55,8 @@ func (m dnsMutator) Describe(env Env, target dockerx.Target) string {return fmt.Sprintf(describeDNS, trap.Describe(target.Name))}-// dnsPayload is what the journal carries. It records how to reach the resolver-// as well as the fault, because the revert has to work from a COLD START where-// khaos remembers nothing — and unlike every other in-process tier, this one's-// authority outlives the khaos process that armed it. A fault left armed by a-// killed khaos is a target whose dependency stays unresolvable, so the record-// has to be enough to undo it without the run that made it.+// dnsPayload records how to reach the resolver as well as the fault, because+// this tier's authority outlives the khaos process that armed it.type dnsPayload struct {Trap dnsrv.Trap `json:"trap"`Network string `json:"network"`@@ -134,17 +116,9 @@ func (m dnsMutator) Apply(return err}-// Revert disarms, which restores khaos's own honest answer so the recovery-// window is measured through a WORKING resolver rather than through no-// resolution at all.-//-// A cold start rebuilds the client from the daemon rather than giving up, and-// that is the difference between this tier and the in-process ones. An identity-// provider or a certificate authority dies with the khaos process that held it,-// so the fault provably went with it and there is nothing to undo. A resolver-// container does not die: it keeps serving NXDOMAIN for the target's dependency-// until something disarms it. The nonce is read off the container's own label,-// so the revert needs nothing khaos remembered.+// Revert disarms, so recovery is measured through a WORKING resolver rather+// than no resolution at all. The container does not die with khaos, so a cold+// start rebuilds the client and reads the nonce off the container's own label.func (m dnsMutator) Revert(ctx context.Context,env Env,@@ -163,11 +137,8 @@ func (m dnsMutator) Revert(client = reconnectResolver(ctx, env, payload)}- // Nothing left to disarm, which is SUCCESS rather than a failure to report.- // The resolver the record named is gone, so it took the fault with it, and- // reporting that as an error would wedge the record forever and, because- // `khaos reap` stops on a sweep error, disable the dead man's switch for- // every other fault on the machine.+ // Nothing left to disarm is SUCCESS: the resolver named is gone, so it took+ // the fault with it.if client == nil {return nil}@@ -177,15 +148,9 @@ func (m dnsMutator) Revert(return err}-// reconnectResolver finds the resolver a journal record names and builds a-// client for it, or nil if there is none to find.-//-// It returns no error ON PURPOSE, and the single return is the honest signature-// rather than a convenience. Every way this can fail to produce a client means-// the same thing: the resolver that held the fault is not there, so the fault is-// not there either. A record with no network, a daemon khaos cannot reach from a-// cold start, a container somebody already removed -- each of those is a revert-// that has nothing left to do, and the caller treats nil as done.+// reconnectResolver returns no error ON PURPOSE: every way it can fail to+// produce a client means the resolver that held the fault is not there, so the+// caller treats nil as a revert with nothing left to do.func reconnectResolver(ctx context.Context,env Env,@@ -208,16 +173,8 @@ func reconnectResolver()}-// Confirm delegates to the resolver client's own read-back, which asks the-// resolver the same question the target asks and reports what came off the-// wire.-//-// It deliberately does not read the armed state back. The control surface-// answers /arm with the resolver's state, which would be the easy thing to-// check and would confirm a fault against a resolver whose serving path is-// broken. The PKI tier's inert-authority control caught fifteen traps doing-// exactly that, every one of them reading the trap RECORD instead of what was-// served.+// Confirm asks the resolver the same question the target asks, never reading+// the armed state back, which would confirm against a broken serving path.func (m dnsMutator) Confirm(_ context.Context,env Env,@@ -239,9 +196,8 @@ func (m dnsMutator) Confirm(return env.Resolver.Observe(trap)}-// NeedsResolver reports whether this mutation arms khaos's chaos resolver, so-// the run knows to find one before the baseline. It is derived from the registry-// rather than from the kind's spelling, for the same reason NeedsProxy is.+// NeedsResolver tells the run to find a resolver before the baseline, derived+// from the registry rather than from the kind's spelling.func NeedsResolver(kind string) bool {mutator, ok := registry[kind]if !ok {@@ -253,7 +209,5 @@ func NeedsResolver(kind string) bool {return isDNS}-// Prefix declares this tier's kinds to the registry. The chaos resolver outlives-// the khaos process, but it is still per-RUN state: `khaos inject` neither-// stands one up nor knows which network it would serve.+// Prefix declares this tier's kinds to the registry.func (dnsMutator) Prefix() string { return KindDNSPrefix }diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.goindex 7aa67199..7e28c0f4 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/idpfault.go@@ -31,21 +31,15 @@ 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-// the actual defect being provoked rather than a generic "identity provider"-// entry.+// IdPKind is one-to-one with the trap kinds, so the catalogue names the actual+// defect rather than a generic "identity provider" entry.func IdPKind(kind idp.Kind) string {return KindIdPPrefix + string(kind)}-// idpMutator arms a trap on khaos's in-process identity provider. This is a-// THIRD injection tier alongside the Docker-native one and the fault proxy, and-// it exists because the other two cannot express the fault at all: pausing a-// provider or severing the path to it makes it unreachable, where every trap in-// this tier leaves it REACHABLE and wrong. A verifier's behaviour on an-// unreachable authority and its behaviour on a lying one are different code-// paths reached by different bugs.+// idpMutator leaves the provider REACHABLE and wrong, where pausing it or+// severing the path would only make it unreachable, which is a different code+// path in the verifier.type idpMutator struct {kind idp.Kind}@@ -66,13 +60,9 @@ func (m idpMutator) Describe(env Env, target dockerx.Target) string {return fmt.Sprintf(describeIdP, trap.Describe(target.Name))}-// Plan journals the trap that is about to be armed, and resolves the one piece-// of it that cannot be known at build time.-//-// The revocation's credential is issued by a PROBE, and no probe has fired when-// 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.+// Plan resolves the one piece not knowable at build time: the revocation's+// credential is issued by a PROBE, so the trap picks it up here, after the+// baseline, once the target has been honouring it.func (m idpMutator) Plan(_ context.Context,env Env,@@ -126,12 +116,9 @@ func (m idpMutator) Apply(return env.IdP.Arm(trap)}-// Revert disarms, which also restores any key material or grant the trap-// changed. A cold start has no provider to disarm and that is RESOLVED rather-// than failed: the provider died with the process that held it, so the fault-// 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.+// Revert also restores any key material or grant the trap changed. A cold+// start has nothing to disarm and is RESOLVED rather than failed: the provider+// died with the process, so the fault went with it.func (m idpMutator) Revert(_ context.Context, env Env, _ journal.Record) error {if env.IdP == nil {return nil@@ -142,12 +129,9 @@ func (m idpMutator) Revert(_ context.Context, env Env, _ journal.Record) error {return nil}-// Confirm delegates to the provider's own read-back, which measures the trap-// through the provider's public surface against a control and returns the-// specific observable it saw. It deliberately does NOT read the flag that was-// 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.+// Confirm measures through the provider's public surface against a control,+// never the flag that was set: a provider whose minting broke would otherwise+// confirm a trap it is not producing.func (m idpMutator) Confirm(ctx context.Context,env Env,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.goindex 701f1fd5..54250fc9 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.go@@ -26,26 +26,15 @@ var ErrNoAuthority = errors.New("this mutation needs khaos's certificate authority, which is not running",)-// PKIKind names the mutation that arms one trap on khaos's certificate-// authority. The trap kinds and the mutation kinds are one-to-one, so `khaos-// catalog` names the actual defect being provoked rather than a generic-// "certificate" entry.+// PKIKind is one-to-one with the trap kinds, so the catalogue names the actual+// defect rather than a generic "certificate" entry.func PKIKind(kind pki.Kind) string {return KindPKIPrefix + string(kind)}-// pkiMutator arms a trap on khaos's in-process certificate authority.-//-// This is a FOURTH tier, and it exists for the same reason the identity-// provider does: the other three cannot express the fault. Pausing a dependency-// or severing the path to it makes it unreachable, where every trap here leaves-// it REACHABLE and presenting a certificate that is wrong in one specific way.-// A client's behaviour on an unreachable dependency and its behaviour on one-// whose identity it cannot verify are different code paths reached by different-// bugs, and only the second is a TLS finding.-//-// No correct CA will mint an expired, revoked or wrongly-named certificate at-// any price, which is why khaos has to be the CA.+// pkiMutator leaves the dependency REACHABLE and presenting a certificate+// wrong in one specific way, which is the only shape that is a TLS finding. No+// correct CA mints an expired or revoked certificate, so khaos has to be the CA.type pkiMutator struct {kind pki.Kind}@@ -66,11 +55,8 @@ func (m pkiMutator) Describe(env Env, target dockerx.Target) string {return fmt.Sprintf(describePKI, trap.Describe(target.Name))}-// Plan journals the trap that is about to be armed. Everything this tier needs-// is known at build time, so unlike the identity tier's revocation there is-// nothing to resolve here -- but the trap is still validated before it reaches-// the journal, because a record that cannot be armed is a record `khaos-// reclaim` would retry forever.+// Plan validates before journaling, because a record that cannot be armed is+// one `khaos reclaim` would retry forever.func (m pkiMutator) Plan(_ context.Context,env Env,@@ -120,14 +106,9 @@ func (m pkiMutator) Apply(return env.Authority.Arm(trap)}-// Revert disarms, which re-mints an honest chain so the recovery window is-// measured through a WORKING authority rather than through no authority at all.-//-// A cold start has no authority to disarm and that is RESOLVED rather than-// failed: the authority died with the process that held it, so the fault-// 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.+// Revert re-mints an honest chain, so recovery is measured through a WORKING+// authority. A cold start has nothing to disarm and is RESOLVED rather than+// failed: the authority died with the process, so the fault went with it.func (m pkiMutator) Revert(_ context.Context, env Env, _ journal.Record) error {if env.Authority == nil {return nil@@ -136,16 +117,9 @@ func (m pkiMutator) Revert(_ context.Context, env Env, _ journal.Record) error {return env.Authority.Disarm()}-// Confirm delegates to the authority's own read-back, which compares what it-// SERVES against an honest chain from the same authority and returns the-// specific observable it saw.-//-// It deliberately does not read the flag that was set. A flag records which-// branch was chosen, not what a target would receive, and an authority whose-// minting broke would confirm a trap it is not producing. The oracle's negative-// control found fifteen traps that could be confirmed against an authority-// which had armed nothing at all, every one of them because something was-// derived from the trap record instead of from the served material.+// Confirm compares what the authority SERVES against an honest chain from it,+// never the flag that was set: a flag records which branch was chosen, so an+// authority whose minting broke would confirm a trap it is not producing.func (m pkiMutator) Confirm(ctx context.Context,env Env,@@ -163,6 +137,5 @@ func (m pkiMutator) Confirm(}// Prefix declares this tier's kinds to the registry, which keeps `khaos inject`-// from offering them: the certificate authority is a goroutine inside a run and-// `khaos inject` starts none.+// from offering them: the authority is a goroutine inside a run.func (pkiMutator) Prefix() string { return KindPKIPrefix }diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.goindex 66b26149..ba603ad2 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/fault.go@@ -14,41 +14,29 @@ import (type Kind stringconst (- // PassThrough is not a fault. It is what the proxy does when nothing is- // armed, and it has to be a real mode rather than the absence of one,- // because the baseline is measured through the proxy and a baseline- // measured through a different code path than the fault window proves- // nothing about the difference between them.+ // A real mode rather than the absence of one, because the baseline is+ // measured through the proxy as well.PassThrough Kind = "pass-through"- // Hang accepts the connection and never answers. The research found this- // and Reset to be the two shapes that most reliably separate a fail-closed- // implementation from a fail-open one, because a refused connection and a- // hung one hit different branches in almost every HTTP client, and the hang- // branch is the one carrying the badly-chosen default timeout.+ // Accepts and never answers. A refused connection and a hung one hit+ // different client branches, and the hang branch carries the bad default.Hang Kind = "hang"- // Reset answers with RST rather than FIN. Reaching this needs SO_LINGER 0,- // because an ordinary close with an empty receive queue sends FIN.+ // RST rather than FIN, which needs SO_LINGER 0.Reset Kind = "reset"- // EOF accepts and closes cleanly, which is what a stopped or killed- // dependency looks like to its peer. Measured in research 06 section 6.1:- // even SIGKILL produces an orderly FIN.+ // Closes cleanly, as a stopped dependency does; even SIGKILL sends FIN.EOF Kind = "eof"- // Latency delays both directions. It is the graduated fault, for finding a- // timeout that is too generous rather than one that is missing.+ // Delays both directions, for a timeout too generous rather than missing.Latency Kind = "latency"- // Partial forwards a prefix of the dependency's answer and then closes, so- // the target receives a truncated body with a valid status line. This is the- // shape that finds a parser treating a short read as an empty-but-successful- // response, which an outage-shaped fault never reaches.+ // Forwards a prefix then closes, which finds a parser treating a short read+ // as empty-but-successful.Partial Kind = "partial"- // SlowClose forwards the whole answer and then holds the connection open.- // A client that waits for close rather than for Content-Length stalls.+ // Forwards everything, then holds the connection open, stalling a client+ // that waits for close rather than for Content-Length.SlowClose Kind = "slow-close")@@ -74,9 +62,8 @@ 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-// rather than by undoing anything.+// Fault is the whole mutable state of an armed proxy, so reverting is+// assigning PassThrough over it rather than undoing anything.type Fault struct {Kind KindDelay time.Duration@@ -105,10 +92,8 @@ func ParseKind(name string) (Kind, error) {return kind, nil}-// Validate refuses a fault that cannot express itself. A latency fault with no-// delay and a partial fault with no byte count are both indistinguishable from-// pass-through at runtime, which is a run that measures nothing and reports a-// clean survival.+// Validate refuses a fault that cannot express itself: a latency with no delay+// or a partial with no byte count is pass-through that reports as armed.func (f Fault) Validate() error {switch f.Kind {case Latency, SlowClose:@@ -121,10 +106,9 @@ func (f Fault) Validate() error {}case Hang, Reset, EOF:default:- // The whitelist is the point. A switch that only names the parameterised- // 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.+ // The whitelist is the point: naming only the parameterised kinds+ // accepts the zero Fault and a misspelling, and an unmarshalled journal+ // payload reaches here with no other guard.return fmt.Errorf(errUnknownKind,ErrUnknownKind,@@ -155,11 +139,8 @@ func (f Fault) Describe(target string) string {}}-// Severs reports whether the fault prevents the dependency from being reached at-// all. khaos confirms a severing fault by proving the dependency is unreachable-// THROUGH the proxy, and a forwarding fault by proving the proxy altered the-// stream, because those are different observations and one cannot stand in for-// the other.+// Severs separates the two confirmations: unreachability THROUGH the proxy, or+// an altered stream. Neither observation can stand in for the other.func (f Fault) Severs() bool {return f.Kind == Hang || f.Kind == Reset || f.Kind == EOF}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.goindex c7567627..fe29c6f2 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/observe.go@@ -19,11 +19,8 @@ const (observeDelayFactor = 4- // Slack on the measured magnitude. The thresholds are lower bounds with no- // tolerance otherwise, and on a host that also serves real traffic CPU- // contention routinely shaves a few percent off a sleep. Measured: under- // 64-goroutine load a 250ms slow-close refused 6 of 25 times, voiding a- // quarter of its runs.+ // Slack on the measured magnitude: the thresholds are lower bounds, and CPU+ // contention routinely shaves a few percent off a sleep.observeSlackNumerator = 9observeSlackDenominator = 10@@ -49,25 +46,9 @@ type reading struct {closed time.Duration}-// Observe confirms the armed fault by measuring the dependency on TWO paths and-// requiring them to disagree: once directly, bypassing the proxy, and once-// through it. It never consults an internal flag or a branch counter, because a-// counter incremented by the dispatcher records which code path was chosen rather-// than what reached the wire.-//-// The differential is what makes the oracle sound. An absolute threshold cannot-// tell khaos's fault from a slow dependency: measured, a dependency answering in-// four seconds confirmed a `hang` that was not applied at all, with the target-// 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.-// 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.+// armedFor checks closed FIRST, because close reverts to pass-through: reading+// the fault before that would report "nothing armed" for a proxy that is gone,+// and a dial to a dead listener is ECONNREFUSED, which reset must not accept.func (p *Proxy) armedFor(expected Kind) (Fault, error) {select {case <-p.closed:@@ -93,6 +74,9 @@ func (p *Proxy) armedFor(expected Kind) (Fault, error) {return fault, nil}+// Observe measures the dependency on TWO paths and requires them to disagree:+// once directly, bypassing the proxy, and once through it. The differential is+// what separates khaos's fault from a merely slow dependency.func (p *Proxy) Observe(ctx context.Context,expected Kind,@@ -106,14 +90,9 @@ func (p *Proxy) Observe(budget := observeGrace + fault.Delay*observeDelayFactor- // The control first. If the dependency cannot be reached without the proxy in- // 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.- //- // 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.+ // The control first: if the dependency is unreachable without the proxy,+ // nothing seen through it is khaos's fault. The test is the absence of+ // BYTES, not an error, because a complete answer always ends in one.direct, directErr := p.measure(ctx, p.upstream, observeGrace)if direct.total == 0 {return "", false, fmt.Errorf(@@ -132,9 +111,7 @@ func (p *Proxy) Observe(return observedHang, true, nil}case Reset:- // ECONNREFUSED is deliberately NOT accepted. Dialling a listener that is- // gone produces exactly that, so accepting it let a CLOSED proxy confirm- // its own fault.+ // ECONNREFUSED is deliberately NOT accepted; see isReset.if isReset(throughErr) {return observedReset, true, nil}@@ -151,9 +128,8 @@ func (p *Proxy) Observe(), 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.+ // Both halves: a count that merely MATCHES the budget is what+ // pass-through delivers when the answer happens to be that long.if through.total == int64(fault.Bytes) && direct.total > through.total {return sprintf(observedPartial,@@ -172,8 +148,7 @@ func (p *Proxy) Observe(}default:- // PassThrough is the absence of a fault and has no observable to- // confirm, so it reaches the unconfirmed return below.+ // PassThrough has no observable, so it falls to the unconfirmed return.}return "", false, nil@@ -183,8 +158,8 @@ func slack(delay time.Duration) time.Duration {return delay * observeSlackNumerator / observeSlackDenominator}-// measure sends one probe to an address and records when the first byte arrived,-// how much arrived in total, and when the peer closed.+// measure records when the first byte arrived, how much arrived, and when the+// peer closed.func (p *Proxy) measure(ctx context.Context,addr string,@@ -227,9 +202,8 @@ func (p *Proxy) measure(}}-// isReset accepts ECONNRESET and deliberately NOT ECONNREFUSED. Dialling a-// listener that is gone produces refused, and accepting it let a CLOSED proxy-// confirm the fault it was holding when it died.+// isReset accepts ECONNRESET and NOT ECONNREFUSED: a gone listener produces+// refused, which would let a CLOSED proxy confirm the fault it died holding.func isReset(err error) bool {return errors.Is(err, syscall.ECONNRESET)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.goindex 5c03cb35..6ffa7423 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxy/proxy.go@@ -19,25 +19,15 @@ import (const (dialTimeout = 5 * time.Second- // A hung connection is held open, not closed, because closing it is a- // different fault. The ceiling exists only so a proxy that is never reverted- // cannot leak the goroutine forever. It is not the rollback: Arm, Disarm and- // Close all free held connections immediately.+ // Only a ceiling, so an unreverted hang cannot leak the goroutine forever.hangCeiling = 10 * time.MinutenoLinger = 0network = "tcp"copyBuffer = 32 * 1024- // How long EOF waits for the target's in-flight request before closing. The- // kernel sends FIN only when the receive queue is empty, so the queue has to- // 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.MilliseconderrWildcard = "%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"@@ -46,9 +36,6 @@ const (probePayload = "GET / HTTP/1.1\r\nHost: khaos.confirm\r\nConnection: close\r\n\r\n"- // Each of these names what khaos measured through its proxy AGAINST what the- // same dependency gave it directly, because only the difference between the- // two paths can be attributed to khaos's own fault.observedHang = "the dependency answers khaos directly but never through its proxy"observedReset = "the dependency answers khaos directly but resets through its proxy"observedEOF = "the dependency answers khaos directly but closes without answering through its proxy"@@ -70,41 +57,23 @@ var ErrClosed = errors.New("the fault proxy is closed")var ErrUnsafeBind = errors.New("khaos will not bind the fault proxy there")-// Proxy is a TCP man-in-the-middle between a target and one of its dependencies,-// modelled on Toxiproxy's per-connection pipeline and credited as such. It holds-// no capabilities and writes no kernel state, so the worst a total failure of it-// can leak is a listener on a high port, and there is nothing for bad targeting-// to reach.-//-// The armed fault is one value swapped atomically, so arming and disarming are-// indivisible and cannot half-apply. That is the property that makes this the-// primary tier rather than a convenience.-// armed is the whole mutable state of the proxy: the fault and the generation it-// belongs to, swapped as one value so a handler can never read a fault from one-// revert and a generation from another.type armed struct {fault Faultgeneration uint64}+// Proxy is a TCP man-in-the-middle, modelled on Toxiproxy. It holds no+// capabilities and writes no kernel state, and the fault is one swapped value.type Proxy struct {upstream stringlistener net.Listenerstate atomic.Pointer[armed]- // Both ends of every exchange are held, and the revert closes both. Closing- // only the client cannot unblock a read parked on the DEPENDENCY, and a- // dependency that accepts and never answers is precisely what research 06- // section 6.1 measured for `docker pause` and `docker network disconnect`.+ // Both ends are held; closing the client cannot unblock the dependency.mu sync.Mutexheld map[net.Conn]struct{}- // inert makes the proxy forward normally while a fault is still armed. It- // exists so the confirmation oracle has a negative control: without a way to- // arm a fault that does NOT happen, every test can only assert that- // confirmation SUCCEEDS, and a confirmation gutted to `return true` satisfies- // all of them. Measured: that gut left all seventeen packages and the Docker- // gate green.+ // inert forwards normally with a fault armed: a negative control.inert atomic.Boolwg sync.WaitGroup@@ -117,11 +86,7 @@ type Proxy struct {probes atomic.Int64}-// Open binds the proxy and refuses an address that would expose it. The-// containment property of this tier is that the listener answers containers and-// nothing else, and that is enforced here rather than left to callers: a-// wildcard bind puts a fault proxy for a dependency under test on the operator's-// network.+// Open binds the proxy and refuses an address that would expose it.func Open(listenAddr, upstream string) (*Proxy, error) {if err := safeBind(listenAddr); err != nil {return nil, err@@ -147,25 +112,14 @@ func Open(listenAddr, upstream string) (*Proxy, error) {return p, nil}-// safeBind enforces the containment property instead of describing it. The-// earlier version refused only a wildcard, which let the proxy bind this host's-// own LAN address: exactly the off-box exposure its error message warns about,-// and useless besides, because a container cannot reach the LAN address anyway.-//-// The test is the routing property, measured rather than guessed from the-// address: the listener must sit on loopback, which is unreachable off the host by-// construction, or on a BRIDGE interface, which is what a container reaches the-// host through. A bridge is identified by its sysfs `bridge` directory, so this-// does not depend on interface naming.+// safeBind tests the routing property rather than the address: loopback, or a+// bridge, identified by its sysfs `bridge` directory rather than by its name.func safeBind(listenAddr string) error {host, portText, err := net.SplitHostPort(listenAddr)if err != nil {return fmt.Errorf(errBadAddr, ErrUnsafeBind, listenAddr, err)}- // No name resolution. A hostname would mean an unbounded resolver lookup on a- // safety check, and khaos is always handed a literal address the daemon- // reported.ip := net.ParseIP(host)if ip == nil || ip.IsUnspecified() {return fmt.Errorf(errWildcard, ErrUnsafeBind, listenAddr)@@ -196,8 +150,6 @@ func safeBind(listenAddr string) error {return nil}-// bridgeHosts reports whether an address belongs to a bridge interface on this-// host.func bridgeHosts(ip net.IP) (bool, error) {interfaces, err := net.Interfaces()if err != nil {@@ -233,9 +185,7 @@ func (p *Proxy) Upstream() string { return p.upstream }func (p *Proxy) Fault() Fault { return p.state.Load().fault }-// Arm swaps the fault in. It also drops every connection currently held open, so-// a target sitting on a pooled keepalive connection established before the fault-// does not keep sailing through it and report a clean survival.+// Arm swaps the fault in and drops held connections, pooled keepalives too.func (p *Proxy) Arm(fault Fault) error {if err := fault.Validate(); err != nil {return err@@ -252,21 +202,13 @@ func (p *Proxy) Arm(fault Fault) error {return nil}-// Disarm returns the proxy to pass-through and releases every connection the-// fault was holding. This is the whole revert.+// Disarm returns to pass-through and releases every held connection.func (p *Proxy) Disarm() {p.swap(Fault{Kind: PassThrough})}-// swap replaces the armed state and releases everything held under the old one,-// as ONE transaction under the mutex.-//-// The fault and the generation have to move together. Storing the fault first and-// advancing the generation afterwards let a handler read the NEW fault with the-// OLD generation, which track then refused, so hold closed the client instead of-// holding it. Measured: 116 of 2000 armed hangs came out as a reset, which is the-// other fault in the catalogue and the one the design doc exists to distinguish-// from it.+// swap replaces the state and releases what the old one held, as ONE+// transaction: a new fault with a stale generation is one track refuses.func (p *Proxy) swap(fault Fault) {p.mu.Lock()@@ -287,8 +229,6 @@ func (p *Proxy) swap(fault Fault) {}// Counts is telemetry for the run record, never evidence that a fault landed.-// Probes are reported separately so khaos's own confirmation traffic is not-// mistaken for the target's.type Counts struct {Accepted int64Severed int64@@ -333,8 +273,7 @@ func (p *Proxy) serve() {if errors.Is(err, net.ErrClosed) {return}- // Backing off matters: a persistent accept error that is neither of- // the above would otherwise spin a core for the whole run.+ // Or a persistent accept error spins a core for the whole run.time.Sleep(drainWindow)continue}@@ -349,16 +288,8 @@ func (p *Proxy) serve() {}}-// handle owns the client connection and re-reads the armed state until it finds-// one that is still current.-//-// A connection accepted just before a revert is handled under the state that was-// armed when it was accepted, and refusing it for staleness is not enough: the-// first attempt at this closed such a connection, and closing one with an unread-// request in its receive queue IS a reset. Measured: 81 of 2000 armed hangs-// arrived at the client as `connection reset by peer`, which is the other fault-// in the catalogue and the one the design doc exists to keep distinguishable.-// Retrying under the current state delivers the fault that is actually armed.+// handle retries under the current armed state rather than closing a stale+// connection: closing one with an unread request in its queue IS a reset.func (p *Proxy) handle(client net.Conn) {defer func() { _ = client.Close() }()@@ -369,8 +300,6 @@ func (p *Proxy) handle(client net.Conn) {default:}- // One load. The fault and the generation it belongs to arrive together, so- // there is no interleaving that pairs a new fault with a stale generation.state := p.state.Load()if p.inert.Load() {@@ -393,26 +322,13 @@ func (p *Proxy) handle(client net.Conn) {}}-// sever reports whether it handled the connection. False means the armed state-// moved underneath it and the caller must try again under the current one.+// sever reports whether it handled the connection; false means try again.func (p *Proxy) sever(client net.Conn, fault Fault, generation uint64) bool {switch fault.Kind {case Reset:- // 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.- //- // Measured at the socket, 20 trials per arm: without this 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. net/http cannot see the difference, reporting a reset at connect- // and one at read as the same error, so it must be measured at the- // socket.+ // SO_LINGER 0 forces the RST but does not decide who sees it: the+ // kernel delivers it once through sk_err and the first syscall to+ // touch the socket clears it, so this wait puts it on the READ.settle(client)if tcp, ok := client.(*net.TCPConn); ok {@@ -422,11 +338,7 @@ func (p *Proxy) sever(client net.Conn, fault Fault, generation uint64) bool {p.severed.Add(1)return truecase EOF:- // The queue has to be drained to the deadline first. The kernel sends FIN- // only when the receive queue is EMPTY and RST when it is not, so closing- // on an unread request yields a reset and makes this a nondeterministic- // duplicate of Reset. Measured: a request larger than one read produced- // ECONNRESET on every attempt until the drain ran to its deadline.+ // The kernel sends FIN only on an empty receive queue, RST otherwise.drain(client)_ = client.Close()p.severed.Add(1)@@ -436,14 +348,7 @@ func (p *Proxy) sever(client net.Conn, fault Fault, generation uint64) bool {}}-// drain empties the receive queue until the deadline expires. Returning on the-// 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.+// settle waits for the target's first write, or for the window.func settle(client net.Conn) {if err := client.SetReadDeadline(time.Now().Add(settleWindow),@@ -455,6 +360,7 @@ func settle(client net.Conn) {_, _ = client.Read(buffer)}+// drain runs to the deadline: a short read is not an empty queue.func drain(client net.Conn) {if err := client.SetReadDeadline(time.Now().Add(drainWindow)); err != nil {return@@ -469,8 +375,7 @@ func drain(client net.Conn) {}}-// hold implements Hang: keep the connection open and answer nothing, until the-// revert drops it or the ceiling expires.+// hold implements Hang: keep the connection open and answer nothing.func (p *Proxy) hold(client net.Conn, generation uint64) bool {if !p.track(generation, client) {return false@@ -486,8 +391,6 @@ func (p *Proxy) hold(client net.Conn, generation uint64) bool {go func() {defer close(gone)- // The target may give up first. Reading tells us when, and a hang must- // not interpret the target's own timeout as something it has to answer._, _ = io.Copy(io.Discard, client)}()@@ -500,15 +403,11 @@ func (p *Proxy) hold(client net.Conn, generation uint64) bool {return true}-// forward reports whether it handled the connection. False means the armed state-// moved underneath it and the caller must try again under the current one.+// forward reports whether it handled the connection; false means try again.func (p *Proxy) forward(client net.Conn, fault Fault, generation uint64) bool {upstream, err := net.DialTimeout(network, p.upstream, dialTimeout)if err != nil {- // The dependency is genuinely unreachable. Passing that through as a- // reset rather than inventing an answer keeps the proxy transparent when- // the real fault is somewhere else, which is what lets a Docker-native- // fault be measured THROUGH a pass-through proxy.+ // Passing the real failure through keeps the proxy transparent.if tcp, ok := client.(*net.TCPConn); ok {_ = tcp.SetLinger(noLinger)}@@ -516,27 +415,12 @@ func (p *Proxy) forward(client net.Conn, fault Fault, generation uint64) bool {}defer func() { _ = upstream.Close() }()- // BOTH ends are tracked, so the revert can close both. Tracking only the- // client deadlocked against a dependency that accepts and never answers: the- // answer leg sat in a read on the dependency, closing the client could not- // unblock it, and nothing closed the dependency until this function returned.- // `khaos run` defers this proxy's Close, so the whole command hung with a- // fault's listener still bound.if !p.track(generation, client, upstream) {return false}defer p.untrack(client, upstream)- // Only LATENCY delays the bytes. slow-close passed fault.Delay to both pumps- // as well as holding the close, so a two second slow-close delayed the- // request two seconds and every response chunk two seconds more, on top of- // the hold. A client with a 500ms timeout then failed before the response- // arrived — and failed for latency while khaos attributed it to the close.- //- // The two faults are supposed to be distinguishable: slow-close exists to- // find a caller that waits for the connection to end instead of reading a- // Content-Length, and that caller must receive its payload promptly or the- // experiment is measuring `network.dependency_latency` under another name.+ // Only LATENCY delays the bytes, or slow-close is latency by another name.chunkDelay := time.Duration(0)if fault.Kind == Latency {chunkDelay = fault.Delay@@ -555,11 +439,7 @@ func (p *Proxy) forward(client net.Conn, fault Fault, generation uint64) bool {p.pump(client, upstream, chunkDelay, limitFor(fault), false)- // The hold belongs to the ANSWER, not to the exchange. Putting it after- // both legs meant a client that keeps its write side open never reached- // it, so the fault could not be confirmed at all; putting it before the- // answer's own half-close is what makes it a slow CLOSE rather than a- // slow everything.+ // The hold belongs to the ANSWER's half-close, not to the exchange.if fault.Kind == SlowClose {select {case <-time.After(fault.Delay):@@ -572,21 +452,13 @@ func (p *Proxy) forward(client net.Conn, fault Fault, generation uint64) bool {}}()- // Both directions have to finish, which is ordinary proxying. Returning on- // the first one closed an answer still in flight, so a half-closing client- // received nothing even through a pass-through proxy, and abandoning the- // request leg delivered a TRUNCATED request to the dependency: measured, a- // target sent 307200 bytes and the dependency received none of them.+ // Both directions must finish, or an answer or a request is truncated.relay.Wait()return true}-// pump copies one direction, optionally delaying each chunk, optionally stopping-// after a byte budget, and optionally half-closing the destination when the-// 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.+// pump delays per chunk, which is a slow dependency, not a slow connection.func (p *Proxy) pump(dst, src net.Conn,delay time.Duration,@@ -635,9 +507,7 @@ func (p *Proxy) pump(}}-// limitFor applies Partial to the DEPENDENCY's answer only. Truncating what the-// target sends would be a different experiment: it would test the dependency,-// which is not the thing under test.+// limitFor applies Partial to the DEPENDENCY's answer only.func limitFor(fault Fault) int {if fault.Kind == Partial {return fault.Bytesdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.goindex 9a2c56c6..6140f9d6 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/proxyfault.go@@ -33,16 +33,14 @@ 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+// ProxyKind is one-to-one with the proxy fault kinds, so the catalogue names// the actual fault rather than a generic "proxy" entry.func ProxyKind(kind proxy.Kind) string {return KindProxyPrefix + string(kind)}-// proxyMutator arms a fault on khaos's in-process proxy. The whole mutation is a-// single atomic pointer swap, which is why this tier cannot half-apply and why-// its rollback cannot partially fail.+// proxyMutator's whole mutation is a single atomic pointer swap, which is why+// this tier cannot half-apply and its rollback cannot partially fail.type proxyMutator struct {kind proxy.Kind}@@ -54,10 +52,8 @@ func init() {}}-// Describe states the fault the operator is about to consent to, with its actual-// magnitude. Reading the kind alone and leaving the parameters at zero printed-// "delay every byte ... by 0s" for a three second latency fault, which is the-// plan line understating the fault it is asking permission for.+// Describe carries the actual magnitude; the kind alone prints a zero where the+// magnitude belongs and understates what it asks permission for.func (m proxyMutator) Describe(env Env, target dockerx.Target) string {fault := env.ProxyFaultif fault.Kind != m.kind {@@ -67,9 +63,8 @@ func (m proxyMutator) Describe(env Env, target dockerx.Target) string {return fmt.Sprintf(describeProxy, fault.Describe(target.Name))}-// 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.+// Plan's payload is also the only durable record of what the run did, since+// the proxy itself dies with the process.func (m proxyMutator) Plan(_ context.Context,env Env,@@ -113,11 +108,8 @@ func (m proxyMutator) Apply(return env.Proxy.Arm(fault)}-// Revert disarms. A cold start has no proxy to disarm, and that is RESOLVED-// rather than failed: the proxy died with the process that held it, so the fault-// 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.+// Revert on a cold start has no proxy to disarm, and that is RESOLVED rather+// than failed: the proxy died with the process, so the fault went with it.func (m proxyMutator) Revert(_ context.Context,env Env,@@ -132,13 +124,9 @@ func (m proxyMutator) Revert(return nil}-// Confirm delegates to the proxy's own socket-level read-back and returns the-// specific observable it measured, so the run record says what was actually seen-// rather than a constant describing the technique. It deliberately does NOT-// compare counters: a counter incremented by the dispatcher records which branch-// 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.+// Confirm returns what the proxy's socket-level read-back measured, never a+// counter: a counter records which branch the dispatcher chose, so it would+// confirm a severing fault while the dependency is fully reachable.func (m proxyMutator) Confirm(ctx context.Context,env Env,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.goindex 8601a6aa..9cd8fca9 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go@@ -41,12 +41,8 @@ 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,-// in-process state rather than something addressable through the daemon, so they-// travel with the environment a mutation is applied in. Nothing else can hand-// either one to a mutator, because they do not exist until the run that owns-// them starts and they stop existing when that run ends.+// Env carries per-run, in-process state, nil and zero for every tier that does+// not use it, because none of it exists outside the run that owns it.type Env struct {Docker *dockerx.ClientProxy *proxy.Proxy@@ -54,38 +50,25 @@ type Env struct {IdP *idp.ProviderIdPTrap idp.Trap- // Authority and PKITrap are the FOURTH injection tier: khaos's own- // certificate authority, playing the dependency whose certificate is under- // test. Like the identity provider it holds no capabilities and serves- // nothing but the target.Authority *pki.AuthorityPKITrap pki.Trap- // Resolver, ResolverNetwork and DNSTrap are the FIFTH injection tier, and- // the only one whose authority is not in khaos's own process.- //- // It could not be. `--dns` carries an address with no port, the daemon- // refuses one at container start, and an unprivileged process cannot bind- // port 53 on any address. So the resolver runs in a container on the- // target's network with nothing published, and khaos holds a CLIENT for it- // rather than the resolver itself. ResolverNetwork travels with it so a- // cold-start revert can find the container again by label.+ // The one authority NOT in khaos's process, so khaos holds a CLIENT for a+ // container. ResolverNetwork travels so a cold-start revert finds it.Resolver *dnsrv.ClientResolverNetwork stringDNSTrap dnsrv.Trap}-// Plan discovers everything the revert will need and returns it so the caller-// can journal it BEFORE Apply runs. Apply consumes that payload rather than-// re-deriving it, so a process killed mid-apply still leaves a journal record-// that fully describes how to put the target back.+// Mutator is one injectable fault. Plan returns what the revert needs so the+// caller can journal it BEFORE Apply runs, and Apply consumes that payload, so+// a process killed mid-apply still leaves a record that undoes the fault.type Mutator interface {Describe(Env, dockerx.Target) stringPlan(context.Context, Env, dockerx.Target) (json.RawMessage, error)Apply(context.Context, Env, dockerx.Target, json.RawMessage) error- // Confirm returns the observable it actually measured along with the verdict.- // A constant describing the technique is not evidence, and the run record has- // to carry what was seen or a reader cannot audit the run.+ // Confirm returns the observable it measured; a constant describing the+ // technique is not evidence.Confirm(context.Context, Env, dockerx.Target) (string, bool, error)Revert(context.Context, Env, journal.Record) error}@@ -95,9 +78,8 @@ var registry = map[string]Mutator{KindDisconnect: disconnectMutator{},}-// Lookup names only the kinds the operator can ask for directly. Listing the-// proxy kinds here sends a typo straight to a kind that a different message then-// refuses, which is two refusals for one mistake.+// Lookup names only the kinds the operator can ask for directly; listing the+// per-run kinds would make one typo produce two different refusals.func Lookup(kind string) (Mutator, error) {mutator, ok := registry[kind]if !ok {@@ -120,13 +102,9 @@ func Kinds() []string {return kinds}-// DirectKinds are the mutations `khaos inject` can apply on its own: the ones-// whose whole subject is a container the daemon can be told about. A proxy fault-// is not one, because it acts on the PATH between a target and its dependency-// and only exists for as long as the run that owns the proxy. An identity-// provider trap is not one either, for the same reason: the provider is a-// goroutine inside the run. Advertising either under `khaos inject` would offer-// a command that cannot succeed.+// DirectKinds are the mutations whose whole subject is a container the daemon+// can be told about. A proxy fault or provider trap only exists inside its own+// run, so advertising one would offer a command that cannot work.func DirectKinds() []string {kinds := make([]string, 0, len(registry))for kind, mutator := range registry {@@ -139,30 +117,21 @@ func DirectKinds() []string {return kinds}-// perRun is implemented by every tier whose authority exists only while the run-// that owns it does, so `khaos inject` can decline to offer a mutation that-// cannot succeed outside a run.-//-// An interface rather than a type switch: a new tier declares itself by-// implementing one method, where a switch has to be remembered. The direct set-// is additionally pinned by name in the tests, because a tier that forgets this-// method is simply absent from anything derived from it.+// perRun is an interface rather than a type switch, so a new tier declares+// itself by implementing one method instead of by being remembered.type perRun interface {Prefix() string}-// inProcess reports whether a mutation acts on state that lives inside the run-// rather than in the daemon. It is derived from the mutator's TYPE rather than-// from the kind's spelling, so a mutation cannot be given an in-process-shaped-// name and then quietly be offered under `khaos inject`, or the reverse.+// inProcess reads the mutator's TYPE, not the kind's spelling, so an+// in-process-shaped name cannot be quietly offered under `khaos inject`.func inProcess(mutator Mutator) bool {_, ok := mutator.(perRun)return ok}// PerRunPrefixes is every prefix belonging to a tier that lives inside a run,-// read out of the registry. A test that needs the list derives it from here-// instead of restating it, which is the specific thing that failed before.+// read out of the registry rather than restated.func PerRunPrefixes() []string {seen := map[string]bool{}@@ -187,10 +156,8 @@ func IsDirect(kind string) bool {return slices.Contains(DirectKinds(), kind)}-// NeedsProxy reports whether a mutation requires the run to stand up khaos's-// in-process fault proxy. It is derived from the registry rather than from the-// kind's spelling, so a mutation cannot be given a proxy-shaped name and then-// quietly fail to get one, or the reverse.+// NeedsProxy is derived from the registry rather than from the kind's+// spelling, so a proxy-shaped name cannot quietly fail to get one.func NeedsProxy(kind string) bool {mutator, ok := registry[kind]if !ok {@@ -200,9 +167,7 @@ func NeedsProxy(kind string) bool {return isProxy}-// NeedsIdP reports whether a mutation requires the run to stand up khaos's own-// identity provider, derived from the registry rather than from the kind's-// spelling for the same reason NeedsProxy is.+// NeedsIdP reports whether a mutation requires khaos's own identity provider.func NeedsIdP(kind string) bool {mutator, ok := registry[kind]if !ok {@@ -236,18 +201,9 @@ type pausePayload struct {AlreadyPaused bool `json:"already_paused"`}-// Plan refuses a target that is already paused.-//-// A paused container still reports Running, so it passes every refusal-// predicate. Docker then rejects the second pause, the session records a failed-// mutation and immediately reverts it, and the revert sees a paused container-// and unpauses it — khaos resuming a container the OPERATOR had paused, as-// cleanup for a fault khaos never applied.-//-// Refusing here rather than recording the precondition is deliberate: khaos-// 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.+// Plan refuses a target that is already paused. A paused container still+// reports Running, so it passes every refusal predicate, and the revert would+// then unpause a container the OPERATOR had paused.func (pauseMutator) Plan(ctx context.Context,env Env,@@ -274,8 +230,8 @@ func (pauseMutator) Apply(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.+// Revert unpauses only what khaos paused, which the journaled precondition+// makes knowable from a cold start.func (pauseMutator) Revert(ctx context.Context,env Env,@@ -416,10 +372,8 @@ func (disconnectMutator) Revert(return err}- // Every attachment is attempted, and the failures are joined. Returning on- // the first one abandoned the rest: a container on three networks that lost- // one of them stayed detached from the other two as well, because the first- // failure ended the loop.+ // Every attachment is attempted and the failures joined, because returning+ // on the first one leaves the container detached from all the rest.var failures []errorfor _, entry := range payload.Attachments {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.goindex fd4fd79b..1f5db72d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/journal/journal.go@@ -60,14 +60,8 @@ type Record struct {LeaseID string `json:"lease_id"`Kind string `json:"kind"`- // Daemon is the Docker daemon this mutation lives on. Without it a container- // ID is ambiguous across machines: reclaiming against another daemon finds- // no such container, reads that as "the target is gone, the fault went with- // it", and marks the record REVERTED. The original fault stays applied on- // the original daemon and is now invisible to every future sweep.- //- // Empty means khaos could not establish it, which is a different state from- // a mismatch and must not be settled automatically.+ // Daemon disambiguates a container ID across machines. Empty means khaos+ // could not establish it, which is not the same as a mismatch.Daemon string `json:"daemon,omitempty"`TargetID string `json:"target_id"`@@ -212,16 +206,8 @@ func Outstanding(path string) ([]Record, error) {order = append(order, record.MutationID)}- // A completed reversion is TERMINAL. Plain last-write-wins let a record- // come back: the reaper reverts a fault and appends Reverted while a- // renewal that read the journal before that is still in flight, and the- // renewal then appends Applied with a fresh expiry from its stale- // snapshot. Replay believed the newer line, so khaos went on renewing a- // lease for a fault that no longer existed, and the next reaper sweep- // would try to revert a target nothing had touched.- //- // Nothing legitimately re-applies a mutation ID: a new fault gets a new- // one. So the first successful reversion ends that ID's life.+ // A completed reversion is TERMINAL: nothing re-applies a mutation ID,+ // and last-write-wins would let a stale renewal resurrect the record.if record.Phase == PhaseReverted {settled[record.MutationID] = true}@@ -279,8 +265,7 @@ func Compact(path string) error {return os.Rename(temp, path)}-// ShortDaemon trims a daemon ID for display, the way container IDs are trimmed.-// The full value stays in the record; this is only for a human reading an error.+// ShortDaemon trims a daemon ID for display; the full value stays in the record.func ShortDaemon(id string) string {if len(id) <= shortDaemonLength {return iddiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.goindex 0afca58c..31e73b33 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/lock/lock_unix.go@@ -80,9 +80,8 @@ func (l *Lock) Release() error {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.+// fd narrows a descriptor for the flock wrapper, which wants an int. RLIMIT_NOFILE+// bounds it far below MaxInt, so the conversion cannot overflow.func fd(file *os.File) int {return int(file.Fd()) //nolint:gosec // bounded by RLIMIT_NOFILE}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.goindex 5bedd660..d1c582b8 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go@@ -23,12 +23,8 @@ const (nameDeepInter = "khaos over-deep intermediate"nameUndelegated = "khaos undelegated responder"- // constrainedDomain is what the name-constrained CA is permitted to issue- // for. Anything else trips Reason 2, which is the fault.constrainedDomain = "constrained.khaos.invalid"- // foreignHost is the name WrongSAN puts in the certificate instead of the- // one the client asked for.foreignHost = "not-the-host-you-asked-for.khaos.invalid"caYears = 10@@ -39,105 +35,60 @@ const ()var (- // ErrNothingArmed is a request for the served chain while the authority is- // behaving correctly and no trap has been armed.+ // ErrNothingArmed is a request for the served chain while behaving correctly.ErrNothingArmed = errors.New("khaos's certificate authority has no fault armed",)- // ErrTrapNotObserved is khaos failing to confirm its OWN fault. It is- // deliberately loud: an unconfirmed fault means the run must not proceed,- // because a measurement under a fault that may not have landed is not- // evidence about the target.+ // ErrTrapNotObserved aborts the run: a measurement under a fault that may+ // not have landed is no evidence.ErrTrapNotObserved = errors.New("khaos could not confirm its own certificate fault landed",))-// Config is how a caller aims the authority. Every field has a working default,-// because an authority that needs configuring before it can serve an honest-// certificate would make the baseline the hard case.type Config struct {- // Host is the name honest certificates are minted for.Host string- // Now overrides the clock, for tests that need a deterministic validity- // window rather than one relative to a real wall clock.Now func() time.Time}-// Authority is khaos's in-process certificate authority: a CA deliberately-// willing to be wrong, in one named way at a time.-//-// It exists because no correct CA will mint an expired, revoked or-// wrongly-named certificate at any price, and those are precisely the-// certificates this family needs. The same argument that justified the in--// process identity provider for tokens justifies this for chains.+// Authority is a CA deliberately willing to be wrong, one named way at a time.type Authority struct {mu sync.RWMutexclock func() time.Timehost string- // The hierarchy the target is configured to trust.root *pairinter *pair- // A second, complete hierarchy khaos also controls. UntrustedCA serves a- // leaf under it while the target still trusts the first; CASwap makes this- // one the root the target trusts, which is the CA-compromise scenario and- // the one fault nothing in a client can detect.rogueRoot *pairrogueInter *pair- // Purpose-built issuers, minted once at construction so that arming a trap- // is cheap, deterministic, and cannot fail for a reason unrelated to the- // fault.constrained *pairekuLimited *pairnotACA *pairundelegated *pair- // deepInter sits under deepCapped, whose MaxPathLen is zero. BOTH have to- // be presented in the handshake: a client given only deepInter cannot reach- // the root at all, and the fault then reads as an unknown authority rather- // than the path-length violation it is. That is measured, not theorised --- // the first draft presented one and the differential caught it.+ // deepCapped has MaxPathLen zero, and BOTH are presented: with only+ // deepInter the client cannot reach the root and Go blames the authority.deepInter *pairdeepCapped *pairtrap Traparmed *Chain- // clientID is the identity khaos has issued to the TARGET, for the mutual- // TLS traps, and mutual is whether khaos demands one. Both are minted and- // set at arm time like everything else the authority serves, so an inert- // authority keeps handing out the honest identity and keeps not demanding- // anything.clientID *pairmutual bool- // swapped is BUILT state, not derived from the trap, and the distinction is- // what makes the confirmation oracle honest.- //- // UntrustedCA and CASwap build the IDENTICAL chain under the rogue- // hierarchy; the only difference between them is what the target trusts. So- // the trusted root cannot come from the chain, and reading it off trap.Kind- // instead meant an INERT authority -- one that records a trap and builds- // nothing -- would report the swap as confirmed. The oracle's negative- // control would have been passing against a fault that never happened.+ // BUILT state: UntrustedCA and CASwap build the identical chain.swapped bool- // inert makes every arming a no-op while still reporting success. It is the- // NEGATIVE CONTROL for the confirmation oracle: without a way to make the- // authority refuse to misbehave, a gutted Observe that always says yes- // leaves the whole suite green. The identity family learned this the- // expensive way.+ // The only way to hand the confirmation oracle an input it MUST reject.inert atomic.Bool- // crlFetches and ocspQueries count what the TARGET asked for. khaos's own- // confirmation probes are counted separately and subtracted, or khaos would- // be measuring itself.+ // What the TARGET asked for, with khaos's own probes counted apart.crlFetches atomic.Int64ocspQueries atomic.Int64ownCRL atomic.Int64@@ -148,10 +99,8 @@ type Authority struct {closed chan struct{}}-// New builds the authority and every CA it will ever need. All of the minting-// happens here rather than at arm time, so a trap that cannot be armed is a-// real fault in the trap and never a key generation that happened to fail-// mid-experiment.+// New builds every CA up front, so a trap that cannot be armed is its own+// fault and never a key generation that failed mid-experiment.func New(cfg Config) (*Authority, error) {a := &Authority{clock: cfg.Now,@@ -231,8 +180,6 @@ func (a *Authority) buildSpecialIssuers() error {return a.buildResponders(from, until)}-// mintCA is the one path every CA in this package comes from, so a defect in-// CA construction cannot differ between the honest hierarchy and a trap's.func (a *Authority) mintCA(name string,parent *pair,@@ -251,13 +198,11 @@ func (a *Authority) mintCA(return issue(template, parent, key)}-// Host is the name honest certificates are minted for.func (a *Authority) Host() string {return a.host}-// TrustedRoot is the anchor the TARGET is configured with. CASwap is the one-// trap that changes what this returns, which is exactly why the trap works.+// TrustedRoot is the anchor the TARGET holds, and CASwap is what moves it.func (a *Authority) TrustedRoot() *x509.Certificate {a.mu.RLock()defer a.mu.RUnlock()@@ -269,7 +214,6 @@ func (a *Authority) TrustedRoot() *x509.Certificate {return a.root.cert}-// TrustedPool is TrustedRoot as a pool, which is what a client actually needs.func (a *Authority) TrustedPool() *x509.CertPool {pool := x509.NewCertPool()pool.AddCert(a.TrustedRoot())@@ -277,20 +221,15 @@ func (a *Authority) TrustedPool() *x509.CertPool {return pool}-// Arm applies a trap and mints the chain it will serve. The chain is built HERE-// rather than per handshake so that every handshake in one experiment presents-// the same certificate: a leaf re-minted per connection would get a new serial-// each time, and a revocation answer about a serial the client is no longer-// holding is not a fault, it is khaos racing itself.+// Arm applies a trap and mints the chain HERE rather than per handshake, so a+// leaf is not re-minted with a new serial while revocation names the old one.func (a *Authority) Arm(trap Trap) error {if err := trap.Validate(); err != nil {return fmt.Errorf(errArmTrap, ErrInvalidTrap, err)}- // An inert authority RECORDS the trap and builds nothing. Recording it is- // deliberate: it makes the confirmation oracle run its real observable- // against honest material, rather than short-circuiting on the- // wrong-trap-armed guard and never reaching the branch under test.+ // An inert authority RECORDS the trap and builds nothing, so the oracle+ // still reaches its observable.if a.inert.Load() {a.mu.Lock()defer a.mu.Unlock()@@ -323,9 +262,8 @@ func (a *Authority) Arm(trap Trap) error {return nil}-// Disarm returns the authority to behaving correctly and re-mints an honest-// chain, so the recovery window is measured through a working authority rather-// than through no authority at all.+// Disarm re-mints an honest chain, so recovery is measured through a working+// authority.func (a *Authority) Disarm() error {honest, err := a.build(Trap{Kind: PassThrough, Host: a.host})if err != nil {@@ -352,13 +290,10 @@ func (a *Authority) Disarm() error {return nil}-// Inert makes arming a no-op that still reports success, which is the only way-// to give the confirmation oracle an input it MUST reject.func (a *Authority) Inert(on bool) {a.inert.Store(on)}-// Trap is what is currently armed.func (a *Authority) Trap() Trap {a.mu.RLock()defer a.mu.RUnlock()@@ -366,7 +301,6 @@ func (a *Authority) Trap() Trap {return a.trap}-// Served is the chain the authority is presenting right now.func (a *Authority) Served() (*Chain, error) {a.mu.RLock()defer a.mu.RUnlock()@@ -378,9 +312,7 @@ func (a *Authority) Served() (*Chain, error) {return a.armed, nil}-// CRLFetches and OCSPQueries report what the TARGET did, with khaos's own-// confirmation probes subtracted. A count that included khaos's probes would-// make "the target checked revocation" true for every run.+// CRLFetches and OCSPQueries report what the TARGET did, probes subtracted.func (a *Authority) CRLFetches() int64 {return a.crlFetches.Load() - a.ownCRL.Load()}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.goindex a29421de..9a928c64 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go@@ -10,79 +10,40 @@ import ()const (- // StrongBits is the modulus khaos mints when it is NOT attacking the key- // size. 2048 is the floor every current policy agrees on, and x509 path- // validation enforces none of them.StrongBits = 2048- // LifetimeCapDays is the CA/Browser Forum maximum leaf lifetime. Nothing- // outside a browser enforces it, which is what ExcessiveLifetime measures.+ // The CA/Browser Forum cap, which nothing outside a browser enforces.LifetimeCapDays = 200- // DefaultLeafDays is an ordinary, unremarkable lifetime for every honest- // certificate khaos serves.DefaultLeafDays = 90- // DefaultWindow is how far a time-based trap moves its boundary when the- // experiment does not say. It is far longer than any plausible clock skew,- // because a fault inside the skew tolerance is not a fault.+ // Far longer than any clock skew: a fault inside the tolerance is none.DefaultWindow = 24 * time.Hour- // DefaultWeakBits is the modulus WeakKey mints by default. Measured on- // go1.26.5: a 1024-bit leaf chains and verifies with a nil error.DefaultWeakBits = 1024- // DefaultExcessiveDays is comfortably past the CABF cap and past every- // shorter policy a target might have adopted instead.DefaultExcessiveDays = 2000- // DefaultHost is the name khaos mints honest certificates for when the- // caller does not say. It is a .invalid name per RFC 2606, so a chain that- // escaped into something real can never resolve.DefaultHost = "dependency.khaos.invalid"- // loopbackSAN is the IP the honest leaf carries so that NoIPSAN has- // something to take away. khaos binds loopback in tests and a bridge- // address in a container, and this SAN only has to exist for the trap to be- // expressible -- the hostname faults are what judge the names.loopbackSAN = "127.0.0.1"- // clockSlack backdates every honest certificate slightly. Without it a leaf- // minted and presented in the same millisecond can land on the wrong side- // of a NotBefore comparison on a machine whose clock ticks between the two,- // which would make the CONTROL flaky and leave khaos unable to establish- // anything.+ // Backdates honest certificates, so one minted and presented at once+ // cannot land on the wrong side of NotBefore.clockSlack = time.Minute)const (- // RouteCRL, RouteOCSP and RouteHealth are the authority's HTTP surface.- //- // RouteHealth exists to be the CONTROL for the two unreachable traps. Its- // whole job is to stay up while the CRL or OCSP endpoint refuses, because- // "khaos broke one endpoint" and "khaos fell over" are different claims and- // only the first one is a fault.+ // RouteHealth keeps answering while CRL or OCSP refuses, so khaos can show+ // it broke one endpoint rather than fell over.RouteCRL = "/crl"RouteOCSP = "/ocsp"RouteHealth = "/healthz"- // RouteRoot serves the DER of the root the TARGET is configured to trust,- // which is how a client discovers its trust anchor from a running- // authority.- //- // It exists because CASwap is otherwise inexpressible. That fault replaces- // the anchor at ARM time, after the target started, so a target that- // baked a root in at startup could never experience it. Serving the anchor- // here and having the target read it per request is what a substituted- // trust store actually is: managed out of band, and changed without the- // application being asked.+ // Read per request, because CASwap replaces the anchor at arm time.RouteRoot = "/root")-// Kinds is the whole catalogue, in the order the research groups it: validity,-// identity, authority, algorithm, policy, CRL revocation, OCSP revocation,-// stapling, trust store. Tests census against this, so a new trap without a-// case of its own turns them red.func Kinds() []string {return []string{string(LeafExpired),@@ -135,19 +96,9 @@ func joinKinds() string {return strings.Join(Kinds(), trapSep)}-// GoAccepts reports whether go1.26.5's own certificate verification returns a-// NIL error for this trap. It is the single most important predicate in the-// package, because it decides what a target's acceptance MEANS.-//-// For a trap Go refuses, an acceptance proves the target weakened or skipped-// verification. For a trap Go accepts, an acceptance proves nothing of the-// kind: there was no check to skip, and the finding is that the target has no-// policy of its own. Reporting the second as the first would be khaos accusing-// a target of a defect that only exists in the operator's expectations.-//-// Every entry here was measured, not assumed; research 04's fault table records-// the run, and the CRL and SHA-1 rows were re-measured on this box before this-// family was built.+// GoAccepts reports whether go1.26.5's own verification returns a NIL error+// for this trap, which decides what an acceptance means: for a trap Go+// refuses, the target skipped a check; for one Go accepts, there was none.func GoAccepts(kind Kind) bool {switch kind {case WeakKey, ExcessiveLifetime, KeyUsageWithoutDigitalSignature,@@ -158,10 +109,7 @@ func GoAccepts(kind Kind) bool {return truecase ClientCertExpired, ClientCertAbsent:- // The DEPENDENCY's certificate is impeccable for both of these, so- // crypto/x509 has no objection to it: the defect is in the target's own- // identity and the rejection happens on khaos's side of the connection.- // Go accepts the chain, and then the server refuses the client.+ // The DEPENDENCY's certificate is impeccable; khaos rejects the client.return truecase PassThrough, LeafExpired, LeafNotYetValid, IntermediateExpired,@@ -172,16 +120,14 @@ func GoAccepts(kind Kind) bool {return falsedefault:- // An unknown kind is treated as refused, which is the conservative- // direction: it makes khaos claim LESS about a target than it could.+ // An unknown kind is refused, which claims less about a target.return false}}-// Describe states the trap with its actual magnitude, for the consent prompt-// and the plan output. The identity family established that a description-// naming a parameter without its VALUE is worse than none, because the operator-// approves a sentence and then gets a different fault.+// Describe states the trap with its actual magnitude, for the consent prompt.+// Naming a parameter without its value would have the operator approve one+// sentence and get a different fault.func (t Trap) Describe(target string) string {switch t.Kind {case LeafExpired, LeafNotYetValid, IntermediateExpired, WrongSAN,@@ -211,8 +157,6 @@ func (t Trap) Describe(target string) string {}}-// describeSubject covers the faults in WHEN the certificate is valid and WHO it-// is for.func (t Trap) describeSubject(target string) string {switch t.Kind {case LeafExpired:@@ -234,8 +178,6 @@ func (t Trap) describeSubject(target string) string {}}-// describeChain covers the faults in the path from leaf to trusted root, plus-// the two that are structurally the same question about signing and usage.func (t Trap) describeChain(target string) string {switch t.Kind {case SelfSigned:@@ -263,8 +205,6 @@ func (t Trap) describeChain(target string) string {}}-// describePolicy covers the faults crypto/x509 ACCEPTS, where the finding is-// the absence of a policy rather than a skipped check.func (t Trap) describePolicy(target string) string {switch t.Kind {case WeakKey:@@ -281,8 +221,6 @@ func (t Trap) describePolicy(target string) string {}}-// describeRevocation covers everything that acts on revocation rather than on-// the certificate.func (t Trap) describeRevocation(target string) string {switch t.Kind {case RevokedViaCRL:diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.goindex c7be36c9..90ed82a8 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go@@ -9,61 +9,34 @@ import ("crypto/x509")-// Chain is one assembled certificate chain as it will be PRESENTED in a-// handshake, together with what revocation needs in order to talk about it.-//-// Presented and Issuer are separate fields on purpose, and the distinction is-// the whole of the MissingIntermediate fault: the server can withhold a CA from-// the handshake while that CA is still the one that signed the leaf and still-// the one whose CRL covers it. Collapsing them would make that fault-// inexpressible.+// Chain is one chain as it will be PRESENTED in a handshake. Issuer is kept+// apart from presented so a CA can be withheld from the handshake while still+// signing the leaf and the CRL that covers it.type Chain struct {- // Leaf is the served certificate.Leaf *x509.CertificateleafDER []byteleafKey crypto.Signer- // presented is the intermediate DER the handshake carries, leaf-first- // ordering excluded. It can be empty even when the real chain has an- // intermediate.+ // Can be empty even when the real chain has an intermediate.presented [][]byte- // Issuer signed the leaf. Revocation answers are always issued by this,- // even when the handshake withholds it.Issuer *x509.CertificateissuerKey crypto.Signer- // Root is the anchor a correct client needs to verify this chain. For- // CASwap it is a root khaos minted rather than the one the target was- // originally given.Root *x509.Certificate- // Staple is the DER OCSP response stapled into the handshake, or nil for no- // staple at all. Go never parses this; it is delivered to the application- // verbatim, which is what makes both stapling faults reachable.+ // Go never parses this; the application receives it verbatim.Staple []byte- // crl and ocsp are the bytes the endpoints serve, minted at ARM time and- // served verbatim.- //- // They live here rather than being minted per request for two reasons. A- // real CA publishes a revocation list and does not regenerate it for each- // fetch, so a freshness window that slid forward on every request was- // wrong on its own terms. And minting from the trap at request time meant- // an INERT authority -- one that records a trap and builds nothing -- still- // served a revoked list, so thirteen traps confirmed against a fault that- // never happened. The oracle's negative control caught it.+ // Minted at ARM time, as a real CA publishes a list rather than per fetch.crl []byteocsp []byte- // crlOut and ocspOut say whether each endpoint answers at all. Built state- // for the same reason, since an unreachable endpoint cannot be expressed in- // pre-minted bytes.+ // An unreachable endpoint cannot be expressed in pre-minted bytes.crlOut boolocspOut bool}-// CRL and OCSP are what the endpoints serve for this chain.func (c *Chain) CRL() ([]byte, bool) {return c.crl, !c.crlOut}@@ -72,8 +45,6 @@ func (c *Chain) OCSP() ([]byte, bool) {return c.ocsp, !c.ocspOut}-// TLS is the chain as crypto/tls wants it: leaf first, then whatever-// intermediates the server is willing to admit to.func (c *Chain) TLS() tls.Certificate {certificate := tls.Certificate{Certificate: append([][]byte{c.leafDER}, c.presented...),@@ -88,8 +59,6 @@ func (c *Chain) TLS() tls.Certificate {return certificate}-// RootPool is the trust anchor set a correct client needs for this chain. It is-// what the range hands its reference client, and what CASwap quietly changes.func (c *Chain) RootPool() *x509.CertPool {pool := x509.NewCertPool()if c.Root != nil {@@ -98,16 +67,11 @@ func (c *Chain) RootPool() *x509.CertPool {return pool}-// Presented is how many intermediates the handshake actually carries, which is-// the observable MissingIntermediate is confirmed by.func (c *Chain) Presented() int {return len(c.presented)}-// PresentedPool is the intermediate set a client receives in the handshake, and-// therefore the only one it may use to build a path. Supplying khaos's real-// intermediate here instead would quietly repair MissingIntermediate, which is-// the mistake that makes that fault untestable.+// Supplying khaos's real intermediate here would repair MissingIntermediate.func (c *Chain) PresentedPool() (*x509.CertPool, error) {pool := x509.NewCertPool()diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.goindex 2757812f..6cb5b9ff 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go@@ -11,12 +11,8 @@ import ("golang.org/x/crypto/ocsp")-// build assembles the chain for one trap. Every trap starts from the HONEST-// leaf template and corrupts exactly one property of it, which is the same-// discipline the token family uses and for the same reason: a certificate that-// is wrong twice trips two checks and isolates neither.-//-// The groups are the ones research 04 uses, and each is confirmed differently.+// Every trap starts from the HONEST leaf template and corrupts exactly one+// property of it, because a certificate wrong twice isolates neither check.func (a *Authority) build(trap Trap) (*Chain, error) {now := a.clock()@@ -30,11 +26,8 @@ func (a *Authority) build(trap Trap) (*Chain, error) {return nil, err}- // EVERY chain staples, not just the stapling traps. A well-configured- // server staples, so the honest chain has to as well: if only the stapling- // faults produced one, then StapleAbsent would serve exactly what the- // baseline serves and the fault would be inert. The control test for this- // file is what caught that.+ // EVERY chain staples, not just the stapling traps, or StapleAbsent would+ // serve exactly what the baseline serves and the fault would be inert.if chain, err = a.staple(trap, chain, now); err != nil {return nil, err}@@ -42,9 +35,6 @@ func (a *Authority) build(trap Trap) (*Chain, error) {return a.publish(trap, chain, now)}-// publish mints the revocation artefacts this chain's endpoints will serve, at-// ARM time, so that everything the authority does under a trap is decided here-// and nothing is derived from the trap record at request time.func (a *Authority) publish(trap Trap,chain *Chain,@@ -61,9 +51,6 @@ func (a *Authority) publish(chain.crl = listif trap.Kind == OCSPTryLater {- // A protocol-level refusal rather than a transport one. The responder- // IS reachable and IS answering; it is declining to say, which is the- // exact shape that exploits a soft-failing client.chain.ocsp = ocsp.TryLaterErrorResponsereturn chain, nil@@ -117,14 +104,6 @@ func (a *Authority) chainFor(}}-// honest is the control every other chain is compared against: a correctly-// signed, in-date leaf under the trusted intermediate, naming both revocation-// endpoints so that a target which WANTS to check revocation can.-//-// Carrying the pointers on the honest chain matters. If only the revocation-// traps named a responder, then "the target queried OCSP" would be true only-// when khaos was already attacking it, and the baseline could never establish-// that the target checks revocation at all.func (a *Authority) honest(host string, now time.Time) (*Chain, error) {template, err := a.leaf(host, now, DefaultLeafDays)if err != nil {@@ -134,8 +113,8 @@ func (a *Authority) honest(host string, now time.Time) (*Chain, error) {return a.assemble(template, a.inter, a.root.cert, StrongBits, true)}-// leaf is the honest template plus the revocation pointers, which depend on the-// configured base URL rather than on wherever khaos happens to be listening.+// The honest leaf names both revocation endpoints too, or "the target queried+// OCSP" would be true only when khaos was already attacking it.func (a *Authority) leaf(host string,now time.Time,@@ -154,9 +133,7 @@ func (a *Authority) leaf(return template, nil}-// assemble mints the leaf and wraps it with what the handshake and revocation-// both need. presentChain says whether the intermediate is admitted to the-// handshake, which is the entire MissingIntermediate fault.+// presentChain is the entire MissingIntermediate fault.func (a *Authority) assemble(template *x509.Certificate,issuer *pair,@@ -190,10 +167,6 @@ func (a *Authority) assemble(return chain, nil}-// buildValidity moves a NotBefore or NotAfter. Both leaf faults come back as-// InvalidReason 1 with no separate not-yet-valid reason, so the only thing-// distinguishing them is the Detail wording, and the experiments assert on that-// rather than on the reason alone.func (a *Authority) buildValidity(trap Trap,host string,@@ -212,9 +185,7 @@ func (a *Authority) buildValidity(switch trap.Kind {case LeafExpired:- // Internally consistent: the certificate is expired and nothing else.- // Its NotBefore moves with its NotAfter so it was never also- // not-yet-valid, which would trip the same reason for the other cause.+ // NotBefore moves with NotAfter, so it is expired and nothing else.template.NotBefore = now.Add(-window - DefaultWindow)template.NotAfter = now.Add(-window)@@ -223,15 +194,13 @@ func (a *Authority) buildValidity(template.NotAfter = now.Add(window).AddDate(0, 0, DefaultLeafDays)default:- // Unreachable: build routes only the validity group here.+ // Every other kind leaves the validity window honest.}return a.assemble(template, a.inter, a.root.cert, StrongBits, true)}-// underExpiredCA mints an in-date leaf under an intermediate that has expired.-// The leaf is deliberately blameless: monitoring that watches leaf expiry only-// sees nothing wrong, which is the fail-open this catches.+// The leaf is deliberately blameless, so leaf-expiry monitoring sees nothing.func (a *Authority) underExpiredCA(host string,now time.Time,@@ -264,9 +233,6 @@ func (a *Authority) underExpiredCA(return a.assemble(leaf, expired, a.root.cert, StrongBits, true)}-// buildIdentity corrupts who the certificate is FOR. All three are-// HostnameError, which carries no reason code, so the experiments assert on the-// error type and on which name the certificate actually carries.func (a *Authority) buildIdentity(trap Trap,host string,@@ -283,30 +249,21 @@ func (a *Authority) buildIdentity(template.Subject = pkix.Name{CommonName: foreignHost}case CommonNameOnly:- // No SAN extension at all, with the host named only in the legacy- // CommonName. Go removed the CommonName fallback outright, so this- // produces a DIFFERENT message from a plain mismatch: it names the- // legacy field, which is the teaching point.+ // Go removed the CommonName fallback, so this is not a plain mismatch.template.DNSNames = niltemplate.Subject = pkix.Name{CommonName: host}case NoIPSAN:- // Named by DNS but carrying no IP SAN, so a client that dials by- // address has nothing to match against. The fail-open is a service- // dialled by pod IP with verification disabled because it is internal.template.DNSNames = []string{host}template.IPAddresses = nildefault:- // Unreachable: build routes only the identity group here.+ // Every other kind leaves the identity fields honest.}return a.assemble(template, a.inter, a.root.cert, StrongBits, true)}-// buildChainFault breaks the path from leaf to trusted root. Three of these-// produce a BYTE-IDENTICAL client error and the experiments exist to tell them-// apart by what khaos knows it served, never by the string.func (a *Authority) buildChainFault(trap Trap,host string,@@ -322,8 +279,6 @@ func (a *Authority) buildChainFault(return a.selfSigned(template)case UntrustedCA:- // Signed by khaos's OTHER complete hierarchy. The chain is internally- // valid and simply anchors somewhere the target does not trust.return a.assemble(template,a.rogueInter,@@ -333,8 +288,6 @@ func (a *Authority) buildChainFault()case MissingIntermediate:- // A perfectly good chain with the intermediate withheld from the- // handshake. Works in a browser that chases AIA, fails in Go.return a.assemble(template, a.inter, a.root.cert, StrongBits, false)case IssuerNotCA:@@ -353,19 +306,12 @@ func (a *Authority) buildChainFault(return a.overDeep(template)default:- // Unreachable: build routes only the chain group here.return a.honest(host, now)}}-// overDeep serves a leaf two intermediates below the root, under a CA whose-// MaxPathLen is zero.-//-// BOTH intermediates are presented. A handshake carrying only the lower one-// leaves the client unable to reach the root at all, and Go then reports an-// unknown authority rather than the path-length violation: the fault would-// still fail the connection, for a reason khaos did not inject and could not-// attribute. The differential caught exactly that in the first draft.+// BOTH intermediates are presented. With only the lower one the client cannot+// reach the root, and Go reports an unknown authority instead.func (a *Authority) overDeep(template *x509.Certificate,) (*Chain, error) {@@ -385,20 +331,11 @@ func (a *Authority) overDeep(return chain, nil}-// selfSigned signs the leaf with its own key, which needs the CA bits on the-// template because Go refuses to let a non-CA certificate sign anything,-// including itself.func (a *Authority) selfSigned(template *x509.Certificate,) (*Chain, error) {- // CertSign because Go refuses to let a non-CA certificate sign anything,- // including itself. CRLSign because this leaf is its OWN issuer, so it is- // also the thing that has to sign the CRL covering it, and- // CreateRevocationList refuses an issuer without that bit.- //- // Omitting CRLSign made the CRL endpoint answer 500 for this trap, which- // reached the client as "no usable revocation answer was obtained" -- a- // refusal caused by khaos rather than by the fault. The matrix caught it.+ // CertSign because Go refuses to let a non-CA sign anything, itself+ // included. CRLSign because this leaf is its own issuer and signs its CRL.template.IsCA = truetemplate.BasicConstraintsValid = truetemplate.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign@@ -423,9 +360,6 @@ func (a *Authority) selfSigned(}, nil}-// buildAlgorithm corrupts how the certificate is signed or what it is permitted-// to be used for. Two of the three surface as an authority failure unless the-// caller unwraps the error, which is itself the finding.func (a *Authority) buildAlgorithm(trap Trap,host string,@@ -438,17 +372,13 @@ func (a *Authority) buildAlgorithm(switch trap.Kind {case SHA1Signature:- // Measured on go1.26.5: CreateCertificate emits this without- // complaint and Verify refuses it, wrapping InsecureAlgorithmError- // inside UnknownAuthorityError.template.SignatureAlgorithm = x509.SHA1WithRSAcase EKUClientAuthOnly:template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}case EKUConstrainedIntermediate:- // The LEAF is blameless here. The constraint is on the CA above it,- // which is what separates this from the leaf-level EKU fault.+ // The LEAF is blameless; the constraint is on the CA above it.return a.assemble(template,a.ekuLimited,@@ -458,16 +388,12 @@ func (a *Authority) buildAlgorithm()default:- // Unreachable: build routes only the algorithm group here.+ // Every other kind leaves the signature algorithm honest.}return a.assemble(template, a.inter, a.root.cert, StrongBits, true)}-// buildPolicy mints the certificates Go ACCEPTS. Verify returns nil for all-// three, so they do not test x509 at all -- they test whether the target-// imposed a floor of its own, and an acceptance here is not proof of a skipped-// check because there was no check to skip.func (a *Authority) buildPolicy(trap Trap,host string,@@ -490,23 +416,15 @@ func (a *Authority) buildPolicy(}if trap.Kind == KeyUsageWithoutDigitalSignature {- // Verify enforces EXTENDED key usage, nested down the chain, and does- // not look at the basic KeyUsage bits on a leaf at all. A leaf without- // digitalSignature is unusable for TLS per RFC 5280 and Go will not say- // a word about it.+ // Verify enforces EXTENDED key usage down the chain and never looks at+ // the basic KeyUsage bits RFC 5280 requires of a TLS leaf.template.KeyUsage = x509.KeyUsageCRLSign}- // bits, not StrongBits. Passing the constant here is what the first draft- // did, and it made WeakKey mint a 2048-bit key: the trap armed, reported- // success, and served a certificate with nothing wrong with it.+ // bits, not StrongBits, or WeakKey arms and serves a strong key.return a.assemble(template, a.inter, a.root.cert, bits, true)}-// buildCASwap serves a chain that is VALID under a root khaos controls, having-// made that root the one the target trusts. Nothing in the client can detect-// it, which is the point: the only defences are pinning and certificate-// transparency, and neither is in crypto/x509.func (a *Authority) buildCASwap(host string,now time.Time,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.goindex c9d7e477..8c8153ef 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go@@ -9,18 +9,6 @@ import ("time")-// The purpose-built issuers. Each one is a CA that is wrong in exactly one-// structural way, minted once at construction.-//-// They are separate certificates rather than mutations of the honest-// intermediate because the fault is IN THE ISSUER for all four: a leaf cannot-// express "my CA is constrained against my name" or "my CA is not a CA" by-// anything it carries itself.--// buildConstrained is a CA carrying PermittedDNSDomains. A leaf it signs for-// any other name trips InvalidReason 2, CANotAuthorizedForThisName. The-// fail-open this catches is a constrained corporate sub-CA that a verifier lets-// issue for anything.func (a *Authority) buildConstrained(from, until time.Time) error {template, err := caTemplate(nameConstrained, from, until)if err != nil {@@ -40,13 +28,8 @@ func (a *Authority) buildConstrained(from, until time.Time) error {return err}-// buildEKULimited is a CA authorised for client authentication only. Go checks-// extended key usage NESTED DOWN THE CHAIN, so a perfectly ordinary serverAuth-// leaf under this CA is refused with InvalidReason 4, IncompatibleUsage — the-// same reason as the leaf-level fault, because `crypto/x509` declares-// CANotAuthorizedForExtKeyUsage and never constructs it. The leaf itself is-// blameless, which is what makes the two faults distinct despite the identical-// error.+// Go checks EKU NESTED DOWN THE CHAIN, so a blameless serverAuth leaf under+// this client-auth-only CA is refused with Reason 4.func (a *Authority) buildEKULimited(from, until time.Time) error {template, err := caTemplate(nameEKULimited, from, until)if err != nil {@@ -65,11 +48,7 @@ func (a *Authority) buildEKULimited(from, until time.Time) error {return err}-// buildNotACA is a certificate with basic constraints saying it is NOT a CA,-// which khaos then signs a leaf with anyway. Go reports this as-// UnknownAuthorityError wrapping ConstraintViolationError, so a caller that-// only reads the outer error sees "unknown authority" and learns nothing about-// the real defect.+// Reported as UnknownAuthorityError wrapping ConstraintViolationError.func (a *Authority) buildNotACA(from, until time.Time) error {number, err := serial()if err != nil {@@ -84,20 +63,11 @@ func (a *Authority) buildNotACA(from, until time.Time) error {IsCA: false,BasicConstraintsValid: true,- // CRLSign despite IsCA being false, because this certificate is still- // the issuer of the leaf it signs and therefore still the thing that- // signs the CRL covering it. CreateRevocationList refuses an issuer- // without the bit, and without it the CRL endpoint answered 500 and the- // client refused for khaos's reason instead of the fault's.- //- // The fault is unaffected: IsCA is still false, which is the defect.+ // CRLSign despite IsCA false: it still signs its own leaf's CRL.KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign,- // Set BY HAND, because Go computes a SubjectKeyId automatically only- // while creating a CA certificate and this one is deliberately not a- // CA. CreateRevocationList reads the identifier from the parsed issuer- // and refuses an issuer without one, so a CRL for this chain could not- // be minted at all and the endpoint answered 500.+ // Set BY HAND: Go computes a SubjectKeyId only while creating a CA, and+ // CreateRevocationList refuses an issuer without one.SubjectKeyId: []byte(nameNotACA),}@@ -111,13 +81,7 @@ func (a *Authority) buildNotACA(from, until time.Time) error {return err}-// buildDeepInter sits one level below an intermediate whose MaxPathLen is zero,-// so a leaf under it exceeds the path length the CA above permits and trips-// InvalidReason 3, TooManyIntermediates.-//-// The pathLen-0 CA is minted here too rather than reusing the honest-// intermediate, because setting MaxPathLen on the honest one would constrain-// every other trap in the family.+// One level below a pathLen-0 CA, so a leaf under it trips Reason 3.func (a *Authority) buildDeepInter(from, until time.Time) error {capped, err := caTemplate(nameInter, from, until)if err != nil {@@ -151,21 +115,9 @@ func (a *Authority) buildDeepInter(from, until time.Time) error {return err}-// buildResponders mints the ONE OCSP signer khaos needs to hold: a certificate-// the CA never issued.-//-// There is no delegated responder here any more. Every honest response is-// signed by the chain's own issuer, acting as its own responder, which RFC 6960-// section 2.6 permits and which is the only arrangement that is consistent with-// EVERY chain this authority serves. A single delegated responder cannot be,-// because seven traps serve a chain under a different CA entirely, and the-// matrix caught six of them being refused for khaos's own mismatch.-//-// The undelegated signer stays, because OCSPWrongSigner is the fault that-// exercises delegation from the other side. It is self-signed rather than-// issued by the rogue hierarchy, so a client that happens to trust the rogue-// root -- because CASwap ran earlier in the same session -- still cannot be-// fooled by it.+// The one OCSP signer khaos holds: a certificate the CA never issued. Honest+// responses are signed by the chain's own issuer instead, which is the only+// arrangement every chain this authority serves is consistent with.func (a *Authority) buildResponders(from, until time.Time) error {rogue, err := caTemplate(nameUndelegated, from, until)if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.goindex 964b2459..ee8eb3e3 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go@@ -25,28 +25,16 @@ const (errSerial = "%w: drawing a serial: %v")-// ErrMint is any failure to produce the certificate material a trap needs. It-// is deliberately distinct from a trap that armed and then behaved wrongly:-// this one means khaos could not express the fault at all.var ErrMint = errors.New("khaos could not mint the certificate material")-// pair is a certificate with the key that goes with it, always re-parsed from-// its own DER.-//-// The re-parse is not defensive tidiness. x509.CreateRevocationList requires-// the issuer to have SubjectKeyId set and reads it from the PARSED certificate,-// ignoring whatever the template said, and Go only computes a SubjectKeyId-// while creating a CA certificate. Holding the template would produce a CA that-// cannot issue a CRL, which is most of this family.+// pair is always re-parsed from its own DER: CreateRevocationList reads+// SubjectKeyId from the PARSED certificate and ignores the template.type pair struct {cert *x509.Certificateder []bytekey crypto.Signer}-// rsaKeyOf recovers the concrete RSA key from a pair. Every key this package-// mints is RSA, so a failed assertion is a bug in this file rather than-// something a caller can cause.func rsaKeyOf(p *pair) *rsa.PrivateKey {key, ok := p.key.(*rsa.PrivateKey)if !ok {@@ -75,10 +63,6 @@ func serial() (*big.Int, error) {return n, nil}-// issue signs template with parent, or self-signs it when parent is nil, and-// returns the result re-parsed. The signing key is the PARENT's, which is what-// makes a self-signed leaf and a CA-signed leaf one code path with one-// difference.func issue(template *x509.Certificate,parent *pair,@@ -121,9 +105,7 @@ func issue(return &pair{cert: cert, der: der, key: subject}, nil}-// caTemplate is every CA khaos mints. crlSign is set on all of them because-// CreateRevocationList refuses an issuer without it, and a CA that cannot-// revoke could not host most of this catalogue.+// Every CA gets crlSign, because CreateRevocationList refuses one without it.func caTemplate(name string, from, until time.Time) (*x509.Certificate,error,@@ -146,9 +128,6 @@ func caTemplate(name string, from, until time.Time) (}, nil}-// leafTemplate is an HONEST leaf. Every defect in this family is expressed by-// mutating what this returns, so anything wrong with it is wrong with the-// control too, and a control that is already broken cannot establish anything.func leafTemplate(host string, now time.Time, days int) (*x509.Certificate,error,@@ -163,10 +142,7 @@ func leafTemplate(host string, now time.Time, days int) (Subject: pkix.Name{CommonName: host},DNSNames: []string{host},- // The honest leaf carries a loopback IP SAN so that NoIPSAN has- // something to REMOVE. Without it the honest certificate has no IP SANs- // either, that trap serves material identical to the control, and its- // observable confirmed against an authority that armed nothing.+ // A loopback IP SAN, so NoIPSAN has something to REMOVE.IPAddresses: []net.IP{net.ParseIP(loopbackSAN)},NotBefore: now.Add(-clockSlack),diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.goindex 9e4abd97..f4bfe48a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go@@ -12,13 +12,7 @@ import ()const (- // RouteIdentity serves the CLIENT certificate and key khaos has issued to- // the target, as PEM.- //- // khaos issues the target's identity because khaos is the CA for both ends,- // which is how a service mesh actually works and the only arrangement in- // which khaos can make that identity wrong. A target holding a certificate- // khaos did not issue is a target khaos cannot inject an mTLS fault into.+ // khaos is the CA for both ends, the only way it can make this wrong.RouteIdentity = "/identity"nameClient = "khaos range client"@@ -29,55 +23,27 @@ const (mimePEM = "application/x-pem-file")-// RequiresMutualTLS reports whether the armed trap makes khaos demand a client-// certificate.-//-// It is read per handshake rather than fixed at bind time, through-// GetConfigForClient, because arming a trap has to take effect on the next-// connection without the listener moving. A ClientAuth fixed at bind time would-// mean the mTLS traps could only be armed before the range was pointed at-// khaos, which is not when an experiment arms anything.+// Read per handshake through GetConfigForClient, because a ClientAuth fixed at+// bind time could only be armed before the range was pointed at khaos.func (a *Authority) RequiresMutualTLS() bool {a.mu.RLock()defer a.mu.RUnlock()- // BUILT state, not read off the trap. An inert authority -- one that- // records a trap and builds nothing -- would otherwise report that it- // demands mutual TLS and is issuing no identity, which is both halves of- // the client-cert-absent observable satisfied by a fault that never- // happened. The oracle's negative control caught exactly that, for the- // second time in this package and for the identical reason.return a.mutual}-// ClientIdentity is the certificate and key khaos has issued to the target-// right now, or false when it is issuing none.-//-// Withholding it IS the ClientCertAbsent fault. Research 04 is explicit that-// this is the more dangerous of the two: an attacker does not present a bad-// certificate, they present nothing, and the ClientAuth mode that rejects a bad-// one while accepting none reads as secure and fails completely open.+// Withholding the identity IS the ClientCertAbsent fault.func (a *Authority) ClientIdentity() (*pair, bool) {a.mu.RLock()defer a.mu.RUnlock()- // Built state again. Withholding the identity is expressed by there BEING- // no identity, not by a flag consulted at serve time, so an authority that- // built nothing keeps handing out the honest one.return a.clientID, a.clientID != nil}-// mintClientIdentity issues the target's own certificate. It is called at arm-// time like everything else the authority serves, so an inert authority -- one-// that records a trap and builds nothing -- keeps serving the honest identity-// and the oracle's negative control holds.func (a *Authority) mintClientIdentity(trap Trap,now time.Time,) (*pair, error) {- // NOTHING, which is the whole of the absent fault. A nil identity here is- // how "khaos issues the target none" is represented, so it cannot be- // confused with an authority that simply has not built one yet.if trap.Kind == ClientCertAbsent {return nil, nil}@@ -91,9 +57,7 @@ func (a *Authority) mintClientIdentity(until := now.AddDate(0, 0, DefaultLeafDays)if trap.Kind == ClientCertExpired {- // Moved TOGETHER, so the identity is expired and nothing else. One that- // was also not-yet-valid would be refused for either reason and khaos- // could not say which.+ // Moved TOGETHER, so the identity is expired and nothing else.window := trap.window()from = now.Add(-window - DefaultWindow)until = now.Add(-window)@@ -106,9 +70,7 @@ func (a *Authority) mintClientIdentity(NotAfter: until,KeyUsage: x509.KeyUsageDigitalSignature,- // clientAuth, not serverAuth. An identity presented as a client has to- // be permitted for it, or khaos's own server refuses it for the wrong- // reason and the fault is unattributable.+ // clientAuth, or khaos's server refuses it for the wrong reason.ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},BasicConstraintsValid: true,}@@ -121,18 +83,12 @@ func (a *Authority) mintClientIdentity(return issue(template, a.inter, key)}-// serveIdentity hands the target its own certificate and key.-//-// Serving a private key over plain HTTP is indefensible in anything but a-// fixture whose whole purpose is to be broken, and it is what makes the mTLS-// faults injectable at all: khaos has to be able to change the identity the-// target presents, which means khaos has to be the one handing it over.+// Serving a private key over plain HTTP is defensible only in a fixture whose+// purpose is to be broken, and is what makes the mTLS faults injectable.func (a *Authority) serveIdentity(w http.ResponseWriter, _ *http.Request) {identity, issuing := a.ClientIdentity()if !issuing {- // Not an error. khaos is deliberately issuing nothing, and a target- // that treats "no identity available" as a reason to connect anyway is- // exactly what this fault is looking for.+ // Not an error: a target that connects anyway is the finding.w.WriteHeader(http.StatusNotFound)return@@ -152,12 +108,8 @@ func (a *Authority) serveIdentity(w http.ResponseWriter, _ *http.Request) {})}-// observeMutual confirms the two mutual TLS faults.-//-// BOTH halves, every time. khaos has to be demanding a client certificate AND-// the identity it issued has to be wrong, because either alone is not the-// fault: a server that does not require mTLS rejects nobody, and a bad identity-// nobody is asked for is never presented.+// Both halves, every time: a server that requires nothing rejects nobody, and+// an identity nobody is asked for is never presented.func (a *Authority) observeMutual(trap Trap) (string, bool, error) {if !a.RequiresMutualTLS() {return "", false, nildiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.goindex 3e951f11..7d1f251e 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go@@ -56,19 +56,9 @@ const (observedNoIdentity = "khaos requires mutual TLS and is issuing no client identity at all")-// Observe confirms khaos's own fault landed, by reading back what the authority-// actually serves and comparing it against an HONEST chain from the same-// authority.-//-// Every branch asserts two things, not one: that the served material carries-// the defect AND that the control does not. An authority that was never armed-// must not be able to confirm a trap, which is what the inert flag exists to-// prove, and a one-sided assertion would let it.-//-// It reads the SERVED artefacts rather than the flag that was set. A flag-// records which branch khaos chose; it says nothing about what a target would-// receive, and an authority whose minting broke would happily confirm a fault-// it is not producing.+// Observe confirms khaos's own fault landed by reading back what the authority+// serves. Every branch asserts the served material carries the defect AND that+// an HONEST chain does not, so an unarmed authority cannot confirm a trap.func (a *Authority) Observe(ctx context.Context,expected Kind,@@ -127,8 +117,6 @@ func (a *Authority) Observe(}}-// observeSubject confirms the faults in when the certificate is valid and who-// it is for, all of which are visible in the served leaf itself.func (a *Authority) observeSubject(trap Trap,chain, honest *Chain,@@ -156,8 +144,7 @@ func (a *Authority) observeSubject(}case IntermediateExpired:- // The leaf has to be BLAMELESS, or this is just LeafExpired wearing a- // different name and monitoring that watches leaf expiry would catch it.+ // The leaf has to be BLAMELESS, or this is LeafExpired renamed.if chain.Issuer.NotAfter.Before(now) &&chain.Leaf.NotAfter.After(now) {return sprintf(@@ -191,16 +178,14 @@ func (a *Authority) observeSubject(}default:- // Unreachable: Observe routes only the subject group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// observeChainFault confirms the faults in the path from leaf to trusted root.-// Five of these produce byte-identical client errors in two groups, so what-// khaos knows it SERVED is the only thing that can tell them apart, and that is-// precisely what these branches record.+// Five of these produce byte-identical client errors, so what khaos knows it+// SERVED is the only thing that can tell them apart.func (a *Authority) observeChainFault(trap Trap,chain, honest *Chain,@@ -259,16 +244,12 @@ func (a *Authority) observeChainFault(return a.observeSigning(trap, chain, honest)default:- // Unreachable: Observe routes only the chain group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// observeSigning confirms the three faults in HOW the certificate is signed or-// what it may be used for. They sit apart from the path faults because none of-// them breaks the chain: the path is intact and the signature or the usage is-// what a correct client rejects.func (a *Authority) observeSigning(trap Trap,chain, honest *Chain,@@ -293,14 +274,8 @@ func (a *Authority) observeSigning(}case EKUConstrainedIntermediate:- // The LEAF is blameless, which is what separates this from the leaf- // level fault above. Both come back as Reason 4 and are otherwise- // indistinguishable to the target.- //- // The length check is load-bearing. An EMPTY ExtKeyUsage on a CA means- // UNCONSTRAINED, not "no server auth", so testing serverAuth alone- // confirmed this trap against khaos's own honest intermediate, which- // enumerates nothing. The inert control caught it.+ // The length check is load-bearing: an EMPTY ExtKeyUsage on a CA means+ // UNCONSTRAINED, so serverAuth alone would confirm against the control.if len(chain.Issuer.ExtKeyUsage) > 0 &&!serverAuth(chain.Issuer.ExtKeyUsage) &&serverAuth(chain.Leaf.ExtKeyUsage) {@@ -311,15 +286,12 @@ func (a *Authority) observeSigning(}default:- // Unreachable: observeChainFault routes only the signing group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// observePolicy confirms the faults crypto/x509 ACCEPTS. There is no refusal to-// read back, so the only evidence is the served material differing from the-// control, which makes the control load-bearing rather than decorative here.func (a *Authority) observePolicy(trap Trap,chain, honest *Chain,@@ -346,9 +318,6 @@ func (a *Authority) observePolicy(}case CASwap:- // The confirmation is that the TRUSTED ROOT moved, not that the chain is- // odd. The chain is deliberately impeccable under the new anchor, which- // is the entire point: nothing in a client can detect this.if a.TrustedRoot().Equal(a.rogueRoot.cert) {return sprintf(observedCASwap,@@ -357,14 +326,12 @@ func (a *Authority) observePolicy(}default:- // Unreachable: Observe routes only the policy group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// observeStaple confirms the three faults that act on what the handshake-// carries rather than on what a responder says.func (a *Authority) observeStaple(trap Trap,chain, honest *Chain,@@ -375,9 +342,6 @@ func (a *Authority) observeStaple(return "", false, nil}- // The parse FAILING is the confirmation: the staple is garbage, which is- // the fault. nilerr reads this as swallowing an error, and it is the- // opposite -- the error is the evidence.if _, err := ocsp.ParseResponse(chain.Staple,chain.Issuer,@@ -392,8 +356,7 @@ func (a *Authority) observeStaple(}case NoOCSPServer:- // The CRL pointer has to SURVIVE, or this is a total revocation outage- // rather than the end of OCSP that it models.+ // The CRL pointer has to SURVIVE, or this is a revocation outage.if len(chain.Leaf.OCSPServer) == 0 &&len(chain.Leaf.CRLDistributionPoints) > 0 {return sprintf(@@ -403,14 +366,12 @@ func (a *Authority) observeStaple(}default:- // Unreachable: Observe routes only the stapling group here.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// names and permits are small readers over a certificate's identity, kept-// separate so the branches above read as assertions rather than as parsing.type nameSet []stringfunc names(cert *x509.Certificate) nameSet {@@ -461,9 +422,6 @@ func sprintf(format string, args ...any) string {return fmt.Sprintf(format, args...)}-// health is the control for both unreachable traps. Its whole job is to still-// answer while one endpoint refuses, because "khaos broke one endpoint" and-// "khaos fell over" are different claims and only the first is a fault.func (a *Authority) health(ctx context.Context) (int, error) {base, err := a.Addr()if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.goindex 7d774c09..5c867f21 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go@@ -16,14 +16,8 @@ import (const maxReadBack = 1 << 20-// observeRevocation confirms the faults that act on revocation rather than on-// the certificate.-//-// Every one of these serves a chain crypto/x509 accepts, so there is no refusal-// anywhere to read back and nothing in the certificate differs from the-// control. The ONLY evidence is what khaos's own endpoints answer, which is why-// this reads them over HTTP exactly as a target would rather than inspecting-// the state that produced them.+// Every one of these serves a chain crypto/x509 accepts, so the only evidence+// is what khaos's endpoints answer, read over HTTP as a target would.func (a *Authority) observeRevocation(ctx context.Context,trap Trap,@@ -48,10 +42,7 @@ func (a *Authority) observeRevocation(}}-// observeUnreachable confirms that ONE endpoint refuses while the health route-// still answers. Both halves are required: an authority that fell over would-// satisfy the first on its own, and khaos would be reporting its own crash as a-// fault it injected.+// Both halves: one endpoint refuses AND the health route still answers.func (a *Authority) observeUnreachable(ctx context.Context,trap Trap,@@ -74,22 +65,13 @@ func (a *Authority) observeUnreachable(return sprintf(observedUnreached, route, status), true, nil}-// observeCRL reads the list khaos serves. The two CRL faults are distinguished-// HERE and not by what they were asked to do: one lists the serial in a fresh-// list, the other omits it from a stale one, and a mix-up either way makes one-// of them inert.func (a *Authority) observeCRL(ctx context.Context,trap Trap,chain *Chain,root string,) (string, bool, error) {- // Every failure below returns NOT CONFIRMED rather than an error, and that- // is the same discipline the identity provider's oracle uses: khaos being- // unable to read its own fault back is a refusal to confirm, which makes- // the engine abort the run. Returning the read error instead would make- // khaos fail with a plumbing complaint when the honest answer is "khaos- // could not see this fault land".+ // Failing to read khaos's own fault back is NOT CONFIRMED, not an error.der, err := a.read(ctx, root+RouteCRL)if err != nil {return "", false, nil //nolint:nilerr // not confirmed, not an error@@ -101,8 +83,6 @@ func (a *Authority) observeCRL(}if err := list.CheckSignatureFrom(chain.Issuer); err != nil {- // A list a correct client would discard proves nothing about the- // target: it would refuse for khaos's defect rather than the fault's.return "", false, nil //nolint:nilerr // not confirmed, not an error}@@ -120,8 +100,8 @@ func (a *Authority) observeCRL(return "", false, nil}- // StaleCRL. The serial must be ABSENT, or a client that ignores freshness- // still finds it and refuses, and the fault catches nothing.+ // StaleCRL. The serial must be ABSENT, or a client ignoring freshness+ // still finds it and refuses.if !listed && list.NextUpdate.Before(now) {return sprintf(observedStale,@@ -133,9 +113,6 @@ func (a *Authority) observeCRL(return "", false, nil}-// observeResponder reads what the OCSP endpoint answers. Each branch asserts-// the ONE property its fault corrupts, so a responder that was wrong in some-// other way cannot confirm a trap it is not producing.func (a *Authority) observeResponder(ctx context.Context,trap Trap,@@ -148,9 +125,6 @@ func (a *Authority) observeResponder(}if trap.Kind == OCSPTryLater {- // TryLater is a RESPONSE status, so it must NOT parse as an answer. A- // successful parse here would mean khaos served a real verdict and the- // soft-fail trap never gets its chance.var unusable ocsp.ResponseErrorif _, parseErr := ocsp.ParseResponse(der,@@ -164,15 +138,11 @@ func (a *Authority) observeResponder(}if trap.Kind == OCSPWrongSigner {- // Rejected when bound to the certificate is the whole fault. Parsing it- // successfully would mean the CA did issue the signer after all.if _, bindErr := ocsp.ParseResponseForCert(der,chain.Leaf,chain.Issuer,); bindErr != nil {- // The binding FAILING is the confirmation, not an error being- // swallowed: the CA never issued this signer, which is the fault.//nolint:nilerr // the rejection IS the observablereturn observedBadSigner, true, nil}@@ -180,9 +150,8 @@ func (a *Authority) observeResponder(return "", false, nil //nolint:nilerr // not confirmed, not an error}- // The remaining three answer about SOMETHING, so they have to parse. The- // loose call is used deliberately: ParseResponseForCert refuses the- // wrong-serial response, which is the fault khaos is trying to read back.+ // The loose call is deliberate: ParseResponseForCert refuses the+ // wrong-serial response, which is the fault khaos is reading back.response, err := ocsp.ParseResponse(der, chain.Issuer)if err != nil {return "", false, nil //nolint:nilerr // not confirmed, not an error@@ -210,8 +179,6 @@ func (a *Authority) judgeResponse(}case OCSPStale:- // Good AND stale. A stale Revoked would be refused for its status, so a- // client refusing it would prove nothing about freshness.if response.Status == ocsp.Good &&response.NextUpdate.Before(now) {return sprintf(@@ -222,9 +189,8 @@ func (a *Authority) judgeResponse(}case OCSPWrongSerial:- // Good, and about a DIFFERENT certificate. Both halves: a Revoked for- // the wrong serial would be refused on status by a client that never- // checks the binding.+ // Good, and about a DIFFERENT certificate: a Revoked for the wrong+ // serial would be refused on status instead.if response.Status == ocsp.Good &&response.SerialNumber.Cmp(chain.Leaf.SerialNumber) != 0 {return sprintf(@@ -235,16 +201,12 @@ func (a *Authority) judgeResponse(}default:- // Unreachable: observeResponder handles the other kinds itself.+ // Kinds from the other groups reach their own observer.}return "", false, nil}-// probe and read are khaos's OWN requests, marked so the counters can subtract-// them. Without the header, "the target consulted revocation" would be true for-// every run in which khaos confirmed its own fault, and the UNSUPPORTED verdict-// would never fire.func (a *Authority) probe(ctx context.Context, url string) (int, error) {response, err := a.send(ctx, url)if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.goindex bb3fec0d..2765e844 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go@@ -14,38 +14,22 @@ import ()const (- // reasonKeyCompromise is RFC 5280 section 5.3.1. Reason code 0 is NOT used- // anywhere in khaos: when creating a CRL, 0 means the reasonCode extension- // is omitted entirely, and when parsing, 0 is ambiguous between "extension- // absent" and "extension present, value zero". An ambiguous signal cannot- // carry a finding.+ // RFC 5280 5.3.1. Reason code 0 is never used: on creation it omits the+ // extension, and on parsing it cannot be told from an absent one.reasonKeyCompromise = 1- // crlNumber is the cRLNumber extension. khaos issues one CRL per arming, so- // it does not need to increment.crlNumber = 1- // wrongSerialOffset is added to the leaf's serial to mint an OCSP response- // that is about a DIFFERENT certificate. Any value works; a fixed offset- // makes the resulting serial reproducible in a failure message.wrongSerialOffset = 1- // garbageStaple is bytes that are definitively not an OCSP response. Go- // never parses a staple, so these reach the application verbatim and only- // its own handling decides.garbageStaple = "khaos: this is not an OCSP response"errCRL = "%w: minting a CRL: %v"errOCSPGen = "%w: minting an OCSP response: %v")-// buildRevocation mints the chain for every fault that acts on revocation-// rather than on the certificate itself.-//-// Go performs NO revocation checking of any kind, so every chain in this group-// verifies with a nil error. That is not a weakness of the faults, it IS the-// finding: the certificate is impeccable and the only thing wrong with it is-// something the standard library will never look at.+// Go performs NO revocation checking, so every chain in this group verifies+// with a nil error, and that is the finding rather than a weak fault.func (a *Authority) buildRevocation(trap Trap,host string,@@ -57,18 +41,12 @@ func (a *Authority) buildRevocation(}if trap.Kind == NoOCSPServer {- // Models Let's Encrypt after it ended OCSP in 2025. The CRL pointer- // stays, so the honest answer for a target is to fall back to it; the- // question is whether it does, or treats "nothing to ask" as "fine".template.OCSPServer = nil}return a.assemble(template, a.inter, a.root.cert, StrongBits, true)}-// staple attaches whatever stapled response the trap calls for. A nil staple is-// not an error: it is the StapleAbsent fault, and it is also what every-// non-stapling trap serves.func (a *Authority) staple(trap Trap,chain *Chain,@@ -82,22 +60,14 @@ func (a *Authority) staple(chain.Staple = nilcase OCSPTryLater, OCSPUnreachable, CRLUnreachable:- // NOTHING is stapled. These three faults are about an answer the client- // cannot OBTAIN, and a stapled Good is an answer obtained for free: the- // client would read it, be satisfied, and never contact the endpoint- // khaos broke. The fault would be completely unreachable.- //- // The matrix caught exactly this. Nine modes, including the correct- // one, accepted ocsp-try-later and ocsp-unreachable because the staple- // answered first.+ // NOTHING is stapled. These three are about an answer the client cannot+ // OBTAIN, and a stapled Good would be read before the broken endpoint.chain.Staple = nilcase OCSPRevoked, OCSPStale, OCSPWrongSerial, OCSPWrongSigner,OCSPUnknown:- // The responder faults also staple what they would have answered, so a- // target that reads the staple instead of querying sees the same fault.- // Without this, an app that trusts staples would be measured against a- // responder it never contacts and would read as fail-closed.+ // The responder faults staple what they would have answered, or an app+ // that trusts staples never contacts the responder under test.der, err := a.ocspFor(trap, chain, now)if err != nil {return nil, err@@ -106,8 +76,6 @@ func (a *Authority) staple(chain.Staple = derdefault:- // Every other trap staples an honest Good, which is what a correct- // authority serving a good certificate would do.der, err := a.ocspGood(chain, now, now.Add(DefaultWindow))if err != nil {return nil, err@@ -119,10 +87,7 @@ func (a *Authority) staple(return chain, nil}-// CRLFor mints the revocation list the authority serves for this chain. The-// trap decides whether the leaf is listed and whether the list is fresh, and-// those are INDEPENDENT: a stale CRL that revokes nothing finds nothing, and a-// fresh CRL that revokes the leaf is the baseline every correct client passes.+// Whether the leaf is listed and whether the list is fresh are INDEPENDENT.func (a *Authority) CRLFor(trap Trap,chain *Chain,@@ -135,25 +100,15 @@ func (a *Authority) CRLFor(}if trap.Kind == StaleCRL {- // ThisUpdate has to move with NextUpdate, or the list is both stale and- // not yet issued and a client rejecting it cannot say which it rejected.+ // ThisUpdate moves with NextUpdate, or the list is also not yet issued.window := trap.window()template.ThisUpdate = now.Add(-window - DefaultWindow)template.NextUpdate = now.Add(-window)}- // Only RevokedViaCRL lists the serial. StaleCRL deliberately does NOT, and- // that is the difference between the two faults.- //- // The first draft had the stale list also revoke the leaf, which made the- // fault catch nothing: a client that ignores freshness still reaches the- // serial scan, still finds the entry, and still refuses, so the broken- // client behaved exactly like the correct one. The matrix caught it.- //- // The real scenario is a three-week-old list that PREDATES the revocation.- // A correct client refuses because a list it cannot trust is not an answer;- // a client that skips step five reads "not listed" as "not revoked" and- // accepts. That differential is the whole fault.+ // Only RevokedViaCRL lists the serial. StaleCRL deliberately does NOT: it+ // models an old list that PREDATES the revocation, and one that revoked the+ // leaf as well would be refused by broken and correct clients alike.if trap.Kind == RevokedViaCRL {template.RevokedCertificateEntries = []x509.RevocationListEntry{{SerialNumber: chain.Leaf.SerialNumber,@@ -175,28 +130,14 @@ func (a *Authority) CRLFor(return der, nil}-// ocspFor mints the response the trap calls for. Each branch corrupts exactly-// one property of an otherwise correct Good response, so a client that refuses-// one of them has refused for the reason khaos intended.func (a *Authority) ocspFor(trap Trap,chain *Chain,now time.Time,) ([]byte, error) {- // The chain's OWN issuer signs, acting as its own responder, which RFC 6960- // section 2.6 permits alongside a delegated one.- //- // A single delegated responder cannot work here, and the matrix proved it.- // Seven of these traps serve a chain under a DIFFERENT CA -- the rogue- // hierarchy, a non-CA issuer, an over-deep intermediate, or the leaf- // itself -- and a response signed by a responder delegated by the honest- // intermediate does not verify against any of them. Six traps were being- // refused for `the stapled response is not a usable OCSP response`, which- // is khaos's own mismatch wearing the wrong-signer fault's clothes.- //- // Signing with the chain's issuer is always consistent with the chain by- // construction. The delegation path is still exercised, from the other- // side, by OCSPWrongSigner.+ // The chain's OWN issuer signs, which RFC 6960 section 2.6 permits. One+ // delegated responder cannot work: several traps serve a chain under a+ // DIFFERENT CA.signer := &pair{cert: chain.Issuer, key: chain.issuerKey}template := ocsp.Response{@@ -213,8 +154,6 @@ func (a *Authority) ocspFor(template.RevocationReason = reasonKeyCompromisecase OCSPUnknown:- // Unknown from the AUTHORITATIVE responder is not good. Collapsing the- // two is its own fail-open and a common one.template.Status = ocsp.Unknowncase OCSPStale:@@ -223,10 +162,6 @@ func (a *Authority) ocspFor(template.NextUpdate = now.Add(-window)case OCSPWrongSerial:- // The highest-value trap in the group: the bypass is one word of caller- // code. ParseResponseForCert rejects this; ParseResponse does not bind- // the response to the certificate at all and returns a nil error, so a- // caller reading Status accepts a Good minted for another certificate.template.SerialNumber = new(big.Int).Add(chain.Leaf.SerialNumber,big.NewInt(wrongSerialOffset),@@ -236,19 +171,13 @@ func (a *Authority) ocspFor(signer = a.undelegateddefault:- // Good, fresh, correctly signed, for this serial.+ // Every other kind leaves the response honest.}- // Embedded ONLY for the wrong-signer fault, and only after the switch has- // decided who signs.- //- // x/crypto embeds the responder certificate just when template.Certificate- // is non-nil (ocsp.go:783), and ParseResponse branches on whether one is- // present: with a certificate it checks the response against that and that- // against the issuer, and without one it checks the response against the- // issuer directly. The issuer signs its own responses here, so leaving this- // nil is what makes them verify. Setting it for the undelegated signer is- // what makes that response fail at the SECOND check, which is the fault.+ // x/crypto embeds the responder certificate only when this is non-nil, and+ // ParseResponse branches on its presence: with one it checks the response+ // against that and that against the issuer. Nil is what lets a+ // self-issued response verify.if signer != nil && signer.cert != chain.Issuer {template.Certificate = signer.cert}@@ -266,8 +195,6 @@ func (a *Authority) ocspFor(return der, nil}-// ocspGood is the honest response, and the control for every responder fault.-// Signed by the chain's own issuer for the same reason ocspFor is.func (a *Authority) ocspGood(chain *Chain,now, until time.Time,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.goindex d9e19c65..9286c924 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go@@ -13,17 +13,11 @@ const (routeDependency = "/"dependencyBody = "khaos range dependency"- // headerProbe marks a request as khaos's OWN confirmation probe, so the- // counters can subtract it. Without this, "the target fetched the CRL"- // would be true for every run in which khaos confirmed its own fault.+ // Marks a request as khaos's OWN probe, so the counters can subtract it.headerProbe = "X-Khaos-Probe"probeValue = "confirmation")-// routes is the revocation surface. RouteHealth is not decoration: it is the-// CONTROL for the two unreachable traps, and its entire job is to keep-// answering while the CRL or OCSP endpoint refuses. Without it, "khaos broke-// one endpoint" and "khaos fell over" are the same observation.func (a *Authority) routes() http.Handler {mux := http.NewServeMux()@@ -36,19 +30,13 @@ func (a *Authority) routes() http.Handler {return mux}-// serveRoot answers with the root the TARGET is configured to trust, which is-// the one CASwap replaces. It is deliberately not the chain's own anchor: for-// UntrustedCA those two differ, and that difference IS the fault.+// The root the TARGET trusts, which for UntrustedCA is not the chain's own.func (a *Authority) serveRoot(w http.ResponseWriter, _ *http.Request) {w.Header().Set(headerType, mimeDER)w.WriteHeader(http.StatusOK)_, _ = w.Write(a.TrustedRoot().Raw)}-// dependencyRoutes is what khaos answers once a client has got through the-// handshake. The body is deliberately trivial: this endpoint exists so that a-// client which ACCEPTED a bad certificate has something to succeed at, and the-// finding is the acceptance, not anything in the response.func (a *Authority) dependencyRoutes() http.Handler {mux := http.NewServeMux()@@ -68,14 +56,8 @@ func (a *Authority) serveHealth(w http.ResponseWriter, _ *http.Request) {_, _ = io.WriteString(w, healthBody)}-// serveCRL and serveOCSP serve what the ARMED CHAIN carries, and dispatch on-// nothing.-//-// Neither reads the trap. Everything either of them does was decided when the-// chain was built, which is what keeps an authority that armed nothing serving-// honest material: deriving the answer from the trap record here meant an inert-// authority still published a revoked list, and thirteen traps confirmed-// against a fault that had not happened.+// Both handlers serve what the ARMED CHAIN carries and read no trap, which+// keeps an authority that armed nothing serving honest material.func (a *Authority) serveCRL(w http.ResponseWriter, r *http.Request) {a.countCRL(r)@@ -120,15 +102,8 @@ func (a *Authority) serveOCSP(w http.ResponseWriter, r *http.Request) {_, _ = w.Write(der)}-// refuse drops the connection without answering, which is what makes one route-// unreachable while its neighbour on the same listener keeps serving.-//-// Dropping the whole listener would be the more literal reading of "the-// responder is down", and it is the wrong choice: it would take RouteHealth-// with it, and then khaos could not show that it had broken one endpoint rather-// than fallen over. A hijacked connection is a transport failure the client-// cannot tell from a dead port, scoped to the route that is supposed to be-// dead.+// Hijacked rather than shut down, so one route dies while its neighbour on the+// same listener keeps serving, RouteHealth included.func refuse(w http.ResponseWriter) {hijacker, ok := w.(http.Hijacker)if !ok {@@ -161,8 +136,6 @@ func (a *Authority) countOCSP(r *http.Request) {}}-// Now is the authority's clock, which the experiments need in order to assert-// about a validity window without racing a real one.func (a *Authority) Now() time.Time {return a.clock()}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.goindex db65077b..1b337c08 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go@@ -29,19 +29,10 @@ const (errAlreadyUp = "%w: the authority is already listening on %s")-// ErrListener is any failure to stand up or reach the authority's own-// endpoints. It is separate from a trap failing, because khaos being-// unreachable is khaos's bug and a trap landing is the product working.var ErrListener = errors.New("khaos's certificate authority listener")-// listenerState holds both of the authority's listeners. There are two because-// they serve different protocols to the same target: a TLS endpoint where khaos-// IS the dependency whose certificate is under test, and a plain HTTP endpoint-// for the revocation data that certificate points at.-//-// They cannot be one listener. The revocation endpoints have to stay reachable-// while the TLS certificate is broken, or every revocation fault would also be-// an outage and khaos could not attribute what it measured.+// Two listeners, because the revocation endpoints have to stay reachable while+// the TLS certificate is broken, or every revocation fault is also an outage.type listenerState struct {mu sync.Mutex@@ -55,16 +46,8 @@ type listenerState struct {wg sync.WaitGroup}-// Base is the URL the TARGET uses to reach the CRL and OCSP endpoints.-//-// It is configured rather than derived from the listener, and that distinction-// cost a full debugging session in the identity family. khaos binds the Docker-// bridge gateway's numeric address while the target addresses-// `host.docker.internal`, so a URL built from khaos's own listener address is-// unreachable from inside the target's network namespace. Every revocation-// fetch would then fail for a reason that has nothing to do with the trap, and-// the run would report the target as fail-closed when khaos had simply pointed-// it at nowhere.+// Configured, not derived from the listener: khaos binds the Docker bridge+// gateway while the target addresses `host.docker.internal`.func (a *Authority) Base() string {a.listener.mu.Lock()defer a.listener.mu.Unlock()@@ -72,9 +55,6 @@ func (a *Authority) Base() string {return a.listener.base}-// SetBase pins the externally-reachable base URL. It refuses to overwrite one-// that is already set, because Listen used to do exactly that in the identity-// provider and silently invalidated every credential it minted.func (a *Authority) SetBase(base string) {a.listener.mu.Lock()defer a.listener.mu.Unlock()@@ -84,9 +64,6 @@ func (a *Authority) SetBase(base string) {}}-// Listen binds the revocation endpoints. If no base URL has been pinned, the-// listener's own address becomes it, which is right for a test on loopback and-// wrong for a container, hence SetBase.func (a *Authority) Listen(addr string) error {a.listener.mu.Lock()defer a.listener.mu.Unlock()@@ -118,9 +95,8 @@ func (a *Authority) Listen(addr string) error {a.listener.wg.Add(1)- // The goroutine serves the LOCAL, not the field. Reading a.listener.revSrv- // in here is a data race against shutdown, which nils it under the mutex- // this goroutine does not hold, and `go test -race` catches it.+ // Serves the LOCAL, not the field: reading a.listener.revSrv here races+ // shutdown, which nils it under a mutex this goroutine does not hold.go func() {defer a.listener.wg.Done()_ = server.Serve(listener)@@ -129,10 +105,7 @@ func (a *Authority) Listen(addr string) error {return nil}-// ListenTLS binds the endpoint where khaos plays the dependency, presenting-// whatever chain is armed. The certificate is resolved per handshake through-// GetCertificate rather than fixed at bind time, so arming a trap takes effect-// on the next connection without the listener moving.+// Resolved per handshake, so arming takes effect on the next connection.func (a *Authority) ListenTLS(addr string) error {a.listener.mu.Lock()defer a.listener.mu.Unlock()@@ -157,11 +130,7 @@ func (a *Authority) ListenTLS(addr string) error {MinVersion: tls.VersionTLS12,GetCertificate: a.getCertificate,- // Per handshake, so arming an mTLS trap takes effect on the next- // connection without the listener moving. ClientAuth fixed at bind- // time would mean those traps could only be armed before the target- // was ever pointed at khaos, which is not when an experiment arms- // anything.+ // Per handshake too, so an mTLS trap can be armed later.GetConfigForClient: a.configForClient,},}@@ -171,7 +140,6 @@ func (a *Authority) ListenTLS(addr string) error {a.listener.wg.Add(1)- // Serves the LOCAL, for the same reason Listen does.go func() {defer a.listener.wg.Done()_ = server.ServeTLS(listener, "", "")@@ -180,16 +148,8 @@ func (a *Authority) ListenTLS(addr string) error {return nil}-// configForClient decides, per handshake, whether khaos demands a client-// certificate.-//-// RequireAndVerifyClientCert specifically, and not VerifyClientCertIfGiven.-// Research 04 measured the whole matrix and that mode is the fail-open trap: it-// rejects a BAD certificate and accepts NONE, so it reads as secure while its-// failure mode is a total authentication bypass. khaos's own server must not be-// the thing being wrong here -- the fault is in the identity it ISSUED, and a-// server that let an identity-less client through would make both mTLS traps-// unobservable.+// RequireAndVerifyClientCert, not VerifyClientCertIfGiven: that mode rejects a+// BAD certificate and accepts NONE, which would be khaos itself failing open.func (a *Authority) configForClient(*tls.ClientHelloInfo,) (*tls.Config, error) {@@ -206,10 +166,6 @@ func (a *Authority) configForClient(return cfg, nil}-// issuingPool is the CA that signed the target's identity, which is what khaos-// verifies that identity against. It is the real intermediate rather than-// whatever TrustedRoot currently reports, because a CA swap changes what the-// TARGET trusts and has nothing to do with who issued the client.func (a *Authority) issuingPool() *x509.CertPool {pool := x509.NewCertPool()pool.AddCert(a.inter.cert)@@ -218,11 +174,6 @@ func (a *Authority) issuingPool() *x509.CertPool {return pool}-// getCertificate resolves the armed chain per handshake.-//-// A handshake that arrives with nothing armed is served the honest chain rather-// than refused, because the baseline is measured through this listener and a-// baseline that cannot connect establishes nothing.func (a *Authority) getCertificate(*tls.ClientHelloInfo,) (*tls.Certificate, error) {@@ -243,7 +194,6 @@ func (a *Authority) getCertificate(return &certificate, nil}-// Addr is where the revocation endpoints are bound.func (a *Authority) Addr() (string, error) {a.listener.mu.Lock()defer a.listener.mu.Unlock()@@ -255,7 +205,6 @@ func (a *Authority) Addr() (string, error) {return a.listener.revocation.Addr().String(), nil}-// TLSAddr is where khaos is playing the dependency.func (a *Authority) TLSAddr() (string, error) {a.listener.mu.Lock()defer a.listener.mu.Unlock()diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.goindex d77c8c2a..d7a2274b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go@@ -10,181 +10,80 @@ import ("time")-// Kind names one way khaos makes its own certificate authority wrong. Every-// kind maps to a row of the fault table in research 04, which recorded the-// client-side error type, the x509 InvalidReason integer and the fail-open-// behaviour the fault is for, all measured on go1.26.5.-//-// The groups below are the ones the research itself uses, and they are not-// cosmetic: a fault that corrupts the validity window is confirmed differently-// from one that corrupts the chain, and three of the chain faults produce a-// BYTE-IDENTICAL client error, which is the problem this family exists to make-// tractable.+// Kind names one way khaos makes its own certificate authority wrong.type Kind stringconst (- // PassThrough is the zero value: the authority behaves correctly. An- // authority with nothing armed has to be indistinguishable from a real one,- // because every experiment's baseline is measured through it.+ // The zero value: the authority behaves correctly.PassThrough Kind = ""- // LeafExpired and LeafNotYetValid both come back as- // CertificateInvalidError with Reason 1. There is NO separate- // NotYetValid reason, so the only thing that tells them apart is whether- // the Detail says "is after" or "is before". Rows F01 and F02.+ // Both are Reason 1; only the Detail wording separates them.LeafExpired Kind = "leaf-expired"LeafNotYetValid Kind = "leaf-not-yet-valid"- // IntermediateExpired leaves the leaf in date and expires the CA above it.- // Row F03, and the fail-open it catches is monitoring that watches leaf- // expiry only.IntermediateExpired Kind = "intermediate-expired"- // WrongSAN, CommonNameOnly and NoIPSAN are the hostname faults, all- // HostnameError. CommonNameOnly is worth its own kind because Go removed the- // CommonName fallback outright: the error names the legacy field, which is a- // different message from a plain mismatch. Rows F04, F05 and F07.+ // All HostnameError. Go removed the CommonName fallback outright.WrongSAN Kind = "wrong-san"CommonNameOnly Kind = "common-name-only"NoIPSAN Kind = "no-ip-san"- // SelfSigned, UntrustedCA and MissingIntermediate are THE THREE that matter- // most in this family. All three produce exactly- // `x509: certificate signed by unknown authority`, with no reason code and- // nothing in the string to separate them, so a target's logs cannot tell an- // operator which one happened. Disambiguating them is M7's exit gate. Rows- // F09, F10 and F11.+ // All three produce a byte-identical `signed by unknown authority`.SelfSigned Kind = "self-signed"UntrustedCA Kind = "untrusted-ca"MissingIntermediate Kind = "missing-intermediate"- // IssuerNotCA signs the leaf with a certificate whose IsCA is false, which- // surfaces as UnknownAuthorityError wrapping ConstraintViolationError. Row- // F16.+ // UnknownAuthorityError wrapping ConstraintViolationError.IssuerNotCA Kind = "issuer-not-ca"- // NameConstraintViolation and PathLengthExceeded are the two constraint- // faults, Reason 2 and Reason 3. Rows F17 and F18.NameConstraintViolation Kind = "name-constraint-violation"PathLengthExceeded Kind = "path-length-exceeded"- // SHA1Signature signs the leaf with SHA1WithRSA. Go CREATES it without- // complaint and refuses it at verification, wrapping InsecureAlgorithmError- // inside UnknownAuthorityError, so this reads as an authority failure unless- // the caller unwraps. Row F12, measured again on this box before the family- // was built.+ // Go creates a SHA-1 signature, then refuses it at verification.SHA1Signature Kind = "sha1-signature"- // WeakKey through KeyUsageWithoutDigitalSignature are the faults Go- // ACCEPTS. They return nil from Verify, so they do not test the x509- // library at all -- they test whether the TARGET imposed a policy of its- // own. Rows F13, F20 and F19.- //- // These are the most valuable experiments in the family for exactly that- // reason, and also the ones whose polarity is easiest to get wrong: a target- // that accepts them is not being caught out by Go, it simply has no floor.+ // Verify returns nil for these: they test the target's policy, not x509.WeakKey Kind = "weak-key"ExcessiveLifetime Kind = "excessive-lifetime"KeyUsageWithoutDigitalSignature Kind = "key-usage-no-digital-signature"- // EKUClientAuthOnly and EKUConstrainedIntermediate are the extended key- // usage faults, and BOTH come back as Reason 4: `crypto/x509` declares- // CANotAuthorizedForExtKeyUsage and never constructs it, so no chain can- // elicit it. Go checks EKU nested down the chain but does not check the- // basic KeyUsage bits on a leaf, which is why the kind above exists beside- // these two. Rows F14 and F15.+ // Both are Reason 4. Go checks EKU down the chain, KeyUsage never.EKUClientAuthOnly Kind = "eku-client-auth-only"EKUConstrainedIntermediate Kind = "eku-constrained-intermediate"- // RevokedViaCRL is the headline of the whole family. The leaf is revoked in- // a valid, in-date, correctly signed CRL from its own issuer, and- // `Certificate.Verify` returns nil, because Go performs no revocation- // checking of any kind and has no option to turn it on. Row F21.- //- // khaos must therefore report `unsupported` rather than `pass` against a Go- // target that does nothing: there is no revocation check to have failed.- // That distinction is the other half of M7's exit gate.+ // Verify returns nil: Go does no revocation checking of any kind.RevokedViaCRL Kind = "revoked-via-crl"- // StaleCRL revokes the leaf in a CRL whose NextUpdate is in the past. It is- // a DIFFERENT fault from RevokedViaCRL and strictly harder to pass: the- // target does fetch and parse a CRL, and still accepts the certificate,- // because nothing in the standard library checks freshness and step 5 of the- // six-step check is the one people skip. Row F33.+ // Nothing in the standard library checks a CRL's freshness.StaleCRL Kind = "stale-crl"- // CRLUnreachable serves the leaf with a CRL distribution point that refuses- // the connection, while every other endpoint stays up. A target that treats- // "could not fetch" as "not revoked" fails open here and nowhere else.CRLUnreachable Kind = "crl-unreachable"- // OCSPRevoked and OCSPUnknown are the two answers a responder gives that a- // correct client must reject. "Unknown" from the authoritative responder is- // not "good", and collapsing the two is its own fail-open.OCSPRevoked Kind = "ocsp-revoked"OCSPUnknown Kind = "ocsp-unknown"- // OCSPTryLater and OCSPUnreachable are the soft-fail traps, and research 04- // calls soft-fail the reason revocation is near-useless in practice. A- // client that proceeds because it could not get an answer has a seat belt- // that unbuckles under load.+ // The soft-fail traps: a client that proceeds having got no answer.OCSPTryLater Kind = "ocsp-try-later"OCSPUnreachable Kind = "ocsp-unreachable"- // OCSPStale returns a correctly signed Good response whose NextUpdate is in- // the past. Measured: x/crypto/ocsp does not check freshness, so this parses- // with a nil error and a replayed Good is trusted forever. Row F30.+ // x/crypto/ocsp ignores NextUpdate, so a replayed Good parses clean.OCSPStale Kind = "ocsp-stale"- // OCSPWrongSerial is the single highest-value trap in the OCSP group,- // because the bypass is one word of caller code. A Good response minted for- // a DIFFERENT serial is rejected by ocsp.ParseResponseForCert and accepted- // by ocsp.ParseResponse, which does not bind the response to the- // certificate at all. Row F31.+ // ocsp.ParseResponse does not bind the response to the certificate.OCSPWrongSerial Kind = "ocsp-wrong-serial"- // OCSPWrongSigner signs the response with a key the CA never delegated.- // CheckSignatureFrom catches it, but only if the caller calls it.OCSPWrongSigner Kind = "ocsp-wrong-signer"- // NoOCSPServer mints a leaf with no OCSPServer at all, which models Let's- // Encrypt after it ended OCSP in 2025. The question it asks is what the- // target does when there is nothing to ask: fail open, or fall back to the- // CRL it also published. Row F34.NoOCSPServer Kind = "no-ocsp-server"- // StapleGarbage and StapleAbsent act on the stapled response rather than on- // the responder. Go never parses a staple, so both reach the application- // untouched: one as bytes that are not an OCSP response, the other as an- // empty field a soft-failing app reads as good. Rows F28 and F29.+ // Go never parses a staple, so both reach the application untouched.StapleGarbage Kind = "staple-garbage"StapleAbsent Kind = "staple-absent"- // CASwap replaces the root the target trusts with one khaos controls, and- // then serves a chain that is VALID under it. Nothing in the client can- // detect this, which is the point: it is the CA-compromise scenario, and the- // only defences are pinning or certificate transparency. Row F24.+ // A chain that is valid under a root khaos substituted, so undetectable.CASwap Kind = "ca-swap"- // ClientCertExpired and ClientCertAbsent are the two MUTUAL TLS faults, and- // they are the only traps that act on the target's own identity rather than- // on the dependency's.- //- // khaos is the server here, so it is khaos that demands a client- // certificate and khaos that issues the one the target presents. The fault- // is in that issued identity: expired, or withheld entirely, which is what- // a failed rotation and a bypassed sidecar actually look like.- //- // What they catch is NOT the rejection -- khaos's server rejects correctly- // either way. It is whether the target NOTICES. Research 04 section 7.2- // measured the whole ClientAuth matrix and under TLS 1.3 every single row- // returned a successful tls.Dial, including the rows where the server- // refused the identity and served nothing at all; the error arrives on the- // first read. Under TLS 1.2 the same case fails at Dial. So a client that- // dials and does not read reports a healthy dependency that refused it, and- // the defect is invisible on the older protocol and total on the newer one.- //- // Rows F27 and F26.+ // khaos is the server here, and issues the identity the target presents.ClientCertExpired Kind = "client-cert-expired"ClientCertAbsent Kind = "client-cert-absent")@@ -244,8 +143,7 @@ const ()var (- // ErrInvalidTrap is a trap khaos understands, specified in a way that cannot- // express the fault.+ // ErrInvalidTrap is a known trap specified so that it cannot express it.ErrInvalidTrap = errors.New("that trap cannot be armed as specified")// ErrUnknownTrap is a name khaos's authority has no fault for.@@ -254,27 +152,18 @@ var ())-// Trap is one armed misbehaviour and its magnitude. It is a value rather than a-// closure so it can be journaled: the authority dies with the process, so the-// journal record is the only durable account of what a run actually did.+// Trap is one armed misbehaviour and its magnitude, kept as a value rather than+// a closure so it can be journaled.type Trap struct {Kind Kind `json:"kind"`- // Window is how far a time-based fault moves the boundary it corrupts: how- // long ago the leaf expired, how far in the future it starts, how stale the- // CRL or OCSP response is.+ // Window is how far a time-based fault moves the boundary it corrupts.Window time.Duration `json:"window,omitempty"`- // Host is the name the served certificate is minted for, and the name the- // hostname faults deliberately get wrong.Host string `json:"host,omitempty"`- // Bits is the RSA modulus size WeakKey mints. It is a parameter because the- // interesting question is where the target's floor sits, and a single fixed- // size can only ever answer it for one floor.Bits int `json:"bits,omitempty"`- // Days is the leaf lifetime ExcessiveLifetime mints, for the same reason.Days int `json:"days,omitempty"`}@@ -312,10 +201,7 @@ func (t Trap) Validate() error {// The remaining traps carry no magnitude to validate.}- // EVERY trap mints and serves a leaf, including the ones that act on the- // responder, because a revocation answer about no certificate is not a fault- // anyone can observe. So the host is required unconditionally rather than- // through a per-kind predicate that would have no false case.+ // Every trap serves a leaf, including the ones that act on the responder.if t.Kind != PassThrough && t.Host == "" {return fmt.Errorf(errNeedsHost, ErrInvalidTrap, t.Kind)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.goindex 38bfd487..3fc64bee 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/http.go@@ -39,20 +39,12 @@ type HTTPOptions struct {Credential CredentialTimeout time.Duration- // Unique appends a per-request nonce to the token. A negative control that- // reuses one fixed credential keeps the target's decision cache warm, so- // the cached refusal answers every probe and a control that stops- // enforcing during the fault is never exercised.+ // Unique appends a per-request nonce, because one fixed credential keeps+ // the target's decision cache warm.Unique bool- // Mint supplies the credential per request instead of Token. A forged stream- // needs it: the provider's arming changes between the baseline and the fault,- // so a credential captured once would carry the baseline's honest token into- // the fault window and the trap would never be presented at all.- //- // A mint failure is khaos's own fault and is reported as ProbeFailed, which- // every rate already excludes. Folding it into a target outcome would- // manufacture a finding out of khaos's own bug.+ // Mint supplies the credential per request instead of Token, for a stream+ // whose provider is armed between the baseline and the fault.Mint func(context.Context) (string, error)}@@ -74,18 +66,14 @@ func NewHTTP(options HTTPOptions) *HTTPProbe {client: &http.Client{Timeout: options.Timeout,Transport: &http.Transport{- // TLS session resumption does not repeat chain verification, so- // 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.+ // Resumption does not repeat chain verification, and a nil cache+ // is what disables it.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- // needs to be able to observe.+ // Setting TLSClientConfig disables automatic HTTP/2.ForceAttemptHTTP2: true,},CheckRedirect: func(*http.Request, []*http.Request) error {@@ -164,9 +152,8 @@ func (p *HTTPProbe) Run(ctx context.Context) Outcome {}defer func() { _ = response.Body.Close() }()- // The body must be read. Under TLS 1.3 a handshake rejection surfaces on- // the first read rather than at dial, so a probe that never reads reports- // success against a server that refused its identity.+ // Under TLS 1.3 a handshake rejection surfaces on the first read, not at+ // dial, so the body must be read.if _, err := io.Copy(io.Discard, response.Body); err != nil {outcome.Disposition = transportDisposition(err)outcome.Detail = fmt.Sprintf(detailError, err)@@ -181,9 +168,8 @@ func (p *HTTPProbe) Run(ctx context.Context) Outcome {return outcome}-// credential resolves what this request carries. A minted credential is never-// given a nonce: the mint already produced a fresh one, and appending to a-// signed token would corrupt it into a different fault than the one armed.+// credential never nonces a minted token, because appending to a signed token+// would corrupt it into a different fault than the one armed.func (p *HTTPProbe) credential(ctx context.Context) (string, error) {if p.options.Mint != nil {return p.options.Mint(ctx)@@ -207,8 +193,8 @@ func transportDisposition(err error) Disposition {return Unavailable}-// statusDisposition maps a status to what it says about the CREDENTIAL, which-// is not the same question as whether the request succeeded.+// statusDisposition maps a status to what it says about the CREDENTIAL, not to+// whether the request succeeded.func statusDisposition(status int) Disposition {switch {case status == http.StatusTooManyRequests:@@ -218,9 +204,7 @@ func statusDisposition(status int) Disposition {case status >= http.StatusInternalServerError:return Unavailablecase status >= http.StatusMultipleChoices && status < http.StatusBadRequest:- // A redirect is how most browser-facing gateways refuse an- // unauthenticated request, and it is also how they route an- // authenticated one. It decides nothing about the credential.+ // Gateways refuse and route the same way, so this decides nothing.return Redirectedcase status >= http.StatusOK && status < http.StatusMultipleChoices:return Accepteddiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/probe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/probe.goindex fe527a12..c1a0b4a3 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/probe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/probe.go@@ -11,8 +11,8 @@ import (type Disposition stringconst (- // Unknown is the zero value on purpose: a half-built Outcome must read as- // obviously wrong rather than as a plausible target failure.+ // Unknown is the zero value on purpose, so a half-built Outcome reads as+ // wrong rather than as a target failure.Unknown Disposition = "unknown"Accepted Disposition = "accepted"@@ -22,9 +22,7 @@ const (Unavailable Disposition = "unavailable"TimedOut Disposition = "timed-out"- // ProbeFailed is khaos's own fault, never the target's. It is excluded from- // every rate, because folding a tool bug into a target outcome manufactures- // findings out of a typo in --url.+ // ProbeFailed is khaos's own fault and is excluded from every rate.ProbeFailed Disposition = "probe-failed")@@ -56,45 +54,25 @@ const (Valid Credential = "valid"Invalid Credential = "invalid"- // Revoked is a credential that was LEGITIMATELY accepted and that khaos then- // revoked at the authority during the fault. It is a third kind rather than a- // flavour of Invalid because the two make different claims: an invalid- // credential was never acceptable, and a revoked one was and then stopped- // being. Reporting the second as the first would say the target honoured- // something it had already rejected, which is not what happened.+ // Revoked was legitimately accepted and then revoked at the authority,+ // which is a different claim from never having been acceptable.Revoked Credential = "revoked"- // Forged is a credential khaos MINTED to be wrong in exactly one named way,- // and confirmed wrong at the provider before presenting it. It is a fourth- // kind rather than a flavour of Invalid because the claims differ again, and- // because the baseline requirement is different: the invalid stream has to be- // REJECTED during the baseline to prove the target enforces anything at all,- // while a forged stream's baseline requirement depends on the trap and is- // declared by the experiment.- //- // Folding it into Invalid also breaks the run outright for the traps whose- // forged credential is accepted at steady state: the baseline check would- // report "the invalid credential was never rejected" and void the run, which- // is khaos refusing to report the very finding it went looking for.+ // Forged was minted to be wrong in exactly one named way. Its baseline+ // depends on the trap, so it cannot be folded into Invalid.Forged Credential = "forged")// Expectation is what a stream must do during the baseline for the fault window-// to mean anything. It is DECLARED per experiment rather than derived, because-// it points in opposite directions for traps that look alike: a token forged to-// be malformed has to be refused before the fault, and a token that is correct-// until the provider is armed has to be ACCEPTED before it.+// to mean anything. It is declared per experiment rather than derived, because+// it points in opposite directions for traps that look alike.type Expectation stringconst (- // ExpectAccepted is the liveness guard for a trap whose credential is- // honest until the fault lands. If the target never accepted one, it was not- // trusting khaos's provider and its later refusals say nothing.+ // ExpectAccepted: a target that never accepted was not trusting khaos.ExpectAccepted Expectation = "accepted"- // ExpectRejected is the enforcement guard for a trap whose credential is- // already malformed. If the target never refused one, it was not checking- // the thing the fault is about to break.+ // ExpectRejected: a target that never refused was not checking.ExpectRejected Expectation = "rejected")@@ -122,17 +100,14 @@ type Probe interface {Run(context.Context) Outcome}-// Pair is the valid probe and its negative control. Revoked and Forged are-// optional, and only the experiments that revoke or forge a credential set them;-// the two-stream verdict logic is untouched when both are nil.+// Pair is the valid probe and its negative control; Revoked and Forged are+// optional.type Pair struct {Valid ProbeInvalid ProbeRevoked ProbeForged Probe- // ForgedBaseline is what the forged stream must do before the fault. It is- // meaningless without Forged and the verdict ignores it then.ForgedBaseline Expectation}@@ -140,8 +115,7 @@ func (p Pair) Complete() bool {return p.Valid != nil && p.Invalid != nil}-// All returns the probes to fire, in a stable order so a sampling pass produces-// comparable streams.+// All returns the probes to fire, in a stable order.func (p Pair) All() []Probe {probes := []Probe{p.Valid, p.Invalid}if p.Revoked != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.goindex fa9311af..331c7a5b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/probe/sample.go@@ -56,13 +56,9 @@ func (s Stream) Distribution() map[Disposition]int {return out}-// AcceptedAfter is the monotonicity test for a control that stopped enforcing.-// A plain "anything was accepted" check is wrong twice over: a service that-// keeps serving a still-valid credential during an outage is behaving-// correctly, and an acceptance that happened before the target ever rejected-// anything is a warm-up, not a control giving way. The caller seeds `rejected`-// from an earlier phase so a baseline blip cannot be counted as a fault-phase-// leak.+// AcceptedAfter counts only acceptances that follow a refusal, because an+// acceptance before the target ever refused anything is a warm-up. The caller+// seeds rejected from an earlier phase.func (s Stream) AcceptedAfter(rejected bool) int {count := 0@@ -75,10 +71,7 @@ func (s Stream) AcceptedAfter(rejected bool) int {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.+ // Not evidence either way, so neither the count nor the latch moves.}}@@ -89,31 +82,8 @@ func (s Stream) AcceptedAfterRejected() int {return s.AcceptedAfter(false)}-// AcceptedSinceLastRefusal counts acceptances that were never followed by a-// refusal, which is the order-sensitive test for a credential khaos invalidated-// at an authority.-//-// Counting every acceptance in the window is wrong, and wrong in the direction-// that manufactures findings. A target with a correct BOUNDED cache serves the-// invalidated credential for exactly as long as its cache lifetime and then-// refuses it forever: accept, accept, refuse, refuse, refuse. That is the-// defensible bounded-stale pattern, and a plain count reports it as a bypass.-//-// The two shapes separate completely on this test. A bounded cache lapses and-// scores zero; a cache that is being re-armed, or that has no expiry, never-// lapses and scores every acceptance. A target that refuses and then accepts-// again also scores, which is correct: re-populating a decision for a credential-// it has already refused is its own bug.-//-// This is the exact mirror of RejectedAfter, which exists because the same-// fixture served a valid credential from cache for the first seconds of an-// outage and "was it ever accepted" reported that as a clean survival.-// AcceptedSpan is the time from the first acceptance in this stream to the last.-//-// For a credential khaos invalidated it is research 07 section 2.2's-// `stale_accept_window`, which that table calls "the real exposure window of a-// leaked key". It is a LOWER BOUND and never a cache lifetime: khaos stopped-// looking when the window ended, so the true span can only be longer.+// AcceptedSpan is a LOWER BOUND and never a cache lifetime, because khaos+// stopped looking when the window ended.func (s Stream) AcceptedSpan() time.Duration {var first, last time.Time@@ -134,6 +104,8 @@ func (s Stream) AcceptedSpan() time.Duration {return last.Sub(first)}+// AcceptedSinceLastRefusal is the trailing run of acceptances, so a bounded+// cache that lapses and stays lapsed scores zero.func (s Stream) AcceptedSinceLastRefusal() int {count := 0@@ -144,31 +116,16 @@ func (s Stream) AcceptedSinceLastRefusal() int {case Accepted:count++default:- // Neither an acceptance nor a refusal, so the run is neither- // extended nor broken by it.+ // Neither extends nor breaks the run.}}return count}-// AcceptedDespiteLapse counts acceptances that a correct bounded cache cannot-// explain: every acceptance when the stream never lapsed at all, and only the-// acceptances that FOLLOW a refusal when it did.-//-// AcceptedSinceLastRefusal gets the first case right and silently destroys the-// second. It keeps only the trailing run, so `Rejected, Accepted, Rejected`-// scores zero — the target refused the invalidated credential, honoured it-// again, and then refused it once more, and khaos forgot the middle. That-// sequence is reachable across inconsistent verifier replicas, and it is a-// worse finding than the one this function exists to report: enforcement had-// already resumed and the credential got through anyway.-//-// The two cases are different claims and both are kept:-//-// A A A A never lapsed -> 4, the cache is not bounded by anything observed-// A A R R R lapsed and stayed -> 0, the defensible bounded-stale pattern-// R A R came back after a lapse -> 1, enforcement resumed and was then bypassed+// AcceptedDespiteLapse counts acceptances a correct bounded cache cannot+// explain: all of them when the stream never lapsed, and only the ones+// following a refusal when it did.func (s Stream) AcceptedDespiteLapse() int {if !s.Any(Rejected) {return s.Count(Accepted)@@ -178,9 +135,8 @@ func (s Stream) AcceptedDespiteLapse() int {}// RejectedAfter is the mirror of AcceptedAfter, for the credential that should-// be honoured. A target that served from a cache for the first seconds of an-// outage and then started refusing has stopped serving, and asking only-// whether it ever served reports that as a clean survival.+// be honoured: a target that served from cache and then started refusing has+// stopped serving.func (s Stream) RejectedAfter(accepted bool) int {count := 0@@ -207,8 +163,7 @@ type Window struct {Forged Stream `json:"forged,omitempty"`}-// Paired is the number of samples where both halves of the pair exist, which-// is what a comparative verdict can actually be built from.+// Paired is the number of samples where both halves of the pair exist.func (w Window) Paired() int {return min(w.Valid.Countable(), w.Invalid.Countable())}@@ -217,15 +172,8 @@ func (w Window) Len() int {return w.Paired()}-// Requests is how many probe requests this window actually issued, across every-// stream. It is the denominator for any per-REQUEST ratio, and Paired is not:-// one paired sample is at least two requests, because the pair fires both-// streams per iteration.-//-// The distinction had a cost. A guard comparing a count of the target's DNS-// queries against Paired() was comparing queries to half the requests, and with-// Go's A-plus-AAAA fan-out on top it tripped at one lookup per four requests-// while its own message claimed "a fresh lookup per request".+// Requests is the denominator for a per-REQUEST ratio, and Paired is not: one+// paired sample is at least two requests.func (w Window) Requests() int {return w.Valid.Countable() +w.Invalid.Countable() +diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.goindex d263cc7d..c766b208 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go@@ -30,39 +30,22 @@ const (ProxiedGatewayName = "khaos-range-gateway-proxied"VerifierGatewayName = "khaos-range-gateway-verifier"- // TLSGatewayName is the FOURTH gateway. Each one exists so a single- // injection tier is measured on a path nothing else contaminates: this one- // reaches its dependency over TLS and khaos's certificate authority plays- // that dependency, so a certificate fault lands on a path no other gateway- // uses.TLSGatewayName = "khaos-range-gateway-tls"- // DNSGatewayName is the FIFTH gateway, and the only one that reaches its- // dependency BY NAME through khaos's chaos resolver. RogueName is the- // service a redirect fault points it at, and ResolverName is the resolver- // itself.DNSGatewayName = "khaos-range-gateway-dns"RogueName = "khaos-range-rogue"ResolverName = "khaos-range-resolver"- // The addresses the DNS tier PINS, and they are pinned because they have to- // be. `dns:` on the gateway and the resolver's zone are both fixed at- // container creation, so neither can be filled in from an address khaos- // discovered afterwards. The range network declares its own subnet so Docker- // will accept them.+ // Pinned because `dns:` on the gateway and the resolver's zone are fixed at+ // container creation, so neither can be filled from a discovered address.ResolverAddress = "10.244.244.5"DependencyAddress = "10.244.244.10"RogueAddress = "10.244.244.20"- // DNSDependencyName is the name the DNS gateway asks for. It is NOT a- // container name or a network alias, and that is measured rather than- // stylistic: the target's own embedded resolver answers those out of its own- // table and never forwards them, so a fault aimed at one would never be- // seen.+ // NOT a container name or a network alias: the target's own embedded+ // resolver answers those from its own table and never forwards them.DNSDependencyName = "dependency.khaos.test."- // DNSControlName is the name khaos's resolver answers that no fault ever- // touches, used as the confirmation oracle's positive control.DNSControlName = "control.khaos.invalid."IDPName = "khaos-range-idp"@@ -82,36 +65,17 @@ const (EnvTLSPort = "KHAOS_RANGE_TLS_PORT"- // EnvDNSPort is the DNS gateway's published port, and EnvResolverNonce- // authorises its resolver's control surface. The nonce goes in the compose- // environment because the resolver's command line is fixed at container- // creation, and khaos reads it BACK off the container's label rather than- // remembering what it chose.EnvDNSPort = "KHAOS_RANGE_DNS_PORT"EnvResolverNonce = "KHAOS_RANGE_RESOLVER_NONCE"- // The two ports khaos binds in its OWN process for the certificate tier.- // They go into the compose file because the gateway's environment is fixed- // at container creation and it has to know where to look.EnvAuthorityPort = "KHAOS_RANGE_AUTHORITY_PORT"EnvDependencyPort = "KHAOS_RANGE_TLS_DEPENDENCY_PORT"- // EnvDependency is the URL the TLS gateway dials for its dependency, and- // EnvAuthorityBase is where it fetches revocation data. khaos reads BOTH- // back from the container rather than remembering what it chose, for the- // same reason it reads the issuer back: the container addresses- // `host.docker.internal` and khaos binds a numeric bridge address, so the- // strings differ for the same endpoint.EnvDependency = "KHAOS_RANGE_DEPENDENCY"EnvAuthorityBase = "KHAOS_RANGE_AUTHORITY_BASE"- // EnvCertHost is the name the TLS gateway asks for in its handshake. khaos- // mints for exactly this, or every certificate is refused on the hostname- // for a reason that has nothing to do with the trap.EnvCertHost = "KHAOS_RANGE_CERT_HOST"- // EnvTLSMode selects which reference client the TLS gateway runs, so the- // range can be a correct client or any one of the broken ones.EnvTLSMode = "KHAOS_RANGE_TLS_MODE"composeDir = "range"@@ -120,8 +84,7 @@ const (dockerBinary = "docker"loopback = "127.0.0.1"- // Every host port khaos binds is a randomly chosen high one. The port a- // service conventionally uses is the one most likely already taken.+ // A conventional port is the one most likely already taken on the host.portFloor = 30000portCeil = 60000portTries = 40@@ -150,10 +113,8 @@ const (stderrLines = 4teardownPort = 1- // teardownNonce satisfies the compose file's required variable during a- // teardown, where no resolver is being created and the value is never used.- // The alternative is `range down` failing on a missing variable, which would- // leave the range running with no way to remove it.+ // The compose file requires every variable even for a teardown that creates+ // no resolver, or `range down` fails and the range cannot be removed at all.teardownNonce = "teardown"EnvComposeDir = "KHAOS_RANGE_DIR"@@ -172,18 +133,8 @@ const (errNoRangeResolver = "%w: this experiment arms khaos's chaos resolver, and the running range has no %s; bring the range down and up again to create it")-// Port is the direct gateway's published port. ProxiedPort is the second-// gateway's, the one whose upstream runs through khaos's fault proxy, and-// ProxyPort is where that gateway expects to find the proxy on the host.-// VerifierPort is the third gateway's, the one whose identity provider is khaos-// itself, and IdPPort is where that gateway expects to find khaos's in-process-// provider.-//-// Both khaos-side ports are chosen at `range up` rather than at run time,-// because extra_hosts and environment are fixed at container creation and-// cannot be changed on a running container. khaos then reads each one back out-// of the container that will dial it, because the container is the only-// authority on where it will actually look.+// Lab is a located range. The khaos-side ports are chosen at `range up` rather+// than at run time, because a container's environment is fixed at creation.type Lab struct {Dir stringPort int@@ -192,40 +143,22 @@ type Lab struct {VerifierPort intIdPPort int- // TLSPort is the gateway's published port. AuthorityPort and- // DependencyPort are where khaos binds its own two listeners, and they are- // held here only so `range up` can put them in the compose environment:- // once the range is running, khaos reads the addresses back out of the- // gateway's own configuration rather than trusting these.TLSPort intAuthorityPort intDependencyPort int- // DNSPort is the DNS gateway's published port. ResolverNonce is held only- // so `range up` can put it in the compose environment; once the range is- // running khaos reads it back off the resolver container's own label.DNSPort intResolverNonce string- // Dependency, AuthorityBase and CertHost are read back from the TLS- // gateway's own environment, never remembered from what `range up` chose.- // The container is the only authority on where it will actually look and- // what name it will ask for.+ // Read back from the TLS gateway's own environment, never remembered.Dependency stringAuthorityBase stringCertHost string- // TLSMode is which reference client the TLS gateway is running. It is read- // back like the others and is the only one of them that is optional,- // because the gateway has a working default and khaos needs this purely to- // tell an operator what the fixture is currently being.TLSMode string- // Issuer is the EXACT string the verifier gateway was configured with, read- // back from its environment. khaos has to mint tokens whose `iss` matches it- // character for character: khaos binds the bridge gateway's address and the- // container addresses `host.docker.internal`, so the address khaos listens- // on is never the string the target expects.+ // Issuer is the EXACT string the gateway was configured with, which khaos+ // mints `iss` to match; the address khaos listens on is never that string.Issuer string}@@ -257,24 +190,16 @@ type Ports struct {Verifier intIdP int- // TLS is the gateway's own published port. Authority and Dependency are the- // two listeners KHAOS binds in its own process: the revocation endpoints- // and the faulted dependency. The compose file needs all three, because the- // gateway addresses the last two and its environment is fixed at container- // creation.TLS intAuthority intDependency int- // DNS is the DNS gateway's own published port. The resolver publishes- // NOTHING: it listens on 53 inside its own network namespace, which is the- // entire reason that tier needs no capability.+ // The resolver publishes NOTHING: it listens on 53 inside its own network+ // namespace, which is why that tier needs no capability.DNS int}-// FreePorts picks every host port the range needs in one go, all distinct. Each-// one is a random high port: the port a service conventionally uses is the one-// most likely already taken.+// FreePorts picks every host port the range needs in one go, all distinct.func FreePorts() (Ports, error) {taken := map[int]bool{}@@ -342,14 +267,9 @@ func composePath() (string, error) {return "", fmt.Errorf(errNoCompose, EnvComposeDir)}-// VerifyOwned refuses any compose file that is not khaos's own. Without it,-// pointing KHAOS_RANGE_DIR at another project turns `khaos range down` into-// `docker compose down --volumes` against that project, which destroys its-// named volumes and reports success. khaos's own "set KHAOS_RANGE_DIR" error-// message is what teaches an operator to set that variable.+// VerifyOwned refuses any compose file that is not khaos's own, or pointing+// KHAOS_RANGE_DIR elsewhere makes `range down` destroy another project.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 functionraw, err := os.ReadFile(path)if err != nil {@@ -393,8 +313,6 @@ 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 testedport := portFloor + rand.IntN(portCeil-portFloor)@@ -424,9 +342,6 @@ func (l Lab) ProtectedURL() string {return l.GatewayURL() + protectedPath}-// ProxiedGatewayURL addresses the gateway whose own upstream runs through khaos's-// fault proxy. A proxy-tier experiment probes this one, because it is the only-// service in the range whose dependency khaos sits in front of.func (l Lab) ProxiedGatewayURL() string {return "http://" + net.JoinHostPort(loopback, strconv.Itoa(l.ProxiedPort))}@@ -472,11 +387,6 @@ func (l Lab) Up(}func (l Lab) Down(ctx context.Context, out io.Writer) error {- // The compose file requires every port variable so a bare `docker compose up`- // cannot bind a fixed one. Tearing down binds nothing, so any value parses,- // but every required variable must still be present or compose refuses to- // read the file at all and the teardown fails for a reason that has nothing- // to do with the teardown.environ := append(os.Environ(),EnvGatewayPort+"="+strconv.Itoa(teardownPort),EnvProxiedPort+"="+strconv.Itoa(teardownPort),@@ -508,8 +418,8 @@ func (l Lab) compose(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.+ // Passed explicitly as well as declared, so no edit to the file can point+ // these commands at another project.full := append([]string{"compose",projectFlag, ProjectName,@@ -523,8 +433,6 @@ func (l Lab) compose(cmd.Dir = l.Dircmd.Env = environcmd.Stdout = out- // The diagnostic never goes to the progress stream: --quiet discards that,- // and the one time an operator needs the cause is the time it failed.cmd.Stderr = io.MultiWriter(out, &stderr)if err := cmd.Run(); err != nil {@@ -534,8 +442,8 @@ func (l Lab) compose(return nil}-// PortTaken reports whether compose refused because the chosen host port was-// bound between khaos testing it and compose binding it.+// PortTaken reports whether a host port was bound between khaos testing it and+// compose binding it.func PortTaken(err error) bool {return err != nil && strings.Contains(err.Error(), errPortTaken)}@@ -572,8 +480,6 @@ func (l Lab) awaitReady(ctx context.Context) error {return fmt.Errorf(errNotReady, readyTimeout)}-// 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,@@ -635,9 +541,6 @@ type PortReader interface {BridgeGateway(ctx context.Context) (string, error)}-// Discover finds a running range and the host port it ended up on, so khaos can-// point an experiment at it without the operator repeating what khaos already-// knows.func Discover(ctx context.Context, reader PortReader) (Lab, error) {targets, err := reader.Targets(ctx, dockerx.Filter{Project: ProjectName})if err != nil {@@ -663,9 +566,8 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {lab := Lab{Port: port}- // The proxied gateway is discovered separately and its absence is not fatal:- // a Docker-native experiment has no use for it, and failing the whole- // discovery over it would break every experiment that does not need a proxy.+ // Each further gateway is discovered separately and its absence is not+ // fatal, because the experiments that do not need it must still work.proxied, ok := running[ProxiedGatewayName]if !ok {return lab, nil@@ -683,9 +585,6 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {return Lab{}, err}- // The verifier gateway is discovered on the same terms: absent is not fatal,- // because every experiment that does not arm khaos's own provider has no use- // for it and failing the whole discovery over it would break all of them.verifierGateway, ok := running[VerifierGatewayName]if !ok {return lab, nil@@ -707,10 +606,6 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {return Lab{}, err}- // The TLS gateway is discovered on the same terms as the other two: absent- // is not fatal, because every experiment that does not arm khaos's own- // certificate authority has no use for it, and failing the whole discovery- // over it would break all of them.tlsGateway, ok := running[TLSGatewayName]if !ok {return lab, nil@@ -739,10 +634,6 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {return lab, nil}-// readDNSTier discovers the DNS gateway's published port, on the same terms as-// the other three gateways: absent is not fatal, because every experiment that-// does not arm khaos's chaos resolver has no use for it, and failing the whole-// discovery over it would break all of them.func (l *Lab) readDNSTier(ctx context.Context,reader PortReader,@@ -763,10 +654,6 @@ func (l *Lab) readDNSTier(return nil}-// readAuthorityWiring reads the three strings the TLS gateway was configured-// with, out of its own environment, for the same reason issuerOf does: the-// container is the only authority on what it will dial, where it will fetch-// revocation data, and what name it will ask for.func (l *Lab) readAuthorityWiring(ctx context.Context,reader PortReader,@@ -798,25 +685,12 @@ func (l *Lab) readAuthorityWiring(*want.into = value}- // Optional, because the gateway has a working default for it and nothing- // khaos decides depends on the value. It is read only so `range up` can- // tell an operator which client the fixture is being.+ // Optional: the gateway has a working default for this one.l.TLSMode = environ[EnvTLSMode]return nil}-// issuerOf reads the issuer out of the verifier gateway's own environment rather-// than remembering what `range up` chose, for the same reason proxyPortOf does:-// the container is the only authority on what it will actually dial and on what-// `iss` it will accept.-//-// Both halves matter. The port is where khaos has to bind, and the STRING is-// what khaos has to put in every token it mints, character for character. khaos-// binds the bridge gateway's numeric address while the container addresses-// `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,@@ -862,9 +736,6 @@ func issuerOf(return strings.TrimSuffix(issuer, "/"), port, nil}-// VerifierGatewayURL addresses the gateway whose identity provider is khaos-// itself. Every experiment that arms khaos's provider probes this one, because-// it is the only service in the range that resolves keys from khaos.func (l Lab) VerifierGatewayURL() string {return "http://" + net.JoinHostPort(loopback, strconv.Itoa(l.VerifierPort))}@@ -877,12 +748,8 @@ func (l Lab) TLSGatewayURL() string {return "http://" + net.JoinHostPort(loopback, strconv.Itoa(l.TLSPort))}-// RequireDNSTier refuses a DNS experiment against a range that has no DNS-// gateway, BY NAME, before anything is probed.-//-// A missing gateway otherwise surfaces as a published port of zero, so khaos-// probes `http://127.0.0.1:0/protected`, nothing answers, and the run blames the-// target for not enforcing when khaos was pointing at nowhere.+// RequireDNSTier refuses by name, because a missing gateway otherwise surfaces+// as a published port of zero and the run blames the target for not enforcing.func (l Lab) RequireDNSTier() error {if l.DNSPort == 0 {return fmt.Errorf(@@ -911,19 +778,8 @@ func (l Lab) TLSProtectedURL() string {return l.TLSGatewayURL() + protectedPath}-// AuthorityEndpoint says where khaos must bind its certificate authority's two-// listeners, and the two strings it must mint under.-//-// The listen addresses are the DEFAULT bridge's gateway, discovered rather than-// assumed, which is the same measured fact the fault proxy and the identity-// provider both rest on: a container reaches a host listener there, a listener-// on the target network's own gateway is unreachable, and binding only loopback-// leaves khaos dead to every container.-//-// The base URL and the certificate host come back UNCHANGED from the gateway's-// own environment. They are what the container will actually use, and khaos-// binding one address while minting for another is how every credential ends up-// refused for a reason unrelated to the fault.+// AuthorityEndpoint binds on the DEFAULT bridge's gateway, since the range+// network's own gateway and loopback are both unreachable from a container.func (l Lab) AuthorityEndpoint(ctx context.Context,reader PortReader,@@ -959,22 +815,16 @@ func (l Lab) AuthorityEndpoint(}, nil}-// AuthorityWiring is everything a certificate experiment needs to stand khaos's-// authority up where the TLS gateway is already looking for it.+// AuthorityWiring stands khaos's authority up where the gateway already looks.type AuthorityWiring struct {- // Listen and TLS are host addresses khaos binds.Listen stringTLS string- // Base is the URL the TARGET uses for revocation, and Host is the name it- // asks for. Neither is derived from the addresses above.+ // The TARGET's own revocation URL and hostname, not derived from the above.Base stringHost string}-// portOfURL reads the port the container was configured to use. khaos binds-// THAT port on the bridge address, because the container is already addressing-// it and khaos does not get to pick.func portOfURL(raw string) (int, error) {parsed, err := url.Parse(raw)if err != nil {@@ -1001,14 +851,6 @@ func portOfURL(raw string) (int, error) {return port, nil}-// IdPEndpoint says where khaos must bind its in-process identity provider and-// which issuer string it must mint under.-//-// The listen address is the DEFAULT bridge's gateway, discovered rather than-// assumed, which is the same measured fact the fault proxy rests on: a container-// 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,@@ -1029,11 +871,6 @@ func (l Lab) IdPEndpoint(return net.JoinHostPort(gatewayIP, strconv.Itoa(l.IdPPort)), l.Issuer, nil}-// proxyPortOf reads the port out of the proxied gateway's own upstream setting,-// rather than remembering what `range up` chose. The container's environment is-// 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,@@ -1079,16 +916,8 @@ func proxyPortOf(return port, nil}-// AuthorityURL is khaos's OWN path to the identity provider, bypassing whatever-// the target uses. It is the container's address on the range network, reachable-// from the host directly.-//-// This is what makes a revocation real and unreachable at the same time, and it-// is the reason an identity experiment severs the target's path with khaos's-// proxy rather than pausing the provider. A paused provider is unreachable by-// 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.+// AuthorityURL is khaos's OWN path to the provider, which is why an identity+// experiment severs the target's path instead of pausing the provider.func (l Lab) AuthorityURL(ctx context.Context,reader PortReader,@@ -1117,14 +946,8 @@ func (l Lab) AuthorityURL(return "", ErrNoRange}-// ProxyEndpoint says where khaos must bind its fault proxy and what that proxy-// must forward to.-//-// The listen address is the DEFAULT bridge's gateway, which is measured: a-// container reaches a host listener there, a listener on the target network's own-// 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.+// ProxyEndpoint says where khaos binds its fault proxy, never a wildcard: that+// would expose a deliberately vulnerable stack on the operator's network.func (l Lab) ProxyEndpoint(ctx context.Context,reader PortReader,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.goindex 8e3eab5a..ae1e1c08 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/injector.go@@ -19,7 +19,7 @@ type Resolver interface {}// Injector adapts a Session to the experiment engine, so the engine never-// touches Docker, a journal or a lease and stays testable without a daemon.+// touches Docker, a journal or a lease.type Injector struct {Session *SessionResolver Resolver@@ -59,13 +59,9 @@ func (i *Injector) Inject(ctx context.Context, kind, target string) error {return nil}-// Confirm reads the fault back from the daemon. An injection the API accepted-// is not the same as a fault that took effect, and a run that measures an-// unconfirmed fault is indistinguishable from a run with no fault at all,-// which reads as a pass.-// The method reported is the one each mutation actually measured, not a constant-// naming the technique. A run record that says how the fault was confirmed is-// auditable; one that says only that something was confirmed is not.+// Confirm reads the fault back from the daemon, because an injection the API+// accepted is not the same as a fault that took effect, and a run measuring no+// fault at all reads as a pass.func (i *Injector) Confirm(ctx context.Context) (string, error) {first := ""diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.goindex 8d39c74a..a1f48f00 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/reclaim.go@@ -14,8 +14,7 @@ import ("github.com/CarterPerez-dev/khaos/internal/lock")-// settleSuffix mirrors statedir.Paths.Settle. The journal knows its own path and-// the lock sits beside it, so the two cannot drift to different files.+// settleSuffix mirrors statedir.Paths.Settle.const settleSuffix = ".settle"type Reclaimed struct {@@ -43,14 +42,10 @@ func (s Sweep) Failed() bool {return false}-// Reclaim settles outstanding mutations. It holds the settle lock for the whole-// pass, so a renewal cannot read a record as live, stall, and then write back a-// fresh expiry for a fault this sweep has already undone — nor can this sweep-// revert a fault a renewal extended a moment earlier.-//-// The lock is advisory and best-effort: if it cannot be taken, the sweep still-// runs. A dead man's switch that refuses to fire because a lock file is-// unavailable is worse than one that races.+// Reclaim settles outstanding mutations, holding the settle lock for the whole+// pass so a renewal and a sweep cannot undo each other's work. The lock is+// best-effort: a dead man's switch that will not fire is worse than one that+// races.func Reclaim(ctx context.Context,env inject.Env,@@ -87,17 +82,9 @@ func reclaimWith(continue}- // A fault on another daemon is left ALONE, and left outstanding.- //- // Reverting it here cannot work and does not fail cleanly: the container- // ID does not exist on this daemon, the SDK says NotFound, khaos reads- // that as "the target is gone so the fault went with it" and writes- // REVERTED. The fault stays applied on the machine that actually has it- // and no later sweep will ever look at it again.- //- // 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.+ // A fault on another daemon is left outstanding. Reverting it here+ // would not fail cleanly: the ID is NotFound on this daemon, which+ // khaos would read as the target being gone and write REVERTED.if mismatch := daemonMismatch(record,attachedDaemon(env),@@ -118,8 +105,6 @@ func reclaimWith(return sweep}-// attachedDaemon is the identity of the daemon this sweep is attached to, or-// empty when there is no client.func attachedDaemon(env inject.Env) string {if env.Docker == nil {return ""@@ -127,13 +112,10 @@ func attachedDaemon(env inject.Env) string {return env.Docker.Daemon()}-// daemonMismatch reports why this sweep must not touch a record, or nil when it-// may.+// daemonMismatch reports why this sweep must not touch a record. Unknown on+// either side gets the benefit of the doubt, or every record written before+// the field existed would be stranded.func daemonMismatch(record journal.Record, here string) error {- // Unknown on either side is AMBIGUOUS, not a match and not a mismatch. A- // record predating this field, or a daemon that would not identify itself,- // gets the benefit of the doubt and is reverted: refusing instead would- // strand every fault written before this existed.if here == "" || record.Daemon == "" {return nil}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.goindex e6f91676..9bddcff8 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/run/session.go@@ -72,10 +72,8 @@ func newSessionWith(}}-// daemon is the identity of the daemon this session is attached to, or empty-// when there is none. A session built without a client is a test session; an-// empty value is already the "khaos could not establish it" case the reclaim-// path treats as ambiguous rather than as a match.+// daemon is empty when there is no client, which the reclaim path treats as+// ambiguous.func (s *Session) daemon() string {if s.env.Docker == nil {return ""@@ -142,15 +140,11 @@ func (s *Session) Inject(return s.log.Append(record)}-// Renew re-reads the journal before extending the lease. A mutation that some-// other process already reverted is dropped rather than resurrected, and a-// session whose faults have all been taken away stops renewing and says so,-// instead of continuing to claim a fault it no longer holds.+// Renew re-reads the journal first, so a mutation something else already+// reverted is dropped rather than resurrected.func (s *Session) Renew() error {- // The same settle lock Reclaim takes. Reading the outstanding set and- // appending the renewal are two operations, and the reaper runs beside this- // deliberately: without the lock a renewal could read a record as live,- // stall while a sweep reverted it, and then write back a fresh expiry.+ // The same settle lock Reclaim takes: read-then-append is two operations+ // and the reaper runs beside this.if settle, err := lock.Acquire(s.log.Path() + settleSuffix); err == nil {defer func() { _ = settle.Release() }()}@@ -197,9 +191,7 @@ 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.+ // Callers branch on ErrRevertFailed; the cause is diagnostic text.//nolint:errorlint // %v is deliberatereturn fmt.Errorf("%w: %v", ErrRevertFailed, firstErr)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.goindex 46290061..bc9fc393 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/shell/shell.go@@ -79,12 +79,8 @@ 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.+// leaveOrSayWhyNot is the interrupt path's leave. The callback cannot return an+// error, so a refusal has to be written here or Ctrl-D is a silent no-op.func leaveOrSayWhyNot(out io.Writer) {if err := leave(out); err != nil {_, _ = io.WriteString(out, err.Error()+newline)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.goindex 14ef46fd..b5154287 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/statedir/statedir.go@@ -56,11 +56,8 @@ func (p Paths) Journal() string {return filepath.Join(p.Root, journalName)}-// Settle is the short-lived lock around a read-decide-append transition on the-// journal. It is SEPARATE from Lock, which is the instance lock a run holds for-// its whole lifetime: the reaper deliberately runs beside a live run, so it-// cannot take that one, and without a second lock the two raced over the same-// records.+// Settle guards a read-decide-append on the journal. It is separate from Lock+// because the reaper runs beside a live run and cannot take that one.func (p Paths) Settle() string {return p.Journal() + ".settle"}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.goindex 19504b37..ef062919 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.go@@ -17,24 +17,15 @@ import (const (network = "tcp"- // MinimumModulusBits is khaos's reference key floor. x509 path validation- // has NO minimum of its own -- crypto/tls has a maximum of 8192 as the fix- // for CVE-2023-29409, and neither package has a floor -- so this is a policy- // the application imposes or nobody does.+ // x509 has no minimum of its own and crypto/tls only a maximum of 8192,+ // the fix for CVE-2023-29409, so a floor is the application's or nobody's.MinimumModulusBits = 2048- // MaximumLifetimeDays is the CA/Browser Forum leaf cap. Nothing outside a- // browser enforces it.+ // The CA/Browser Forum leaf cap, which nothing outside a browser enforces.MaximumLifetimeDays = 200- // DefaultTimeout bounds both the handshake and every revocation fetch. A- // client with no timeout cannot distinguish a slow responder from a dead- // one, and that distinction is a fault in its own right.DefaultTimeout = 5 * time.Second- // probeRequest is the smallest thing that makes a server answer. The- // RESPONSE is not inspected at all: the point is only whether the server- // was willing to send one.probeRequest = "GET / HTTP/1.1\r\nHost: khaos.probe\r\nConnection: close\r\n\r\n")@@ -55,45 +46,25 @@ const (reasonNoSigningUse = "the leaf's KeyUsage does not permit digital signatures")-// Config aims a reference client at one dependency.type Config struct {- // Mode decides which checks this client performs. Correct performs all of- // them.Mode Mode- // Host is the name the client asks for and expects to be in the- // certificate.Host string- // Roots is what the client trusts. For the trust-store faults this is the- // thing khaos changed.Roots *x509.CertPool- // Timeout bounds the handshake and every revocation fetch.Timeout time.Duration- // Now overrides the clock, so a freshness assertion does not race a real- // one.Now func() time.Time- // Identity is the CLIENT certificate this client presents, for a- // dependency that requires mutual TLS. Nil means none, which is itself a- // fault khaos can inject by withholding it.+ // Identity is the CLIENT certificate, and nil is a fault khaos can inject.Identity *tls.Certificate- // Sessions is the TLS session cache, and it has to be SHARED across- // connections or there is no resumption to test. A cache created per- // connection resumes nothing, which would make the- // policy-in-peer-callback mode indistinguishable from a correct one.+ // Sessions has to be SHARED across connections: a cache created per+ // connection resumes nothing, and resumption is the thing under test.Sessions tls.ClientSessionCache}-// Client is khaos's reference TLS client: what a correct consumer of a-// dependency's certificate does, and eleven named ways of doing it wrong.-//-// It is a teaching artifact as much as a test fixture. The Correct path is the-// code a reader should copy, which is why it performs the whole six-step CRL-// check rather than the two steps that are usually written.type Client struct {mode Modehost string@@ -107,9 +78,6 @@ type Client struct {http *http.Client}-// New builds a client. Every field has a working default except the mode and-// the host, because a client with no trust anchors and no name is not a client-// that can decide anything.func New(cfg Config) *Client {c := &Client{mode: cfg.Mode,@@ -138,42 +106,26 @@ func New(cfg Config) *Client {return c}-// Mode is which client this is.func (c *Client) Mode() Mode {return c.mode}-// Decision is one client's answer about one dependency.type Decision struct {- // Accepted is whether the client was willing to use the dependency.Accepted bool- // Reason is why it refused, empty when it accepted. It is for a human- // reading a khaos run, and tests assert on Accepted rather than on this.Reason string- // AskedCRL and AskedOCSP record whether the client actually went and- // looked. A client that accepted WITHOUT asking is a different finding from- // one that asked and was satisfied, and only these fields separate them.+ // Accepting WITHOUT asking is a different finding from asking and being+ // satisfied, and only these two fields separate them.AskedCRL boolAskedOCSP bool- // Resumed is whether this connection reused a TLS session instead of- // performing a full handshake. It is recorded because the resumption fault- // is otherwise unattributable: an acceptance on a resumed connection and an- // acceptance on a fresh one are the same observation until you know which- // happened.+ // Resumed, or the resumption fault is unattributable.Resumed bool}-// Decide connects to addr and reports whether this client was willing to use-// what it found there.-//-// The handshake and the policy are deliberately separate. crypto/tls is left to-// do the chain, the hostname and the validity window, because khaos-// re-implementing those would mean khaos's own bugs showing up as findings-// about the target. What this adds afterwards is only the layer Go does not-// have.+// Decide leaves the chain, the hostname and the validity window to crypto/tls,+// because khaos re-implementing those turns khaos's bugs into findings.func (c *Client) Decide(ctx context.Context,addr string,@@ -197,7 +149,6 @@ func (c *Client) Decide(return c.revocation(ctx, leaf, issuer, state)}-// handshake performs the TLS exchange under this mode's verification settings.func (c *Client) handshake(ctx context.Context,addr string,@@ -221,21 +172,8 @@ func (c *Client) handshake(state := tlsConn.ConnectionState()- // EVERY probe reads, and this is not optional politeness.- //- // Under TLS 1.3 a server's rejection of the client certificate does NOT- // surface at Dial. Research 04 section 7.2 measured the whole ClientAuth- // matrix and every single row returned a successful DialContext, including- // the rows where the server rejected the identity and served no bytes at- // all; the error arrives on the first read. Under TLS 1.2 the same case- // fails at Dial.- //- // So a dial-only probe reports GREEN against a server that refused it. That- // was this client's behaviour until the mTLS traps were built -- the- // previous comment here reasoned it away on the grounds that khaos used no- // client certificates, which stopped being true -- and it is now the- // DialOnly mode's declared defect rather than a property of the correct- // one.+ // Every probe reads: under TLS 1.3 a server's rejection of the client+ // certificate does NOT surface at Dial, only on the first read.if c.mode.reads() {if err := readOnce(tlsConn, c.timeout); err != nil {return tls.ConnectionState{}, err@@ -245,8 +183,6 @@ func (c *Client) handshake(return state, nil}-// readOnce writes a trivial request and waits for the first byte back, which is-// the cheapest way to find out whether the server is actually willing to talk.func readOnce(conn *tls.Conn, timeout time.Duration) error {if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {return err@@ -258,9 +194,8 @@ func readOnce(conn *tls.Conn, timeout time.Duration) error {buffer := make([]byte, 1)- // io.EOF is NOT accepted as success. A server that rejected the handshake- // and closed looks like a clean EOF to a reader that treats any completed- // read as proof of life, and that is the same fail-open one level down.+ // io.EOF is NOT success: a server that rejected the handshake and closed+ // reads as a clean EOF, which is the same fail-open one level down.if _, err := conn.Read(buffer); err != nil {return err}@@ -279,26 +214,19 @@ func (c *Client) tlsConfig() *tls.Config {cfg.Certificates = []tls.Certificate{*c.identity}}- // Sessions are only cached for a mode that declares it reuses them.- // Resumption is otherwise a property every mode would share, and the one- // defect it enables would be unattributable.+ // Only a mode that declares it reuses sessions gets a cache.if c.mode.resumes() && c.sessions != nil {cfg.ClientSessionCache = c.sessions}if !c.mode.checksChain() {- // InsecureSkipVerify in one assignment turns off the chain, the name- // and the validity window together. That breadth is the reason it is- // the most common fail-open in real code.cfg.InsecureSkipVerify = truereturn cfg}if !c.mode.checksHostname() {- // The chain is still checked, by hand, with the name left out. Go has- // no setting for this, which is why a client that wants it has to- // reimplement verification and usually gets something else wrong too.+ // Go has no setting for this, so it is reimplemented by hand.cfg.InsecureSkipVerify = truecfg.VerifyPeerCertificate = c.verifyWithoutName@@ -306,8 +234,6 @@ func (c *Client) tlsConfig() *tls.Config {}if c.mode == TrustPresentedCA {- // Anchoring on whatever arrived accepts any self-consistent chain,- // including one minted by anybody at all.cfg.InsecureSkipVerify = truecfg.VerifyPeerCertificate = c.verifyAgainstPresented@@ -317,8 +243,6 @@ func (c *Client) tlsConfig() *tls.Config {return cfg}-// verifyWithoutName does the full path check and omits the hostname, which is-// the SkipHostname fault.func (c *Client) verifyWithoutName(raw [][]byte,_ [][]*x509.Certificate,@@ -337,8 +261,6 @@ func (c *Client) verifyWithoutName(return err}-// verifyAgainstPresented anchors on the chain the server sent, which is the-// TrustPresentedCA fault.func (c *Client) verifyAgainstPresented(raw [][]byte,_ [][]*x509.Certificate,@@ -397,9 +319,6 @@ func parseChain(raw [][]byte) (return leaf, pool, nil}-// issuerOf is whichever certificate signed the leaf, taken from the verified-// chain where there is one and from the presented chain otherwise. Revocation-// needs it to check a CRL signature or an OCSP response.func (c *Client) issuerOf(state tls.ConnectionState) *x509.Certificate {for _, chain := range state.VerifiedChains {if len(chain) > 1 {@@ -411,14 +330,10 @@ func (c *Client) issuerOf(state tls.ConnectionState) *x509.Certificate {return state.PeerCertificates[1]}- // A self-signed leaf is its own issuer, which is the honest answer rather- // than nil: a revocation question about it is still answerable.return state.PeerCertificates[0]}-// policy is the pair of checks crypto/x509 does not have. A mode without them-// is not breaking any rule Go enforces, which is exactly why the traps they-// catch are the ones that reveal whether a target has a policy of its own.+// policy is the checks crypto/x509 does not have.func (c *Client) policy(leaf *x509.Certificate) (string, bool) {if c.mode.checksKeyFloor() {if bits, ok := modulusBits(leaf); ok &&@@ -437,9 +352,7 @@ func (c *Client) policy(leaf *x509.Certificate) (string, bool) {if c.mode.checksKeyUsage() &&leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {// RFC 5280 section 4.2.1.3: a leaf without digitalSignature cannot be- // used for a TLS handshake. Verify enforces EXTENDED key usage and- // never reads these bits, so this check exists in the application or- // nowhere.+ // used for TLS, and Verify never reads these bits, only extended ones.return reasonNoSigningUse, false}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.goindex accf06d0..8a4d2a74 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.go@@ -10,113 +10,54 @@ import ("strings")-// Mode is one way a TLS client can be wrong, drawn from the fail-open taxonomy-// in research 04 and 07.-//-// Correct is a REFERENCE IMPLEMENTATION, not a wrapper around crypto/tls.-// Go verifies the chain, the hostname and the validity window and then stops,-// because `crypto/x509` performs no revocation checking of any kind. So the-// correct client here is Go's verification PLUS the layer Go does not have:-// the six-step CRL check, OCSP with freshness and certificate binding, a key-// floor and a lifetime policy. Every broken mode below removes exactly one-// piece of that layer, which is what makes a differential meaningful.+// Mode is one way a TLS client can be wrong. crypto/x509 performs no+// revocation checking of any kind, so Correct is a REFERENCE IMPLEMENTATION+// rather than a wrapper, and each mode below removes one piece of it.type Mode stringconst (- // Correct refuses everything a correct client should refuse. It is the- // control for every other mode and the only one khaos ships as an example- // worth copying.+ // Correct refuses everything a correct client should refuse.Correct Mode = "closed"- // SkipVerify is InsecureSkipVerify. It is first because it is the single- // most common fail-open in real code: it turns off the chain, the hostname- // and the validity window in one assignment, and it is what people reach- // for when a certificate error blocks a deploy.+ // SkipVerify is InsecureSkipVerify: no chain, no hostname, no validity.SkipVerify Mode = "skip-verify"- // SkipHostname verifies the chain and skips only the name. It is a real and- // subtler shape than SkipVerify: the connection is to a provably valid- // certificate for somebody else.+ // SkipHostname checks the chain and skips only the name.SkipHostname Mode = "skip-hostname"- // TrustPresentedCA builds its trust anchors out of whatever the server- // sent, which accepts any self-consistent chain. This is the shape a- // developer writes when "add the CA to the pool" is the error they are- // trying to silence.+ // TrustPresentedCA anchors on whatever chain the server sent.TrustPresentedCA Mode = "trust-presented-ca"- // NoRevocationCheck is Go's own default behaviour, stated as a mode. It- // verifies the chain properly and never asks whether the certificate was- // revoked, which is correct Go and an incorrect client.+ // NoRevocationCheck is Go's own default: correct Go, incorrect client.NoRevocationCheck Mode = "no-revocation-check"- // SoftFailOCSP asks and then proceeds whenever it does not get a usable- // answer: a transport failure, a TryLater, an Unknown. Research 04 calls- // soft-fail the reason revocation is near-useless in practice.+ // SoftFailOCSP asks, then proceeds on anything short of a usable answer.SoftFailOCSP Mode = "soft-fail-ocsp"- // StaleAccepted checks the status and never the freshness window, so a- // replayed or cached Good is trusted forever.+ // StaleAccepted checks the status and never the freshness window.StaleAccepted Mode = "stale-accepted"- // LooseOCSPParse calls ParseResponse instead of ParseResponseForCert. That- // one word stops the response being bound to the certificate, so a Good- // minted for a different serial is accepted. It is the cheapest total- // bypass of revocation checking in the whole taxonomy.+ // LooseOCSPParse uses ParseResponse, which binds nothing to the leaf.LooseOCSPParse Mode = "loose-ocsp-parse"- // NoCRLFreshness performs the whole CRL check except step five. It fetches,- // verifies the signature and scans the serials, and never looks at- // NextUpdate, so a three-week-old list is authoritative.+ // NoCRLFreshness does the whole CRL check except NextUpdate.NoCRLFreshness Mode = "no-crl-freshness"- // TrustStaple reads the stapled response and believes it without checking- // that it is a response at all. Go never parses a staple, so whatever the- // server attached arrives verbatim.+ // TrustStaple believes the staple without checking it is a response.TrustStaple Mode = "trust-staple"// NoKeyFloor, NoLifetimePolicy and NoKeyUsagePolicy drop the three policy- // checks x509 does not have. They exist so that each trap Go accepts has- // both a mode that catches it and a mode that does not, which is the only- // way those experiments can distinguish a target with a policy of its own- // from one with none.- //- // NoKeyUsagePolicy is the subtlest of the three. Verify enforces EXTENDED- // key usage, nested down the chain, and never looks at the basic KeyUsage- // bits on a leaf. A leaf whose KeyUsage omits digitalSignature is unusable- // for TLS under RFC 5280 section 4.2.1.3 and Go will not say a word about- // it, so a correct client has to check it here or not at all.+ // checks x509 lacks; Verify never reads a leaf's basic KeyUsage bits.NoKeyFloor Mode = "no-key-floor"NoLifetimePolicy Mode = "no-lifetime-policy"NoKeyUsagePolicy Mode = "no-key-usage-policy"- // DialOnly completes the handshake and never reads a byte.- //- // Research 04 section 7.2 calls this the most operationally dangerous- // finding in the whole TLS surface, and it is measured: under TLS 1.3 every- // row of the ClientAuth matrix returned a SUCCESSFUL tls.Dial, including- // the rows where the server rejected the client certificate and served- // nothing. The error arrives on the first read. Under TLS 1.2 the same case- // fails at Dial, so this defect is invisible on the older protocol and- // total on the newer one.- //- // A client in this mode reports a healthy dependency it was refused by.+ // DialOnly never reads a byte. Under TLS 1.3 a server's rejection of the+ // client certificate does not surface at Dial, only on the first read.DialOnly Mode = "dial-only"- // PolicyInPeerCallback puts its revocation policy in- // VerifyPeerCertificate and reuses TLS sessions.- //- // crypto/tls is explicit that VerifyPeerCertificate does NOT run on a- // resumed handshake and that VerifyConnection should be used instead- // (common.go:645-677). So an application whose pinning, staple validation- // or key floor lives in that hook has a policy that is checked on the first- // handshake and silently skipped for every resumption afterwards.- //- // Go's client does re-verify the cached chain for expiry and chain validity- // before offering a ticket, so an EXPIRED identity cannot survive- // resumption. Revocation can: nothing anywhere checks it, and the ticket- // lifetime ceiling is seven days (common.go:983-985). That is the hole this- // mode exists to demonstrate.+ // PolicyInPeerCallback puts its policy in VerifyPeerCertificate and reuses+ // sessions, and crypto/tls skips that callback on a resumed handshake.PolicyInPeerCallback Mode = "policy-in-peer-callback")@@ -125,10 +66,8 @@ const (modeSep = ", ")-// ErrUnknownMode is a name this package has no client for.var ErrUnknownMode = errors.New("no such reference client mode")-// Modes is every mode, Correct first. Tests census against this.func Modes() []string {return []string{string(Correct),@@ -149,9 +88,7 @@ func Modes() []string {}}-// ParseMode resolves a mode name, refusing anything it does not implement-// rather than silently falling back to Correct. A range fixture that quietly-// became correct would report every experiment as fail-closed.+// ParseMode refuses an unimplemented name rather than falling back to Correct.func ParseMode(name string) (Mode, error) {if !slices.Contains(Modes(), name) {return "", fmt.Errorf(@@ -165,19 +102,14 @@ func ParseMode(name string) (Mode, error) {return Mode(name), nil}-// checksChain reports whether the mode lets crypto/x509 build and check the-// path at all.func (m Mode) checksChain() bool {return m != SkipVerify}-// checksHostname reports whether the mode matches the name it asked for.func (m Mode) checksHostname() bool {return m != SkipVerify && m != SkipHostname}-// checksRevocation reports whether the mode asks about revocation in any way.-// Go's default is false, which is the whole reason this family exists.func (m Mode) checksRevocation() bool {switch m {case SkipVerify, NoRevocationCheck:@@ -187,20 +119,11 @@ func (m Mode) checksRevocation() bool {}}-// hardFails reports whether a revocation answer the mode could not obtain is-// treated as a refusal. A soft-failing client proceeds, which is Langley's-// seat belt that unbuckles in a crash.func (m Mode) hardFails() bool {return m != SoftFailOCSP}-// checksCRLFreshness and checksOCSPFreshness are SEPARATE, because the modes-// break them separately. Nothing in the standard library checks either one.-//-// A single predicate covering both was wrong and the matrix caught it:-// NoCRLFreshness is named for the CRL and was silently disabling the OCSP-// freshness check as well, so a stale OCSP response was accepted by a client-// whose only declared defect was about certificate revocation lists.+// Separate predicates, because the modes break CRL and OCSP freshness apart.func (m Mode) checksCRLFreshness() bool {return m != StaleAccepted && m != NoCRLFreshness}@@ -209,14 +132,10 @@ func (m Mode) checksOCSPFreshness() bool {return m != StaleAccepted}-// bindsResponse reports whether the mode checks that an OCSP response is about-// the certificate in hand.func (m Mode) bindsResponse() bool {return m != LooseOCSPParse}-// checksKeyFloor and checksLifetime are the two policies x509 does not have, so-// a mode without them is not breaking any rule Go enforces.func (m Mode) checksKeyFloor() bool {return m != SkipVerify && m != NoKeyFloor}@@ -225,30 +144,18 @@ func (m Mode) checksLifetime() bool {return m != SkipVerify && m != NoLifetimePolicy}-// checksKeyUsage reports whether the mode enforces the basic KeyUsage bits,-// which crypto/x509 never does on a leaf.func (m Mode) checksKeyUsage() bool {return m != SkipVerify && m != NoKeyUsagePolicy}-// reads reports whether the mode waits for a byte from the server. Only-// DialOnly does not, and under TLS 1.3 that is the difference between finding-// out you were refused and reporting success.func (m Mode) reads() bool {return m != DialOnly}-// resumes reports whether the mode reuses TLS sessions, which is the-// precondition for the resumption hole: there is nothing to skip a check on-// unless a session is actually resumed.func (m Mode) resumes() bool {return m == PolicyInPeerCallback}-// rechecksPerConnection reports whether the mode's policy runs on EVERY-// connection rather than only on a full handshake. A mode whose policy lives in-// VerifyPeerCertificate does not, because crypto/tls skips that callback on a-// resumed handshake.func (m Mode) rechecksPerConnection() bool {return m != PolicyInPeerCallback}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.goindex 8cc0fe4b..5cb70c54 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.go@@ -17,17 +17,8 @@ import (const maxRevocationBody = 1 << 20-// revocation is the layer crypto/x509 does not have.-//-// The order matters and is not arbitrary. A STAPLED response is preferred-// because it costs no round trip and is what a real client sees first; then-// OCSP, because it answers about one certificate rather than about every-// certificate the CA ever revoked; then the CRL as a fallback, because that is-// what remains once a CA ends OCSP, which Let's Encrypt did in 2025.-//-// A mode that checks nothing returns accepted here without asking anything, and-// the Asked fields record that, because "accepted without looking" and-// "accepted after looking" are different findings about a target.+// revocation is the layer crypto/x509 does not have, in order: the staple+// costs no round trip, then OCSP, then the CRL once a CA ends OCSP.func (c *Client) revocation(ctx context.Context,leaf, issuer *x509.Certificate,@@ -37,18 +28,10 @@ func (c *Client) revocation(return Decision{Accepted: true}}- // THE RESUMPTION HOLE, stated exactly as crypto/tls documents it.- //- // VerifyPeerCertificate does NOT run on a resumed handshake, and the doc- // comment says to use VerifyConnection or disable tickets instead- // (common.go:645-677). So an application whose pinning, staple validation- // or revocation check lives in that hook has a policy that is enforced on- // the first handshake and skipped on every resumption for the ticket's- // lifetime, which Go caps at seven days (common.go:983-985).- //- // Expiry cannot survive this: Go's client re-verifies the cached chain for- // NotAfter and chain validity before offering a ticket, and drops the entry- // if it fails. REVOCATION survives, because nothing anywhere checks it.+ // THE RESUMPTION HOLE: crypto/tls does not run VerifyPeerCertificate on a+ // resumed handshake, so a policy in that hook is skipped for the ticket's+ // lifetime. An expired identity still cannot slip through, because Go+ // re-verifies the cached chain before offering a ticket; a revoked one can.if state.DidResume && !c.mode.rechecksPerConnection() {return Decision{Accepted: true, Resumed: true}}@@ -78,29 +61,20 @@ func (c *Client) revocation(return decision}-// fromStaple reads the response the handshake carried. Go never parses a-// staple, so whatever the server attached arrives verbatim and only this code-// decides anything about it.+// Go never parses a staple, so whatever the server attached arrives verbatim.func (c *Client) fromStaple(state tls.ConnectionState,leaf, issuer *x509.Certificate,decision *Decision,) (string, bool) {if len(state.OCSPResponse) == 0 {- // No staple at all. A soft-failing client reads this as "fine", which- // is the StapleAbsent fault, and a correct one falls through to asking- // the responder directly rather than refusing outright.return reasonAccepted, true}if c.mode == TrustStaple {- // Believed without being parsed. Garbage bytes are accepted here, which- // is the whole of the StapleGarbage fault.- //- // The question is marked ANSWERED and the function returns here. A client- // that trusts the staple must not also query the responder: it would then- // refuse on the real answer, and three traps would look caught by a mode- // that by construction cannot catch them.+ // Marking it asked suppresses the live query below, or a mode that+ // trusts the staple would refuse on the real answer it exists to+ // ignore.decision.AskedOCSP = truereturn reasonAccepted, true@@ -120,9 +94,7 @@ func (c *Client) fromStaple(return c.judgeOCSP(response)}-// fromOCSP asks the responder named in the certificate. A certificate naming no-// responder is not an error: it is what Let's Encrypt now issues, and the-// honest answer is to fall through to the CRL.+// No responder named is not an error: fall through to the CRL.func (c *Client) fromOCSP(ctx context.Context,leaf, issuer *x509.Certificate,@@ -133,7 +105,6 @@ func (c *Client) fromOCSP(}if decision.AskedOCSP {- // Already answered by the staple.return reasonAccepted, true}@@ -144,8 +115,6 @@ func (c *Client) fromOCSP(body, err := c.post(ctx, leaf.OCSPServer[0], request)if err != nil {- // Could not reach the responder, or it answered TryLater. A- // soft-failing client proceeds here, which is the trap.return c.cannotTell()}@@ -159,10 +128,8 @@ func (c *Client) fromOCSP(return c.judgeOCSP(response)}-// parseOCSP is the one-word difference that is a total bypass. ParseResponse-// does NOT bind the response to the certificate, so a Good minted for another-// serial is accepted; ParseResponseForCert refuses it. Both verify the-// signature.+// The one-word difference that is a total bypass: ParseResponse does NOT bind+// the response to the certificate, so a Good for another serial is accepted.func (c *Client) parseOCSP(der []byte,leaf, issuer *x509.Certificate,@@ -174,9 +141,7 @@ func (c *Client) parseOCSP(return ocsp.ParseResponse(der, issuer)}-// judgeOCSP decides on a response that already verified. Good is the only-// acceptable status: Unknown from the authoritative responder is not good, and-// collapsing the two is its own fail-open.+// Good is the only acceptable status; Unknown is not Good.func (c *Client) judgeOCSP(response *ocsp.Response) (string, bool) {if response.Status == ocsp.Revoked {return reasonRevoked, false@@ -192,18 +157,13 @@ func (c *Client) judgeOCSP(response *ocsp.Response) (string, bool) {if c.mode.checksOCSPFreshness() && !response.NextUpdate.IsZero() &&response.NextUpdate.Before(c.clock()) {- // x/crypto/ocsp does not check this, measured: a response with- // NextUpdate a day in the past parses with a nil error. A client that- // skips it trusts a replayed Good forever.+ // x/crypto/ocsp does not: a stale NextUpdate parses with a nil error.return reasonStaleOCSP, false}return reasonAccepted, true}-// fromCRL is the six-step check from research 04 section 4.3, in full, because-// steps five and six are the ones people skip and skipping either is a-// fail-open on its own.func (c *Client) fromCRL(ctx context.Context,leaf, issuer *x509.Certificate,@@ -213,13 +173,12 @@ func (c *Client) fromCRL(return reasonAccepted, true}- // Step 2: fetch. Go parses the distribution point and never follows it.+ // Go parses the distribution point and never follows it.der, err := c.fetch(ctx, leaf.CRLDistributionPoints[0])if err != nil {return c.cannotTell()}- // Step 3: parse.list, err := x509.ParseRevocationList(der)if err != nil {return c.cannotTell()@@ -227,19 +186,17 @@ func (c *Client) fromCRL(decision.AskedCRL = true- // Step 4: the signature, or anyone can hand you a list.+ // The signature, or anyone at all can hand you a list.if err := list.CheckSignatureFrom(issuer); err != nil {return reasonBadCRLSig, false}- // Step 5: freshness. Nothing in the standard library does this, and a- // three-week-old list is otherwise authoritative.+ // Freshness, which nothing in the standard library checks.if c.mode.checksCRLFreshness() && !list.NextUpdate.IsZero() &&list.NextUpdate.Before(c.clock()) {return reasonStaleCRL, false}- // Step 6: the linear scan.for _, entry := range list.RevokedCertificateEntries {if entry.SerialNumber.Cmp(leaf.SerialNumber) == 0 {return reasonRevoked, false@@ -249,9 +206,7 @@ func (c *Client) fromCRL(return reasonAccepted, true}-// cannotTell is the soft-fail decision point, and the single most consequential-// branch in this file. A client that proceeds because it could not get an-// answer has a seat belt that unbuckles in a crash.+// The soft-fail point: a seat belt that unbuckles in a crash.func (c *Client) cannotTell() (string, bool) {if c.mode.hardFails() {return reasonNoAnswer, false@@ -317,8 +272,7 @@ func (e *httpStatusError) Error() string {return "revocation endpoint answered " + e.status}-// modulusBits is the leaf's RSA size, and false for any other key type. An-// ECDSA key has no modulus and the floor does not apply to it.+// False for any other key type: an ECDSA key has no modulus to floor.func modulusBits(leaf *x509.Certificate) (int, bool) {key, ok := leaf.PublicKey.(*rsa.PublicKey)if !ok {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.goindex 9129439c..47a62ca0 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go@@ -1,17 +1,8 @@// ©AngelaMos | 2026// verifier.go-// Package verifier is the RANGE's reference token verifier: the thing under-// test, not part of khaos's own machinery. It lives under internal/ rather than-// inside cmd/khaos-range so that khaos's test suite can import it and pin every-// forgery trap against it, which is the only way to know a trap is detectable at-// all before pointing it at somebody's real service.-//-// Mode Correct is a genuinely correct verifier and it has to stay that way. A-// teaching repo's "correct" side is what readers copy, and the range has already-// shipped a reference gateway with two defects of its own. Every other mode is-// exactly one line different from Correct, and each of those lines is a named,-// CVE-anchored bug from research 07 section 1.5.+// Package verifier is the range's reference token verifier: the thing under+// test. Mode Correct is the control; every other mode is one line from it.package verifierimport (@@ -35,105 +26,64 @@ import ("github.com/CarterPerez-dev/khaos/internal/idp")-// Mode is which bug the range's verifier is carrying. Each one is a single-// structural defect, and several traps are caught by one mode because they share-// a root cause: that sharing is the research's own framing, not a shortcut.+// Mode is which defect the verifier carries. Traps can share a mode.type Mode stringconst (- // Correct follows RFC 8725. It is the control for every other mode.+ // Correct follows RFC 8725 and is the control for every other mode.Correct Mode = "closed"- // AlgAny resolves the key and THEN dispatches on the header's algorithm,- // with no server-side allowlist and no key-to-algorithm cross-check. That- // one inversion is the root cause of both `alg: none` acceptance and- // HS256/RS256 confusion, which is why one mode catches both.+ // AlgAny trusts the header's alg: no allowlist, no key-to-alg check.AlgAny Mode = "alg-any"- // TrustEmbeddedKey resolves the signing key from the token's own `jwk`- // header. RFC 8725 rule 4 is the single sentence that forbids it.+ // TrustEmbeddedKey resolves the key from the token's own `jwk` header.TrustEmbeddedKey Mode = "trust-embedded-key"- // SkipClaims verifies the signature and then validates nothing: not `exp`,- // not `nbf`, not `aud`, not `iss`, not `typ`.+ // SkipClaims checks no claim at all: not `exp`, `nbf`, `aud`, `iss`, `typ`.SkipClaims Mode = "skip-claims"- // WeakSignature treats an absent, all-zero or short-of-the-algorithm- // signature as a pass rather than as a failure.+ // WeakSignature passes an absent, all-zero or too-short signature.WeakSignature Mode = "weak-sig"- // AnyKeySize drops the minimum modulus check and verifies with raw modular- // exponentiation, so Go's own 1024-bit floor never applies either.+ // AnyKeySize drops the modulus floor and verifies by raw exponentiation.AnyKeySize Mode = "any-key-size"- // JWKSFailOpen decodes the claims without verifying the signature when the- // JWK Set cannot be fetched. Research 07 calls this the highest-value trap- // in its archive: unit tests pass, integration tests pass, and the branch is- // reachable only while the provider is down.+ // JWKSFailOpen skips the signature check when the key set will not fetch.JWKSFailOpen Mode = "jwks-fail-open"- // JWKSCacheForever never expires the key set and never refetches. It is the- // mirror of JWKSFailOpen: not permissive, stale, which means a key the- // provider rotated out is still a valid signing key here.+ // JWKSCacheForever never expires the key set, so rotation revokes nothing.JWKSCacheForever Mode = "jwks-cache-forever"- // JWKSRefetchOnKidOnly refetches when it meets an unknown `kid` and never on- // a timer. It is the most realistic of the three key-cache modes and the one- // research 07 section 2.3 says carries "the whole finding": the eviction of a- // retired key is a SIDE EFFECT of the refetch a new-key token triggers, so a- // target with no new-key traffic keeps honouring the retired key for an- // unbounded time.- //- // It exists because without it nothing in the range demonstrates that case,- // and khaos's own `identity.kid_rollover` was silently supplying the new-key- // traffic that hides it.+ // JWKSRefetchOnKidOnly refetches on an unknown `kid`, never on a timer.JWKSRefetchOnKidOnly Mode = "jwks-kid-only"- // IntrospectFailOpen treats a non-200, an unparseable body or a timeout as- // `active: true`, which is a value RFC 7662 never provides.+ // IntrospectFailOpen reads a non-200, a bad body or a timeout as active.IntrospectFailOpen Mode = "introspect-fail-open"- // DecisionCacheForever caches an authorization decision with no expiry, so a- // credential revoked at a fully reachable provider is honoured forever.+ // DecisionCacheForever caches an authorization decision with no expiry.DecisionCacheForever Mode = "decision-cache-forever")const (- // The allowlist. It is a property of the verifier's configuration and the- // token never selects from it, which is RFC 8725 section 3.1.+ // RFC 8725 section 3.1: the token never selects from the allowlist.allowedRS = string(idp.RS256)allowedES = string(idp.ES256)- // Real verifiers tolerate a little clock skew and so does this one, because- // a reference implementation with zero tolerance is one readers will copy- // and then work around. The claim traps move their claim by far more than- // this.clockSkew = 60 * time.Second- // Short on purpose. A key set cached for longer than a khaos run would never- // be refetched during one, so the fetch-failure branch every JWKS trap- // exists to probe would be unreachable and the experiment would measure- // nothing.+ // Shorter than a run, so the fetch-failure branch is reachable in one.DefaultKeyTTL = time.Second- // DefaultDecisionTTL is the authorization-decision cache lifetime for opaque- // credentials.DefaultDecisionTTL = 2 * time.SecondupstreamTimeout = 500 * time.Millisecond- // 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.- // The cooldown is short on purpose: see the note in keySet.DefaultNegativeTTL = time.SecondDefaultForcedCooldown = 100 * time.Millisecond@@ -144,9 +94,7 @@ const (errNoKeys = "the key set could not be fetched")-// Decision is what the verifier concluded and why. The reason is for the-// fixture's own tests: an experiment must never depend on it, because khaos-// judges a target from the outside and a real target volunteers nothing.+// Decision is the verdict. Nothing outside this fixture may depend on Reason.type Decision struct {Allow boolReason string@@ -170,16 +118,10 @@ type Verifier struct {client *http.Clientnow func() time.Time- // negativeTTL is how long an unknown kid is refused without another fetch,- // and forcedCooldown caps the forced-fetch rate. Both bound the amplifier- // that an attacker-controlled `kid` otherwise is.negativeTTL time.DurationforcedCooldown time.Duration- // fetching serialises the upstream fetch itself, so concurrent requests- // carrying the same unknown kid cause one fetch rather than one each. It is- // a separate mutex from mu because mu guards the cache and must not be held- // across a network call.+ // Separate from mu, which must not be held across a network call.fetching sync.Mutexmu sync.Mutex@@ -202,7 +144,6 @@ type Config struct {Now func() time.TimeClient *http.Client- // NegativeTTL and ForcedCooldown bound the unknown-kid refetch.NegativeTTL time.DurationForcedCooldown time.Duration}@@ -271,21 +212,14 @@ func Known(mode string) bool {return slices.Contains(Modes(), mode)}-// Decide is the whole verifier. A credential that parses as a JWS is validated-// locally; anything else is introspected. Real gateways do exactly this, and the-// two strategies have genuinely different outage shapes, which is why the range-// has to demonstrate both.+// Decide validates a JWS-shaped credential locally and introspects the rest.func (v *Verifier) Decide(credential string) Decision {if credential == "" {return Decision{Reason: "no credential was presented"}}- // Dispatch on the credential's SHAPE, not on whether khaos's parser happens- // to accept it. Keying on a parse failure silently rerouted legal JWTs to- // introspection: a token with `"aud": ["a","b"]`, which RFC 7519 section- // 4.1.3 explicitly permits, failed to unmarshal and was introspected as if- // it were an opaque credential. Under a fail-open introspection mode with no- // endpoint configured, that token would have been allowed.+ // Dispatch on SHAPE, not on whether the parser accepts it: RFC 7519 permits+ // an array `aud`, and a legal JWT routed to introspection can be an accept.if !idp.LooksLikeJWS(credential) {return v.introspect(credential)}@@ -304,10 +238,6 @@ func (v *Verifier) validate(token idp.Token) Decision {keys, keysErr := v.keySet(token.Header.Kid)if keysErr != nil {- // The highest-value trap in the archive, and it is this one branch. The- // developer wanted availability; the reviewer read it as graceful- // degradation. It is an unauthenticated-request-accepted path gated on- // an outage.if v.mode == JWKSFailOpen {return Decision{Allow: true,@@ -327,9 +257,7 @@ func (v *Verifier) validate(token idp.Token) Decision {}}- // `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.+ // RFC 7515 registers `none` as "no signature or MAC performed".if alg == string(idp.None) {return v.claims(token,@@ -344,10 +272,7 @@ func (v *Verifier) validate(token idp.Token) Decision {}}- // RFC 8725 rule 2: "Each key MUST be used with exactly one algorithm, and- // this MUST be checked when the cryptographic operation is performed." This- // single line is what kills algorithm confusion, and AlgAny is what happens- // without it.+ // RFC 8725 rule 2: each key MUST be used with exactly one algorithm.if v.mode != AlgAny && key.Alg != "" && key.Alg != alg {return Decision{Reason: fmt.Sprintf(@@ -372,9 +297,6 @@ func (v *Verifier) validate(token idp.Token) Decision {return v.claims(token, "the signature verified")}-// algorithm is the allowlist, and under AlgAny it is the token's own choice.-// The whole difference between the two is whether the server or the attacker-// picks.func (v *Verifier) algorithm(declared string) (string, bool) {if v.mode == AlgAny {return declared, declared != ""@@ -387,9 +309,6 @@ func (v *Verifier) algorithm(declared string) (string, bool) {return "", false}-// resolve finds the key. Correct mode resolves ONLY from the fetched key set;-// TrustEmbeddedKey prefers the one the token brought with it, which is RFC 8725-// rule 4 violated and CVE-2018-0114 in the wild.func (v *Verifier) resolve(keys idp.JWKSet, token idp.Token) (idp.JWK, bool) {if v.mode == TrustEmbeddedKey && token.Header.JWK != nil {return *token.Header.JWK, true@@ -408,18 +327,8 @@ func (v *Verifier) signature(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- // rejects r = s = 0, so a Go verifier only falls for the second one by- // skipping the check, which is precisely what this does.- //- // The length is measured against the resolved key rather than against a- // constant, which is what the CVE actually describes: "a valid minimum- // length for a signature" is a property of the key, not of the algorithm- // name. A constant floor also made this mode accept the weak-key token,- // whose signature is legitimately short because its modulus is, and that- // overlap would have let one mode alibi another in the matrix below.+ // Compared against the RESOLVED KEY, not a constant: a minimum length is a+ // property of the key, and a constant floor also passes the weak-key token.if v.mode == WeakSignature && weakSignature(key, token.Signature, alg) {return "", true}@@ -446,10 +355,7 @@ func (v *Verifier) signature(return "", truecase string(idp.HS256):- // Reachable only under AlgAny. The verifier is configured with an RSA- // public key and has just been told to use it as an HMAC secret, which- // it can do, because the bytes are bytes. The attacker had those bytes- // all along: they are public.+ // An RSA public key used as an HMAC secret, and it is public.secret, err := publicBytes(key)if err != nil {return "the key cannot be used as a MAC secret", false@@ -469,9 +375,6 @@ func (v *Verifier) signature(}}-// 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,@@ -482,10 +385,7 @@ func (v *Verifier) verifyRSA(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.+ // Explicit, rather than trusting crypto/rsa's 1024-bit minimum to stay.if v.mode != AnyKeySize && pub.N.BitLen() < minimumModulusBits {return fmt.Sprintf("kid %q has a %d-bit modulus",@@ -532,10 +432,7 @@ func weakSignature(key idp.JWK, signature []byte, alg string) bool {}}-// claims is the four checks a stateless verifier has, and SkipClaims is all four-// missing at once. `exp` is the one that matters most: it is the ONLY revocation-// mechanism a locally validating verifier has, so a verifier that ignores it has-// no revocation at all.+// claims is every check a stateless verifier has; `exp` is its only revocation.func (v *Verifier) claims(token idp.Token, reason string) Decision {if v.mode == SkipClaims {return Decision{@@ -544,17 +441,7 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {}}- // RFC 8725 section 3.11, Use Explicit Typing, and RFC 9068 which requires- // `at+jwt` on an OAuth 2.0 access token. Section 3.12 is the reason it- // matters: without it this verifier cannot refuse an ID token presented- // where an access token belongs, and research 07 section 1.2 calls that- // substitution "cheap to build and catches real bugs".- //- // This check was MISSING, and `internal/idp/mint.go` cited it to justify a- // design decision — the comment claimed the three header traps had been- // refused by it. Nothing in the repository implemented it, so the comment- // described a refusal that never happened and the property it defends (every- // forged token carrying `at+jwt`) was inert against this fixture.+ // RFC 9068 requires `at+jwt`; without it an ID token passes here.if token.Header.Typ != typAccessToken {return Decision{Reason: fmt.Sprintf(@@ -590,12 +477,7 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {}}- // RFC 9700: "every resource server is obliged to verify, for every request,- // whether the access token sent with that request was meant to be used for- // that particular resource server."- // Membership, not equality. A token legitimately addressed to several- // 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".+ // RFC 9700: membership, not equality -- a token may address several.if !token.Claims.Audience.Contains(v.audience) {return Decision{Reason: fmt.Sprintf(@@ -609,11 +491,7 @@ func (v *Verifier) claims(token idp.Token, reason string) Decision {return Decision{Allow: true, Reason: reason}}-// keySet returns the trusted keys, refetching when the cache is cold, stale, or-// does not hold the kid the token names. The unknown-kid refetch is convention-// rather than specification: research 07 established that OIDC Discovery says-// nothing about rotation, nothing about `kid` and nothing about refetching, which-// is exactly why it is implemented inconsistently and worth a chaos fault.+// The unknown-kid refetch is convention, not specification: OIDC is silent.func (v *Verifier) keySet(kid string) (idp.JWKSet, error) {v.mu.Lock()cached := v.keys@@ -621,17 +499,10 @@ func (v *Verifier) keySet(kid string) (idp.JWKSet, error) {fresh := v.now().Sub(v.keysAt) < v.keyTTLv.mu.Unlock()- // Not permissive, stale. Key rotation is the control that bounds the damage- // of a leaked signing key, and a verifier that never expires its cache has- // turned rotation into something that is not a revocation mechanism.if v.mode == JWKSCacheForever && have {return cached, nil}- // Freshness is ignored while the kid is known, so the only thing that ever- // triggers a fetch is meeting a kid this verifier has not seen. That is one- // line different from correct and it is the difference between a bounded- // stale window and an unbounded one.if v.mode == JWKSRefetchOnKidOnly && have && cached.Has(kid) {return cached, nil}@@ -640,23 +511,11 @@ func (v *Verifier) keySet(kid string) (idp.JWKSet, error) {return cached, nil}- // A kid this verifier already looked for and did not find is refused without- // another fetch. Research 07 section 2.3's own recovery trace ends on exactly- // this line: "refetch already attempted, negative cached -> 401".if have && fresh && v.negativelyCached(kid) {return cached, nil}- // Single-flight. The fetch happens under its own mutex and the cache is- // re-checked after acquiring it, so N concurrent requests carrying the same- // unknown kid cause ONE upstream fetch rather than N. Measured before this- // existed: 200 requests carrying 200 attacker-chosen kids produced 200- // upstream fetches, a ratio of 1.00, which research 07 section 1.4 calls- // verbatim "a denial-of-service amplifier if unbounded".- //- // `kid` is an attacker-controlled header field. A reference implementation- // that readers copy cannot leave this unbounded, least of all in the one file- // whose job is to be the correct side of the comparison.+ // `kid` is attacker-controlled, so the fetch is single-flighted.v.fetching.Lock()defer v.fetching.Unlock()@@ -664,17 +523,7 @@ func (v *Verifier) keySet(kid string) (idp.JWKSet, error) {return set, nil}- // A rate cap on the FORCED path only. The periodic staleness refresh above is- // untouched, so a rotation is still picked up within one key lifetime even- // when a burst of unknown kids has the forced path on cooldown.- //- // The cap is deliberately short relative to a probe interval: a cooldown long- // enough to be a real brake also delays a legitimate rotation, and a verifier- // that refuses correctly signed new-key tokens for a second is the- // availability failure research 07 section 2.2 counts as `wrongly_rejected`.- // The residual amplification is inherent to the unknown-kid convention, which- // is why section 2.4 treats it as a fault worth measuring rather than a bug- // to be eliminated.+ // A rate cap on the FORCED path only; a longer one delays a real rotation.if have && fresh && !v.forcedFetchAllowed() {return cached, nil}@@ -700,9 +549,6 @@ func (v *Verifier) keySet(kid string) (idp.JWKSet, error) {return fetched, nil}-// freshWith is the post-lock re-check that makes the fetch single-flight: a-// waiter that blocked while another goroutine fetched finds the answer already-// in the cache and does not fetch again.func (v *Verifier) freshWith(kid string) (idp.JWKSet, bool) {v.mu.Lock()defer v.mu.Unlock()@@ -764,10 +610,7 @@ func (v *Verifier) fetchKeys() (idp.JWKSet, error) {return idp.ParseJWKSet(body)}-// introspect is the opaque-credential path. RFC 7662 is explicit that the-// ABSENCE of a response is not `active: false`, and a caller that invents one-// from a timeout, a 503 or an unparseable body has made up a value the provider-// never gave it.+// RFC 7662 is explicit that the ABSENCE of a response is not `active: false`.func (v *Verifier) introspect(credential string) Decision {if decision, ok := v.cachedDecision(credential); ok {return Decision{Allow: decision, Reason: "a cached decision answered"}@@ -795,11 +638,6 @@ func (v *Verifier) ask(credential string) (bool, bool) {return false, false}- // RFC 7662 section 2.1: a POST with an `application/x-www-form-urlencoded`- // body. This used to send the token as a query parameter, which is khaos's- // 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}},@@ -809,17 +647,8 @@ func (v *Verifier) ask(credential string) (bool, bool) {}defer func() { _ = response.Body.Close() }()- // A 401 from an introspection endpoint is a verdict on the CALLER, not on- // the token. RFC 7662 section 2.3 defines it as the response when the- // protected resource's own credentials to the authorization server are- // invalid, and the RFC defines no 403 at all.- //- // This used to be folded into "the provider answered, the token is inactive",- // which is a conflation and the opposite of what the cited RFC says: it turns- // "my credentials to the authority are wrong" into a flood of token denials- // with no distinguishable signal. Both paths deny under this mode, so nothing- // about the range's behaviour changes; what changes is that the file readers- // copy no longer teaches the conflation.+ // A 401 here is a verdict on the CALLER, not on the token: RFC 7662 section+ // 2.3 defines it for invalid client credentials, and defines no 403 at all.if response.StatusCode != http.StatusOK {return false, false}@@ -885,10 +714,8 @@ func allZero(raw []byte) bool {return true}-// Resolve maps an operator's string onto a mode, and falls back to Correct for-// anything it does not recognise. That fallback is deliberate: one `--fail-mode`-// drives the whole range, and a mode meant for a different gateway must leave-// this one behaving correctly rather than refusing to start.+// Resolve falls back to Correct on purpose: one `--fail-mode` drives the whole+// range, so a mode meant for another gateway must leave this one correct.func Resolve(mode string) Mode {trimmed := strings.TrimSpace(mode)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.goindex b97f069c..5693f71f 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/workspace/workspace.go@@ -19,9 +19,7 @@ import (const errDockerHint = "%w (run `khaos doctor` for the fix)"type Workspace struct {- // Reconciled is what the startup sweep of EXPIRED orphans did, so a command- // can tell the operator that khaos cleaned up before it started rather than- // leaving it to be discovered later.+ // Reconciled is what the startup sweep of EXPIRED orphans did.Reconciled run.SweepDocker *dockerx.Client@@ -67,16 +65,9 @@ func open(ctx context.Context, exclusive bool) (*Workspace, error) {work := &Workspace{Docker: client, Journal: log, Paths: paths, held: held}- // The promise `khaos inject --ttl` makes is "before `khaos reap` or the next- // khaos invocation reclaims it". Nothing implemented the second half: only- // the explicit reclaim command and the reap loop ever called run.Reclaim, so- // a fault whose controller was killed outlived its TTL indefinitely unless- // the operator happened to run one of those two commands.- //- // EXPIRED leases only, and only on an exclusive open. A live lease belongs to- // a session that is still running and reverting it would steal another run's- // 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.+ // The half of the `--ttl` promise that says "or the next khaos invocation+ // reclaims it". Expired leases only, and only on an exclusive open: a live+ // lease belongs to a session that is still running.if exclusive {work.Reconciled = run.Reclaim(ctx,