1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
|
package integrationtests
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
gossh "golang.org/x/crypto/ssh"
)
const (
authKeyFastPathLog = "Authorized by in-memory auth key store"
dcatExpectedFirstOutput = "1 Sat 2 Oct 13:46:45 EEST 2021"
)
func TestAuthKeyFastReconnectIntegration(t *testing.T) {
skipIfNotIntegrationTest(t)
cleanupTmpFiles(t)
t.Run("RegistrationFastPathAndFallback", testAuthKeyRegistrationFastPathAndFallback)
t.Run("TTLExpiry", testAuthKeyTTLExpiry)
t.Run("MaxKeysPerUser", testAuthKeyMaxKeysPerUser)
t.Run("NoAuthKeyFlag", testNoAuthKeyFlagDisablesFeature)
}
func testAuthKeyRegistrationFastPathAndFallback(t *testing.T) {
authKeyPath := createAuthKeyPair(t, "authkey-registration")
server := startAuthKeyServer(t, "")
defer server.Stop()
exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_registration_1.tmp", server.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected first connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_registration_1.tmp")
waitForServerLogs()
if got := server.CountLogLinesContaining(authKeyFastPathLog); got != 0 {
t.Fatalf("Expected first connection to use fallback, fast-path count=%d", got)
}
exitCode, err = runDCatWithAuthKey(server.Context(), t, "authkey_registration_2.tmp", server.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected second connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_registration_2.tmp")
waitForServerLogs()
if got := server.CountLogLinesContaining(authKeyFastPathLog); got < 1 {
t.Fatalf("Expected fast-path authorization after registration, fast-path count=%d", got)
}
server.Stop()
time.Sleep(300 * time.Millisecond)
restartedServer := startAuthKeyServer(t, "")
defer restartedServer.Stop()
exitCode, err = runDCatWithAuthKey(restartedServer.Context(), t, "authkey_registration_3.tmp", restartedServer.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected fallback after restart to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_registration_3.tmp")
waitForServerLogs()
if got := restartedServer.CountLogLinesContaining(authKeyFastPathLog); got != 0 {
t.Fatalf("Expected no fast-path hit on first post-restart connection, fast-path count=%d", got)
}
}
func testAuthKeyTTLExpiry(t *testing.T) {
authKeyPath := createAuthKeyPair(t, "authkey-ttl")
ttlSeconds := 8
cfgFile := writeAuthKeyServerConfig(t, ttlSeconds, 5)
server := startAuthKeyServer(t, cfgFile)
defer server.Stop()
exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_ttl_1.tmp", server.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected first connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_ttl_1.tmp")
exitCode, err = runDCatWithAuthKey(server.Context(), t, "authkey_ttl_2.tmp", server.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected second connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_ttl_2.tmp")
fastPathCountAfterSecond := waitForLogCountAtLeast(server, authKeyFastPathLog, 1, 5*time.Second)
if fastPathCountAfterSecond < 1 {
t.Fatalf("Expected fast-path hit before TTL expiry, count=%d\nserver logs:\n%s",
fastPathCountAfterSecond, strings.Join(server.LogLines(), "\n"))
}
time.Sleep(time.Duration(ttlSeconds+1) * time.Second)
exitCode, err = runDCatWithAuthKey(server.Context(), t, "authkey_ttl_3.tmp", server.Address(), authKeyPath, false)
if err != nil || exitCode != 0 {
t.Fatalf("Expected fallback after TTL expiry to still connect, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_ttl_3.tmp")
waitForServerLogs()
fastPathCountAfterThird := server.CountLogLinesContaining(authKeyFastPathLog)
if fastPathCountAfterThird != fastPathCountAfterSecond {
t.Fatalf("Expected TTL-expired key to stop fast-path hits: before=%d after=%d",
fastPathCountAfterSecond, fastPathCountAfterThird)
}
}
func testAuthKeyMaxKeysPerUser(t *testing.T) {
authKeyOne := createAuthKeyPair(t, "authkey-max-one")
authKeyTwo := createAuthKeyPair(t, "authkey-max-two")
cfgFile := writeAuthKeyServerConfig(t, 3600, 1)
server := startAuthKeyServer(t, cfgFile)
defer server.Stop()
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_max_1.tmp", server.Address(), authKeyOne, false); err != nil || exitCode != 0 {
t.Fatalf("Expected first key registration to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_max_1.tmp")
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_max_2.tmp", server.Address(), authKeyTwo, false); err != nil || exitCode != 0 {
t.Fatalf("Expected second key registration to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_max_2.tmp")
waitForServerLogs()
initialFastPathCount := server.CountLogLinesContaining(authKeyFastPathLog)
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_max_3.tmp", server.Address(), authKeyOne, false); err != nil || exitCode != 0 {
t.Fatalf("Expected first key connection (after max eviction) to succeed via fallback, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_max_3.tmp")
waitForServerLogs()
afterOldKeyCount := server.CountLogLinesContaining(authKeyFastPathLog)
if afterOldKeyCount != initialFastPathCount {
t.Fatalf("Expected evicted old key to avoid fast-path hit: before=%d after=%d",
initialFastPathCount, afterOldKeyCount)
}
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_max_4.tmp", server.Address(), authKeyOne, false); err != nil || exitCode != 0 {
t.Fatalf("Expected re-registered first key to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_max_4.tmp")
waitForServerLogs()
afterNewKeyCount := server.CountLogLinesContaining(authKeyFastPathLog)
if afterNewKeyCount <= afterOldKeyCount {
t.Fatalf("Expected re-registered key to use fast-path: old-count=%d new-count=%d", afterOldKeyCount, afterNewKeyCount)
}
}
func testNoAuthKeyFlagDisablesFeature(t *testing.T) {
authKeyPath := createAuthKeyPair(t, "authkey-noauth")
server := startAuthKeyServer(t, "")
defer server.Stop()
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_noauth_1.tmp", server.Address(), authKeyPath, true); err != nil || exitCode != 0 {
t.Fatalf("Expected first --no-auth-key connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_noauth_1.tmp")
if exitCode, err := runDCatWithAuthKey(server.Context(), t, "authkey_noauth_2.tmp", server.Address(), authKeyPath, true); err != nil || exitCode != 0 {
t.Fatalf("Expected second --no-auth-key connection to succeed, exit=%d err=%v", exitCode, err)
}
assertDCatSuccessfulOutput(t, "authkey_noauth_2.tmp")
waitForServerLogs()
if got := server.CountLogLinesContaining(authKeyFastPathLog); got != 0 {
t.Fatalf("Expected --no-auth-key to prevent fast-path registration, fast-path count=%d", got)
}
}
type authKeyServer struct {
ctx context.Context
cancel context.CancelFunc
addr string
logs *authKeyServerLogs
}
func (s *authKeyServer) Stop() {
s.cancel()
}
func (s *authKeyServer) Context() context.Context {
return s.ctx
}
func (s *authKeyServer) Address() string {
return s.addr
}
func (s *authKeyServer) CountLogLinesContaining(substring string) int {
return s.logs.countContaining(substring)
}
func (s *authKeyServer) LogLines() []string {
return s.logs.snapshot()
}
type authKeyServerLogs struct {
mu sync.Mutex
lines []string
}
func newAuthKeyServerLogs() *authKeyServerLogs {
return &authKeyServerLogs{
lines: make([]string, 0, 128),
}
}
func (l *authKeyServerLogs) append(line string) {
l.mu.Lock()
defer l.mu.Unlock()
l.lines = append(l.lines, line)
}
func (l *authKeyServerLogs) countContaining(substring string) int {
l.mu.Lock()
defer l.mu.Unlock()
count := 0
for _, line := range l.lines {
if strings.Contains(line, substring) {
count++
}
}
return count
}
func (l *authKeyServerLogs) snapshot() []string {
l.mu.Lock()
defer l.mu.Unlock()
lines := make([]string, len(l.lines))
copy(lines, l.lines)
return lines
}
func startAuthKeyServer(t *testing.T, cfgFile string) *authKeyServer {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
port := getUniquePortNumber()
args := []string{
"--cfg", "none",
"--logger", "stdout",
"--logLevel", "info",
"--bindAddress", "localhost",
"--port", fmt.Sprintf("%d", port),
}
if cfgFile != "" {
args = append(args, "--cfg", cfgFile)
}
stdoutCh, stderrCh, cmdErrCh, err := startCommandWithEnv(ctx, t, "", "../dserver",
map[string]string{"DTAIL_TURBOBOOST_DISABLE": "yes"}, args...)
if err != nil {
cancel()
t.Fatalf("Unable to start dserver: %v", err)
}
logs := newAuthKeyServerLogs()
go func() {
for {
select {
case line, ok := <-stdoutCh:
if ok {
logs.append(line)
}
case line, ok := <-stderrCh:
if ok {
logs.append(line)
}
case err := <-cmdErrCh:
if err != nil {
logs.append(err.Error())
}
return
case <-ctx.Done():
return
}
}
}()
if err := waitForServerReady(ctx, "localhost", port); err != nil {
cancel()
t.Fatalf("Unable to start dserver: %v", err)
}
return &authKeyServer{
ctx: ctx,
cancel: cancel,
addr: fmt.Sprintf("localhost:%d", port),
logs: logs,
}
}
func runDCatWithAuthKey(ctx context.Context, t *testing.T, outFile,
serverAddress, authKeyPath string, noAuthKey bool) (int, error) {
t.Helper()
args := []string{
"--plain",
"--cfg", "none",
"--servers", serverAddress,
"--files", "dcat1a.txt",
"--trustAllHosts",
"--noColor",
"--auth-key-path", authKeyPath,
}
if noAuthKey {
args = append(args, "--no-auth-key")
}
return runCommand(ctx, t, outFile, "../dcat", args...)
}
func assertDCatSuccessfulOutput(t *testing.T, outFile string) {
t.Helper()
outBytes, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("Unable to read dcat output file %s: %v", outFile, err)
}
output := string(outBytes)
if strings.Contains(output, "SSH handshake failed") {
t.Fatalf("Expected successful SSH connection, got handshake failure in %s:\n%s", outFile, output)
}
if !strings.Contains(output, dcatExpectedFirstOutput) {
t.Fatalf("Expected dcat output to contain %q in %s, got:\n%s", dcatExpectedFirstOutput, outFile, output)
}
}
func writeAuthKeyServerConfig(t *testing.T, ttlSeconds, maxPerUser int) string {
t.Helper()
cfgPath := filepath.Join(t.TempDir(), "authkey_server_config.json")
cfgContent := fmt.Sprintf(
`{"Server":{"AuthKeyEnabled":true,"AuthKeyTTLSeconds":%d,"AuthKeyMaxPerUser":%d}}`,
ttlSeconds, maxPerUser,
)
if err := os.WriteFile(cfgPath, []byte(cfgContent), 0600); err != nil {
t.Fatalf("Unable to write auth-key server config: %v", err)
}
return cfgPath
}
func createAuthKeyPair(t *testing.T, keyName string) string {
t.Helper()
keyPath := filepath.Join(t.TempDir(), keyName)
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("Unable to generate private key: %v", err)
}
privateKeyBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
if err := os.WriteFile(keyPath, privateKeyBytes, 0600); err != nil {
t.Fatalf("Unable to write private key: %v", err)
}
publicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
t.Fatalf("Unable to generate public key: %v", err)
}
if err := os.WriteFile(keyPath+".pub", gossh.MarshalAuthorizedKey(publicKey), 0600); err != nil {
t.Fatalf("Unable to write public key: %v", err)
}
return keyPath
}
func waitForServerLogs() {
time.Sleep(300 * time.Millisecond)
}
func waitForLogCountAtLeast(server *authKeyServer, substring string, minCount int, timeout time.Duration) int {
if minCount <= 0 {
return server.CountLogLinesContaining(substring)
}
deadline := time.Now().Add(timeout)
for {
count := server.CountLogLinesContaining(substring)
if count >= minCount {
return count
}
if time.Now().After(deadline) {
return count
}
time.Sleep(100 * time.Millisecond)
}
}
|