---
phase: 08-external-http
plan: 02
type: tdd
wave: 2
depends_on:
  - 08-01
files_modified:
  - internal/validation/executor.go
  - internal/validation/executor_test.go
autonomous: true
requirements:
  - EXT-01
  - EXT-02
  - EXT-03
  - EXT-04

must_haves:
  truths:
    - "A connectivity validation with `mode: external` sends an HTTP request from the CLI host via net/http — no pod exec"
    - "External check with `hostHeader` sets `req.Host` on the outgoing request (not req.Header)"
    - "External check returns passed=true when server responds with the expected status code"
    - "External check returns passed=false with a message when server responds with wrong status code"
    - "External check with `expectedStatusCode: 0` returns passed=true when the connection is refused or times out"
    - "External check returns passed=false when connection refused and expectedStatusCode != 0"
    - "All existing internal connectivity tests continue to pass unchanged"
  artifacts:
    - path: "internal/validation/executor.go"
      provides: "checkExternalConnectivity method; checkExternalConnectivityAll helper; executeConnectivity mode branch"
      contains: "checkExternalConnectivity"
    - path: "internal/validation/executor_test.go"
      provides: "Unit tests for external mode using httptest.NewServer"
      contains: "TestCheckExternalConnectivity_Success"
  key_links:
    - from: "internal/validation/executor.go executeConnectivity"
      to: "internal/validation/executor.go checkExternalConnectivityAll"
      via: "spec.Mode == \"external\" branch before SourcePod switch"
      pattern: "spec\\.Mode.*external"
    - from: "internal/validation/executor.go checkExternalConnectivity"
      to: "net/http"
      via: "http.NewRequestWithContext + req.Host override + client.Do"
      pattern: "req\\.Host"
---

<objective>
Implement `checkExternalConnectivity` in `executor.go` — the net/http-based path that handles `mode: external` connectivity specs. Branch in `executeConnectivity` before the sourcePod switch. Tests use `httptest.NewServer` for deterministic, DNS-free unit tests.

Purpose: Deliver the runtime behavior for EXT-01 through EXT-04. No new dependencies — stdlib only.
Output: Updated `executor.go` with external mode support, new executor tests (RED→GREEN).
</objective>

<execution_context>
@/Users/paul/.claude/get-shit-done/workflows/execute-plan.md
@/Users/paul/.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/phases/08-external-http/08-CONTEXT.md
@.planning/phases/08-external-http/08-RESEARCH.md
@.planning/phases/08-external-http/08-01-SUMMARY.md

<interfaces>
<!-- Key contracts from Plan 01 output and existing executor patterns. -->

From internal/validation/types.go (after Plan 01):
```go
type ConnectivitySpec struct {
    Mode      string             `yaml:"mode,omitempty" json:"mode,omitempty"`
    SourcePod SourcePod          `yaml:"sourcePod" json:"sourcePod"`
    Targets   []ConnectivityCheck `yaml:"targets" json:"targets"`
}

type ConnectivityCheck struct {
    URL                string `yaml:"url" json:"url"`
    ExpectedStatusCode int    `yaml:"expectedStatusCode" json:"expectedStatusCode"`
    TimeoutSeconds     int    `yaml:"timeoutSeconds,omitempty" json:"timeoutSeconds,omitempty"`
    HostHeader         string `yaml:"hostHeader,omitempty" json:"hostHeader,omitempty"`
}
```

From internal/validation/executor.go (current executeConnectivity signature):
```go
func (e *Executor) executeConnectivity(ctx context.Context, spec ConnectivitySpec) (bool, string, error)
```

From internal/validation/loader.go (constant already defined):
```go
const DefaultConnectivityTimeoutSeconds = 5
```

From executor.go (success message constant already defined):
```go
msgAllConnectivityPassed = "All connectivity checks passed"
```

From executor.go (test-environment guard pattern used in checkConnectivity):
```go
// External mode uses net/http — no K8s client involved.
// Unit tests use httptest.NewServer — no guard needed.
```

