|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "crypto/tls" |
| 5 | + "errors" |
4 | 6 | "net/http" |
5 | 7 | "net/http/httptest" |
6 | 8 | "net/url" |
7 | 9 | "strconv" |
| 10 | + "sync" |
8 | 11 | "sync/atomic" |
9 | 12 | "testing" |
10 | 13 | "time" |
11 | 14 | ) |
12 | 15 |
|
| 16 | +func sslTestServer(t *testing.T, handshake func(*tls.ClientHelloInfo) (*tls.Config, error)) (*httptest.Server, ConfigDocument) { |
| 17 | + t.Helper() |
| 18 | + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })) |
| 19 | + server.TLS = &tls.Config{GetConfigForClient: handshake} |
| 20 | + server.StartTLS() |
| 21 | + t.Cleanup(server.Close) |
| 22 | + parsed, err := url.Parse(server.URL) |
| 23 | + if err != nil { |
| 24 | + t.Fatal(err) |
| 25 | + } |
| 26 | + port, err := strconv.Atoi(parsed.Port()) |
| 27 | + if err != nil { |
| 28 | + t.Fatal(err) |
| 29 | + } |
| 30 | + doc := minimalTestConfig() |
| 31 | + doc["sslcerts"] = []any{map[string]any{ |
| 32 | + "name": "local", "domain": server.URL, "port": port, "interval": 7200, |
| 33 | + }} |
| 34 | + return server, doc |
| 35 | +} |
| 36 | + |
| 37 | +func sslTestState(app *App, key string) CertState { |
| 38 | + app.certMu.RLock() |
| 39 | + defer app.certMu.RUnlock() |
| 40 | + return *app.certs[key] |
| 41 | +} |
| 42 | + |
| 43 | +func waitForSSLCheck(t *testing.T, app *App, config SSLCertConfig, previous time.Time) CertState { |
| 44 | + t.Helper() |
| 45 | + eventually(t, 2*time.Second, func() bool { |
| 46 | + state := sslTestState(app, certKey(config)) |
| 47 | + return !state.Checking && state.LastCheck.After(previous) |
| 48 | + }) |
| 49 | + return sslTestState(app, certKey(config)) |
| 50 | +} |
| 51 | + |
| 52 | +func TestSSLFailureAndRecovery(t *testing.T) { |
| 53 | + var rejectHandshake atomic.Bool |
| 54 | + server, doc := sslTestServer(t, func(*tls.ClientHelloInfo) (*tls.Config, error) { |
| 55 | + if rejectHandshake.Load() { |
| 56 | + return nil, errors.New("test TLS failure") |
| 57 | + } |
| 58 | + return nil, nil |
| 59 | + }) |
| 60 | + app := newTestApp(t, doc) |
| 61 | + config := app.RuntimeSnapshot().SSLCerts[0] |
| 62 | + key := certKey(config) |
| 63 | + app.runDueSSLChecks() |
| 64 | + state := waitForSSLCheck(t, app, config, time.Time{}) |
| 65 | + if state.ExpireTS != server.Certificate().NotAfter.Unix() || state.LastError != "" { |
| 66 | + t.Fatalf("initial certificate check: %+v", state) |
| 67 | + } |
| 68 | + |
| 69 | + for _, phase := range []string{"TLS failure", "recovery", "connection failure"} { |
| 70 | + t.Run(phase, func(t *testing.T) { |
| 71 | + switch phase { |
| 72 | + case "TLS failure": |
| 73 | + rejectHandshake.Store(true) |
| 74 | + case "recovery": |
| 75 | + rejectHandshake.Store(false) |
| 76 | + case "connection failure": |
| 77 | + server.Close() |
| 78 | + } |
| 79 | + previous := state.LastCheck |
| 80 | + app.certMu.Lock() |
| 81 | + // Simulate the next scheduled interval without waiting two hours. |
| 82 | + app.certs[key].LastCheck = time.Time{} |
| 83 | + if phase != "recovery" { |
| 84 | + // A failed check must also discard any prior hostname mismatch. |
| 85 | + app.certs[key].Mismatch = true |
| 86 | + } |
| 87 | + app.certMu.Unlock() |
| 88 | + app.runDueSSLChecks() |
| 89 | + state = waitForSSLCheck(t, app, config, previous) |
| 90 | + entry := app.sslSnapshot([]SSLCertConfig{config}, time.Now())[0].(map[string]any) |
| 91 | + if phase == "recovery" { |
| 92 | + if state.LastError != "" || state.ExpireTS != server.Certificate().NotAfter.Unix() || state.Mismatch { |
| 93 | + t.Errorf("certificate did not recover: %+v", state) |
| 94 | + } |
| 95 | + if _, hasError := entry["error"]; hasError || entry["expire_days"].(int) <= 0 { |
| 96 | + t.Errorf("recovered snapshot: %#v", entry) |
| 97 | + } |
| 98 | + } else if state.LastError == "" || state.ExpireTS != 0 || state.Mismatch || |
| 99 | + entry["error"] == nil || entry["expire_ts"] != int64(0) || entry["expire_days"] != 0 || entry["mismatch"] != false { |
| 100 | + t.Errorf("failed check retained a certificate result: state=%+v snapshot=%#v", state, entry) |
| 101 | + } |
| 102 | + }) |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +func TestSSLConfigReloadRechecks(t *testing.T) { |
| 107 | + for _, change := range []string{"unchanged reload", "interval", "callback"} { |
| 108 | + t.Run(change, func(t *testing.T) { |
| 109 | + _, doc := sslTestServer(t, nil) |
| 110 | + app := newTestApp(t, doc) |
| 111 | + config := app.RuntimeSnapshot().SSLCerts[0] |
| 112 | + key := certKey(config) |
| 113 | + app.runDueSSLChecks() |
| 114 | + before := waitForSSLCheck(t, app, config, time.Time{}) |
| 115 | + alarmTime := time.Now() |
| 116 | + app.certMu.Lock() |
| 117 | + app.certs[key].LastAlarm7 = alarmTime |
| 118 | + app.certs[key].LastAlarm3 = alarmTime |
| 119 | + app.certs[key].LastAlarm1 = alarmTime |
| 120 | + app.certs[key].LastAlarmMismatch = alarmTime |
| 121 | + app.certMu.Unlock() |
| 122 | + |
| 123 | + if change == "unchanged reload" { |
| 124 | + if apiErr := app.ReloadConfig(); apiErr != nil { |
| 125 | + t.Fatal(apiErr) |
| 126 | + } |
| 127 | + } else { |
| 128 | + updated := app.ConfigSnapshot() |
| 129 | + cert := updated["sslcerts"].([]any)[0].(map[string]any) |
| 130 | + if change == "interval" { |
| 131 | + cert["interval"] = 14400 |
| 132 | + } else { |
| 133 | + cert["callback"] = "http://127.0.0.1:1/?message=" |
| 134 | + } |
| 135 | + if _, apiErr := app.ReplaceConfig(updated); apiErr != nil { |
| 136 | + t.Fatal(apiErr) |
| 137 | + } |
| 138 | + } |
| 139 | + state := sslTestState(app, key) |
| 140 | + if !state.LastCheck.IsZero() || state.Checking || state.ExpireTS != 0 || state.Mismatch || state.LastError != "" { |
| 141 | + t.Errorf("reload did not reset the certificate check: %+v", state) |
| 142 | + } |
| 143 | + if state.LastAlarm7 != alarmTime || state.LastAlarm3 != alarmTime || state.LastAlarm1 != alarmTime || state.LastAlarmMismatch != alarmTime { |
| 144 | + t.Errorf("reload reset notification cooldowns: %+v", state) |
| 145 | + } |
| 146 | + app.runDueSSLChecks() |
| 147 | + state = waitForSSLCheck(t, app, config, before.LastCheck) |
| 148 | + if state.ExpireTS == 0 || state.LastError != "" { |
| 149 | + t.Errorf("reload did not publish a fresh result: %+v", state) |
| 150 | + } |
| 151 | + }) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +func TestSSLDiscardInFlightResultAfterConfigChange(t *testing.T) { |
| 156 | + for _, change := range []string{"reload", "remove and readd"} { |
| 157 | + t.Run(change, func(t *testing.T) { |
| 158 | + oldStarted, newStarted := make(chan struct{}), make(chan struct{}) |
| 159 | + releaseOld, releaseNew := make(chan struct{}), make(chan struct{}) |
| 160 | + var oldOnce, newOnce sync.Once |
| 161 | + unblockOld := func() { oldOnce.Do(func() { close(releaseOld) }) } |
| 162 | + unblockNew := func() { newOnce.Do(func() { close(releaseNew) }) } |
| 163 | + var handshakes atomic.Int32 |
| 164 | + _, doc := sslTestServer(t, func(*tls.ClientHelloInfo) (*tls.Config, error) { |
| 165 | + switch handshakes.Add(1) { |
| 166 | + case 1: |
| 167 | + close(oldStarted) |
| 168 | + <-releaseOld |
| 169 | + case 2: |
| 170 | + close(newStarted) |
| 171 | + <-releaseNew |
| 172 | + } |
| 173 | + return nil, nil |
| 174 | + }) |
| 175 | + // Unblock handshakes before httptest.Server cleanup, including failures. |
| 176 | + t.Cleanup(unblockOld) |
| 177 | + t.Cleanup(unblockNew) |
| 178 | + app := newTestApp(t, doc) |
| 179 | + config := app.RuntimeSnapshot().SSLCerts[0] |
| 180 | + key := certKey(config) |
| 181 | + app.certMu.Lock() |
| 182 | + oldState := app.certs[key] |
| 183 | + oldState.Checking = true |
| 184 | + app.certMu.Unlock() |
| 185 | + oldDone := make(chan struct{}) |
| 186 | + go func() { |
| 187 | + app.executeSSLCheck(key, oldState) |
| 188 | + close(oldDone) |
| 189 | + }() |
| 190 | + await := func(channel <-chan struct{}) { |
| 191 | + t.Helper() |
| 192 | + select { |
| 193 | + case <-channel: |
| 194 | + case <-time.After(2 * time.Second): |
| 195 | + t.Fatal("certificate handshake did not reach the expected stage") |
| 196 | + } |
| 197 | + } |
| 198 | + await(oldStarted) |
| 199 | + if change == "reload" { |
| 200 | + if apiErr := app.ReloadConfig(); apiErr != nil { |
| 201 | + t.Fatal(apiErr) |
| 202 | + } |
| 203 | + } else { |
| 204 | + withoutCert := app.ConfigSnapshot() |
| 205 | + withoutCert["sslcerts"] = []any{} |
| 206 | + if _, apiErr := app.ReplaceConfig(withoutCert); apiErr != nil { |
| 207 | + t.Fatal(apiErr) |
| 208 | + } |
| 209 | + if _, apiErr := app.ReplaceConfig(doc); apiErr != nil { |
| 210 | + t.Fatal(apiErr) |
| 211 | + } |
| 212 | + } |
| 213 | + app.runDueSSLChecks() |
| 214 | + await(newStarted) |
| 215 | + unblockOld() |
| 216 | + await(oldDone) |
| 217 | + state := sslTestState(app, key) |
| 218 | + if !state.Checking || !state.LastCheck.IsZero() || state.ExpireTS != 0 || state.Mismatch || state.LastError != "" { |
| 219 | + t.Errorf("old check changed the new in-flight state: %+v", state) |
| 220 | + } |
| 221 | + unblockNew() |
| 222 | + state = waitForSSLCheck(t, app, config, time.Time{}) |
| 223 | + if state.ExpireTS == 0 || state.LastError != "" { |
| 224 | + t.Errorf("new check did not publish its result: %+v", state) |
| 225 | + } |
| 226 | + }) |
| 227 | + } |
| 228 | +} |
| 229 | + |
13 | 230 | func TestCertificateCheckAndSnapshot(t *testing.T) { |
14 | 231 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })) |
15 | 232 | defer server.Close() |
|
0 commit comments