Critical Go net/http patterns (from research — HIGH confidence):
- Use `req.Host = target.HostHeader` NOT `req.Header.Set("Host", h)` — only req.Host overrides the wire Host header
- Use `http.ErrUseLastResponse` in CheckRedirect to prevent automatic redirect following
- Always `defer func() { _ = resp.Body.Close() }()` after client.Do
- Per-request http.Client (no shared state)
- `context.WithTimeout` wraps incoming ctx; set both context deadline AND client.Timeout to timeout seconds
</interfaces>
</context>

<tasks>

<task type="auto" tdd="true">
  <name>Task 1: Write failing executor tests (RED)</name>
  <files>internal/validation/executor_test.go</files>
  <behavior>
    - TestCheckExternalConnectivity_Success: httptest server returns 200, check expects 200 → passed=true
    - TestCheckExternalConnectivity_WrongStatus: httptest server returns 404, check expects 200 → passed=false, message contains "got status 404"
    - TestCheckExternalConnectivity_BlockedConnection: connection refused URL, expectedStatusCode=0 → passed=true, message contains "blocked"
    - TestCheckExternalConnectivity_ConnectionRefused: connection refused URL, expectedStatusCode=200 → passed=false, message contains "failed"
    - TestCheckExternalConnectivity_HostHeader: httptest server records r.Host, check has hostHeader set → server receives the hostHeader value as Host
    - TestCheckExternalConnectivity_StatusCodes: parametrized check for 200, 201, 301, 404 — each expected code matches server response
    - TestExecuteConnectivity_ExternalMode: full executeConnectivity call with mode:external → routes to net/http path (no pod exec attempted)
  </behavior>
  <action>
Add the following test functions to `internal/validation/executor_test.go`. Import `"net/http/httptest"` and `"net/http"` if not already present.

All tests use `httptest.NewServer` — no DNS, no sslip.io, no real cluster needed.

```go
func TestCheckExternalConnectivity_Success(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    }))
    defer srv.Close()

    e := &Executor{} // net/http path — no K8s client needed
    target := ConnectivityCheck{
        URL:                srv.URL + "/",
        ExpectedStatusCode: 200,
        TimeoutSeconds:     5,
    }
    passed, msg := e.checkExternalConnectivity(context.Background(), target)
    assert.True(t, passed)
    assert.Empty(t, msg)
}

func TestCheckExternalConnectivity_WrongStatus(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusNotFound)
    }))
    defer srv.Close()

    e := &Executor{}
    target := ConnectivityCheck{
        URL:                srv.URL + "/",
        ExpectedStatusCode: 200,
        TimeoutSeconds:     5,
    }
    passed, msg := e.checkExternalConnectivity(context.Background(), target)
    assert.False(t, passed)
    assert.Contains(t, msg, "got status 404")
}

func TestCheckExternalConnectivity_BlockedConnection(t *testing.T) {
    e := &Executor{}
    target := ConnectivityCheck{
        URL:                "http://127.0.0.1:1", // port 1 — always refused
        ExpectedStatusCode: 0,
        TimeoutSeconds:     2,
    }
    passed, msg := e.checkExternalConnectivity(context.Background(), target)
    assert.True(t, passed)
    assert.Contains(t, msg, "blocked")
}

func TestCheckExternalConnectivity_ConnectionRefused(t *testing.T) {
    e := &Executor{}
    target := ConnectivityCheck{
        URL:                "http://127.0.0.1:1", // port 1 — always refused
        ExpectedStatusCode: 200,
        TimeoutSeconds:     2,
    }
    passed, msg := e.checkExternalConnectivity(context.Background(), target)
    assert.False(t, passed)
    assert.Contains(t, msg, "failed")
}

func TestCheckExternalConnectivity_HostHeader(t *testing.T) {
    var receivedHost string
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        receivedHost = r.Host
        w.WriteHeader(http.StatusOK)
    }))
    defer srv.Close()

    e := &Executor{}
    target := ConnectivityCheck{
        URL:                srv.URL + "/",
        ExpectedStatusCode: 200,
        TimeoutSeconds:     5,
        HostHeader:         "myapp.example.com",
    }
    passed, _ := e.checkExternalConnectivity(context.Background(), target)
    assert.True(t, passed)
    assert.Equal(t, "myapp.example.com", receivedHost)
}

func TestCheckExternalConnectivity_StatusCodes(t *testing.T) {
    tests := []struct {
        serverCode   int
        expectedCode int
        wantPassed   bool
    }{
        {200, 200, true},
        {201, 201, true},
        {301, 301, true},
        {404, 404, true},
        {200, 404, false},
        {301, 200, false},
    }
    for _, tc := range tests {
        tc := tc
        t.Run(fmt.Sprintf("server=%d_expected=%d", tc.serverCode, tc.expectedCode), func(t *testing.T) {
            srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                w.WriteHeader(tc.serverCode)
            }))
            defer srv.Close()
            e := &Executor{}
            target := ConnectivityCheck{
                URL:                srv.URL + "/",
                ExpectedStatusCode: tc.expectedCode,
                TimeoutSeconds:     5,
            }
            passed, _ := e.checkExternalConnectivity(context.Background(), target)
            assert.Equal(t, tc.wantPassed, passed)
        })
    }
}

func TestExecuteConnectivity_ExternalMode(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    }))
    defer srv.Close()

    // External mode — no K8s client interaction expected
    e := NewExecutor(nil, nil, nil, "test-ns")
    spec := ConnectivitySpec{
        Mode: "external",
        Targets: []ConnectivityCheck{
            {URL: srv.URL + "/", ExpectedStatusCode: 200, TimeoutSeconds: 5},
        },
    }
    passed, msg, err := e.executeConnectivity(context.Background(), spec)
    require.NoError(t, err)
    assert.True(t, passed)
    assert.Equal(t, msgAllConnectivityPassed, msg)
}
```

Run: `go test ./internal/validation/... -run "TestCheckExternalConnectivity|TestExecuteConnectivity_ExternalMode" -v -count=1`

These tests will FAIL because `checkExternalConnectivity` does not exist yet. Confirm RED before moving to implementation.
  </action>
  <verify>
    <automated>go build ./internal/validation/... 2>&1 | grep -v "^$" || true</automated>
  </verify>
  <done>Test functions added to executor_test.go; file compiles (even if tests fail at runtime). RED confirmed: `go test ./internal/validation/... -run TestCheckExternalConnectivity -count=1` fails with "undefined: checkExternalConnectivity" or test failures.</done>
</task>

<task type="auto" tdd="true">
  <name>Task 2: Implement checkExternalConnectivity in executor.go (GREEN)</name>
  <files>internal/validation/executor.go</files>
  <behavior>
    - executeConnectivity branches on spec.Mode == "external" before any SourcePod resolution
    - checkExternalConnectivityAll iterates targets, collects failures, returns msgAllConnectivityPassed on full pass
    - checkExternalConnectivity creates a per-request http.Client with CheckRedirect returning http.ErrUseLastResponse
    - checkExternalConnectivity uses context.WithTimeout(ctx, timeout) — timeout from target.TimeoutSeconds or DefaultConnectivityTimeoutSeconds
    - checkExternalConnectivity sets req.Host = target.HostHeader when HostHeader is non-empty (NOT req.Header.Set)
    - checkExternalConnectivity drains/closes resp.Body on every response path
    - When err != nil (connection refused/timeout): returns passed=true if ExpectedStatusCode==0, else passed=false
    - When response received: returns passed=(resp.StatusCode == target.ExpectedStatusCode)
  </behavior>
  <action>
**Step 1 — Add `"net/http"` to the import block in `executor.go`** (it is not currently imported; `"time"` is already present).

**Step 2 — Add the mode branch at the TOP of `executeConnectivity`, before any SourcePod resolution:**

```go
func (e *Executor) executeConnectivity(ctx context.Context, spec ConnectivitySpec) (bool, string, error) {
    logger.Debug("Executing connectivity validation")

    // EXT-01: external mode — CLI host sends HTTP request via net/http, no pod exec
    if spec.Mode == "external" {
        return e.checkExternalConnectivityAll(ctx, spec)
    }

    // existing internal/probe path unchanged below...
    // Resolve source namespace: SourcePod.Namespace wins over executor default (CONN-02, PROBE-02)
    sourceNamespace := e.namespace
    // ... rest of existing function unchanged
```

**Step 3 — Add `checkExternalConnectivityAll` and `checkExternalConnectivity` methods after `executeConnectivity`:**

```go
// checkExternalConnectivityAll iterates all targets for an external connectivity spec.
// Mirrors the internal target loop in executeConnectivity.
func (e *Executor) checkExternalConnectivityAll(ctx context.Context, spec ConnectivitySpec) (bool, string, error) {
    allPassed := true
    var messages []string
    for _, target := range spec.Targets {
        passed, msg := e.checkExternalConnectivity(ctx, target)
        if !passed {
            allPassed = false
            messages = append(messages, msg)
        }
    }
    if allPassed {
        return true, msgAllConnectivityPassed, nil
    }
    return false, strings.Join(messages, "; "), nil
}

// checkExternalConnectivity sends a single HTTP request from the CLI host via net/http.
// No pod exec — used for mode: external (EXT-01).
func (e *Executor) checkExternalConnectivity(ctx context.Context, target ConnectivityCheck) (bool, string) {
    timeout := target.TimeoutSeconds
    if timeout == 0 {
        timeout = DefaultConnectivityTimeoutSeconds
    }

    reqCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
    defer cancel()

    req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, target.URL, nil)
    if err != nil {
        return false, fmt.Sprintf("Invalid URL %s: %v", target.URL, err)
    }

    // EXT-02: override wire Host header for virtual-host routing
    // IMPORTANT: req.Host overrides the Host header on the wire.
    // req.Header.Set("Host", h) does NOT work for the Host header in Go.
    if target.HostHeader != "" {
        req.Host = target.HostHeader
    }

    client := &http.Client{
        Timeout: time.Duration(timeout) * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            // Return redirects as-is — do not follow automatically.
            // Allows challenge specs to assert on 3xx status codes.
            return http.ErrUseLastResponse
        },
    }

    resp, err := client.Do(req)
    if err != nil {
        // Connection refused or timeout — treat as "blocked" for expectedStatusCode==0
        if target.ExpectedStatusCode == 0 {
            return true, fmt.Sprintf("Connection to %s blocked as expected", target.URL)
        }
        return false, fmt.Sprintf("Connection to %s failed: %v", target.URL, err)
    }
    defer func() { _ = resp.Body.Close() }()

    if resp.StatusCode == target.ExpectedStatusCode {
        return true, ""
    }
    return false, fmt.Sprintf("Connection to %s: got status %d, expected %d",
        target.URL, resp.StatusCode, target.ExpectedStatusCode)
}
```

**Step 4 — Run tests to confirm GREEN:**

```bash
go test ./internal/validation/... -run "TestCheckExternalConnectivity|TestExecuteConnectivity_ExternalMode" -v -count=1
```

All 8+ test cases must pass.

**Step 5 — Run full suite:**

```bash
task test:unit
```

No regressions.
  </action>
  <verify>
    <automated>go test ./internal/validation/... -run "TestCheckExternalConnectivity|TestExecuteConnectivity_ExternalMode" -v -count=1</automated>
  </verify>
  <done>All external connectivity tests pass (GREEN); `task test:unit` exits 0; `task lint` exits 0 (no new lint errors from net/http import or new methods)</done>
</task>

</tasks>

<verification>
After both tasks complete:

```bash
# External mode tests
go test ./internal/validation/... -run "TestCheckExternalConnectivity|TestExecuteConnectivity_ExternalMode|TestParse_Connectivity_ExternalMode" -v -count=1

# Full unit suite
task test:unit

# Lint clean
task lint
```

All green. Total test count increased by 7+ tests (new external mode cases).
</verification>

<success_criteria>
- `checkExternalConnectivity` method exists in `executor.go` and uses `net/http` with `req.Host` override
- `executeConnectivity` branches on `spec.Mode == "external"` before any SourcePod logic
- 8 new executor tests pass; 5 loader tests from Plan 01 still pass
- `task test:unit` exits 0 — no regressions in any of the 297+ pre-existing tests
- `task lint` exits 0
</success_criteria>

<output>
After completion, create `.planning/phases/08-external-http/08-02-SUMMARY.md`
</output>
