~bigbes/sr-ht-spec

ref: a53c6d7ddd2d3718183838ae0354aa250ab4b892 sr-ht-spec/cmd/specsrht-migrate/main_test.go -rw-r--r-- 16.0 KiB
a53c6d7d — Eugene Blikh migrate: install the instance's masking before brant can log a DSN 11 hours ago
                                                                                
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package main

import (
	"bytes"
	"context"
	"crypto/rand"
	"database/sql"
	"encoding/hex"
	"errors"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"git.sr.ht/~bitfehler/brant/cli"
	"github.com/alexflint/go-arg"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/vaughan0/go-ini"
)

// testArgvEnv turns a re-executed copy of this test binary into the migrate
// binary itself: TestMain sees it, replaces os.Args with its whitespace-split
// value and calls main().
//
// Running main() in a subprocess is the only way to observe what main() does.
// It reads the config off the filesystem through config.LoadConfig, the record
// under test is written by a library past every seam a unit test could reach,
// and the run ends in os.Exit — which takes the process with it. What is under
// test is what an operator finds in the upgrade log, so the test has to read
// that log.
const testArgvEnv = "SPECSRHT_MIGRATE_TEST_ARGV"

func TestMain(m *testing.M) {
	if argv, ok := os.LookupEnv(testArgvEnv); ok {
		os.Args = append([]string{progName}, strings.Fields(argv)...)
		main()
		os.Exit(0)
	}
	os.Exit(m.Run())
}

// runMain runs main() in a subprocess whose working directory is empty — no
// config.ini, no ./migrations — and returns everything the process wrote and the
// status it exited with.
//
// Stdout and stderr are interleaved into one buffer because that is how a
// package manager's upgrade log shows them, and the question this asks is what
// an operator finds there.
func runMain(t *testing.T, argv string) (output string, code int) {
	t.Helper()

	exe, err := os.Executable()
	require.NoError(t, err, "locate the test binary to re-execute")

	cmd := exec.Command(exe)
	cmd.Dir = t.TempDir()
	cmd.Env = append(os.Environ(), testArgvEnv+"="+argv)
	var buf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &buf

	err = cmd.Run()
	var exit *exec.ExitError
	switch {
	case err == nil:
		code = 0
	case errors.As(err, &exit):
		code = exit.ExitCode()
	default:
		require.NoError(t, err, "run %s %s", exe, argv)
	}
	return buf.String(), code
}

// testPassword is a fake credential no configuration on this instance holds. It
// is written into the DSN the test passes and looked for in everything the
// process wrote; a real one would put the thing under test into the test log.
const testPassword = "HUNTER2SECRET"

// TestMainDoesNotPrintTheConnectionString pins the reason main() installs a
// logger at all.
//
// brant reports a migration directory it cannot open with
// `slog.Error("failed to create provider", "datasource", a.DataSourceName, ...)`
// — the connection string, password and all, at ERR level. A missing directory
// is not an exotic state: it is what an installed package is in until its first
// migration ships. Two things have to hold for the password not to reach the
// journal, and this asserts through both: the key "datasource" must be in the
// instance's mask list (sr-ht-ecore's, which did not know that spelling until it
// was added), and a handler carrying that list must be slog's default by the
// time brant writes, or the record goes to Go's built-in stderr handler and no
// list of any kind applies.
func TestMainDoesNotPrintTheConnectionString(t *testing.T) {
	out, code := runMain(t,
		"up --dir /nonexistent --dsn postgresql://u:"+testPassword+"@localhost/x")

	// The run must actually reach brant and fail there, or the assertions below
	// would pass over an empty log.
	assert.NotZero(t, code, "the missing directory must still be a failed run: %s", out)
	assert.Contains(t, out, "failed to create provider",
		"the leaking record must have been written at all: %s", out)

	assert.NotContains(t, out, testPassword, "the DSN reached the log in the clear: %s", out)
	assert.Contains(t, out, "datasource=***", "%s", out)
}

// testParse parses argv the way main() does, except that the environment is
// ignored: BRANT_DSN / BRANT_MIGRATION_DIR / BRANT_DIALECT in a developer's
// shell would otherwise silently change the defaults under test.
func testParse(t *testing.T, argv ...string) (*arg.Parser, *Args) {
	t.Helper()
	p, a := newParser(arg.Config{IgnoreEnv: true, Out: os.Stderr, Exit: func(int) {}})
	if err := p.Parse(argv); err != nil {
		t.Fatalf("parse %v: %v", argv, err)
	}
	return p, a
}

func TestParseSubcommands(t *testing.T) {
	t.Run("up", func(t *testing.T) {
		p, a := testParse(t, "up")
		if p.Subcommand() == nil {
			t.Fatal("up: no subcommand selected")
		}
		if a.Up == nil {
			t.Fatal("up: Up subcommand not set")
		}
		if a.Init != nil {
			t.Error("up: Init unexpectedly set")
		}
		if a.Directory != defaultDirectory {
			t.Errorf("up: Directory = %q, want %q", a.Directory, defaultDirectory)
		}
		if a.DataSourceName != "" {
			t.Errorf("up: DataSourceName = %q, want empty", a.DataSourceName)
		}
		if a.Auto {
			t.Error("up: Auto set without -a")
		}
	})

	t.Run("current", func(t *testing.T) {
		_, a := testParse(t, "current")
		if a.Current == nil {
			t.Fatal("current: Current subcommand not set")
		}
	})

	t.Run("init", func(t *testing.T) {
		p, a := testParse(t, "init")
		if p.Subcommand() == nil {
			t.Fatal("init: no subcommand selected")
		}
		if a.Init == nil {
			t.Fatal("init: Init subcommand not set")
		}
		if a.Init.Schema != defaultSchema {
			t.Errorf("init: Schema = %q, want %q", a.Init.Schema, defaultSchema)
		}
	})

	t.Run("init --schema", func(t *testing.T) {
		_, a := testParse(t, "init", "--schema", "/opt/spec.sr.ht.sql")
		if a.Init == nil {
			t.Fatal("init --schema: Init subcommand not set")
		}
		if a.Init.Schema != "/opt/spec.sr.ht.sql" {
			t.Errorf("init --schema: Schema = %q", a.Init.Schema)
		}
	})

	t.Run("-a up", func(t *testing.T) {
		_, a := testParse(t, "-a", "up")
		if !a.Auto {
			t.Error("-a up: Auto not set")
		}
		if a.Up == nil {
			t.Error("-a up: Up subcommand not set")
		}
	})

	t.Run("--dsn and --dir", func(t *testing.T) {
		_, a := testParse(t, "--dsn", "postgres://u@h/spec.sr.ht", "--dir", "/srv/m", "up")
		if a.DataSourceName != "postgres://u@h/spec.sr.ht" {
			t.Errorf("DataSourceName = %q", a.DataSourceName)
		}
		if a.Directory != "/srv/m" {
			t.Errorf("Directory = %q", a.Directory)
		}
	})

	// The brant subcommands we do not advertise in the README must still parse:
	// this binary is a wrapper, not a reduced surface.
	for _, name := range []string{"down", "list", "validate", "ping"} {
		t.Run(name, func(t *testing.T) {
			p, _ := testParse(t, name)
			if p.Subcommand() == nil {
				t.Fatalf("%s: no subcommand selected", name)
			}
		})
	}
}

func TestParseNoSubcommandIsUsageError(t *testing.T) {
	p, _ := testParse(t)
	if p.Subcommand() != nil {
		t.Fatal("bare invocation selected a subcommand")
	}
}

func TestResolveDSN(t *testing.T) {
	confWith := func(dsn string) ini.File {
		f := ini.File{serviceName: ini.Section{}}
		if dsn != "" {
			f[serviceName]["connection-string"] = dsn
		}
		return f
	}

	t.Run("flag wins over config", func(t *testing.T) {
		got, err := resolveDSN(confWith("postgres://from-config/x"), "postgres://from-flag/x")
		if err != nil {
			t.Fatalf("resolveDSN: %v", err)
		}
		if got != "postgres://from-flag/x" {
			t.Errorf("got %q, want the --dsn value", got)
		}
	})

	t.Run("config used when flag empty", func(t *testing.T) {
		got, err := resolveDSN(confWith("postgres://from-config/x"), "")
		if err != nil {
			t.Fatalf("resolveDSN: %v", err)
		}
		if got != "postgres://from-config/x" {
			t.Errorf("got %q, want the configured value", got)
		}
	})

	t.Run("missing key is an error", func(t *testing.T) {
		if _, err := resolveDSN(ini.File{}, ""); err == nil {
			t.Fatal("expected an error with no config and no --dsn")
		}
	})

	t.Run("empty configured value is an error", func(t *testing.T) {
		if _, err := resolveDSN(confWith(""), ""); err == nil {
			t.Fatal("expected an error for an empty connection-string")
		}
	})
}

func TestResolvePaths(t *testing.T) {
	t.Run("checkout ./migrations wins", func(t *testing.T) {
		dir := t.TempDir()
		if err := os.Mkdir(filepath.Join(dir, "migrations"), 0o755); err != nil {
			t.Fatal(err)
		}
		t.Chdir(dir)

		a := &Args{Init: &InitArgs{Schema: defaultSchema}}
		a.Directory = defaultDirectory
		if err := resolvePaths(ini.File{}, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		if a.Directory != defaultDirectory {
			t.Errorf("Directory = %q, want the checkout dir %q", a.Directory, defaultDirectory)
		}
		if a.Init.Schema != defaultSchema {
			t.Errorf("Schema = %q, want the checkout file %q", a.Init.Schema, defaultSchema)
		}
	})

	t.Run("installed assets path when no ./migrations", func(t *testing.T) {
		t.Chdir(t.TempDir())

		a := &Args{Init: &InitArgs{Schema: defaultSchema}}
		a.Directory = defaultDirectory
		if err := resolvePaths(ini.File{}, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		wantDir := filepath.Join(defaultAssets, "migrations", serviceName)
		if a.Directory != wantDir {
			t.Errorf("Directory = %q, want %q", a.Directory, wantDir)
		}
		wantSchema := filepath.Join(defaultAssets, serviceName+".sql")
		if a.Init.Schema != wantSchema {
			t.Errorf("Schema = %q, want %q", a.Init.Schema, wantSchema)
		}
	})

	t.Run("[sr.ht]assets overrides the installed path", func(t *testing.T) {
		t.Chdir(t.TempDir())

		conf := ini.File{"sr.ht": ini.Section{"assets": "/opt/sourcehut"}}
		a := &Args{Init: &InitArgs{Schema: defaultSchema}}
		a.Directory = defaultDirectory
		if err := resolvePaths(conf, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		if want := "/opt/sourcehut/migrations/" + serviceName; a.Directory != want {
			t.Errorf("Directory = %q, want %q", a.Directory, want)
		}
		if want := "/opt/sourcehut/" + serviceName + ".sql"; a.Init.Schema != want {
			t.Errorf("Schema = %q, want %q", a.Init.Schema, want)
		}
	})

	t.Run("--dir override is respected verbatim", func(t *testing.T) {
		dir := t.TempDir()
		if err := os.Mkdir(filepath.Join(dir, "migrations"), 0o755); err != nil {
			t.Fatal(err)
		}
		t.Chdir(dir)

		a := &Args{Init: &InitArgs{Schema: defaultSchema}}
		a.Directory = "/srv/other-migrations"
		if err := resolvePaths(ini.File{}, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		if a.Directory != "/srv/other-migrations" {
			t.Errorf("Directory = %q, want the --dir value", a.Directory)
		}
		if a.Init.Schema != defaultSchema {
			t.Errorf("Schema = %q, want it untouched when --dir is given", a.Init.Schema)
		}
	})

	t.Run("--schema override survives the assets fallback", func(t *testing.T) {
		t.Chdir(t.TempDir())

		a := &Args{Init: &InitArgs{Schema: "/tmp/custom.sql"}}
		a.Directory = defaultDirectory
		if err := resolvePaths(ini.File{}, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		if a.Init.Schema != "/tmp/custom.sql" {
			t.Errorf("Schema = %q, want the --schema value", a.Init.Schema)
		}
	})

	t.Run("a ./migrations file is not a directory", func(t *testing.T) {
		dir := t.TempDir()
		if err := os.WriteFile(filepath.Join(dir, "migrations"), []byte("not a dir"), 0o644); err != nil {
			t.Fatal(err)
		}
		t.Chdir(dir)

		a := &Args{}
		a.Directory = defaultDirectory
		if err := resolvePaths(ini.File{}, a); err != nil {
			t.Fatalf("resolvePaths: %v", err)
		}
		if want := filepath.Join(defaultAssets, "migrations", serviceName); a.Directory != want {
			t.Errorf("Directory = %q, want the assets path %q", a.Directory, want)
		}
	})
}

// testEnv names the DSN env var that gates the Postgres-backed tests, matching
// the convention used by the db package. When unset those tests skip; the flag,
// DSN and path-resolution tests above run on a machine with no database at all.
const testEnv = "SPECSRHT_TEST_PG"

// scratchDSN creates an isolated schema on the Postgres pointed at by
// SPECSRHT_TEST_PG and returns a DSN pinned to it, plus a cleanup that drops it.
// A per-test schema avoids needing CREATE DATABASE privileges.
func scratchDSN(t *testing.T) (string, func()) {
	t.Helper()
	base := os.Getenv(testEnv)
	if base == "" {
		t.Skipf("%s not set; skipping Postgres-backed test (set it to a DSN to run)", testEnv)
	}

	admin, err := sql.Open("postgres", base)
	if err != nil {
		t.Fatalf("open admin pool: %v", err)
	}
	if err := admin.Ping(); err != nil {
		admin.Close()
		t.Fatalf("ping %s: %v", testEnv, err)
	}

	buf := make([]byte, 8)
	if _, err := rand.Read(buf); err != nil {
		admin.Close()
		t.Fatalf("rand: %v", err)
	}
	schema := "specsrht_migrate_test_" + hex.EncodeToString(buf)
	if _, err := admin.Exec(`CREATE SCHEMA "` + schema + `"`); err != nil {
		admin.Close()
		t.Fatalf("create schema %s: %v", schema, err)
	}

	scoped, err := withSearchPath(base, schema)
	if err != nil {
		admin.Exec(`DROP SCHEMA "` + schema + `" CASCADE`)
		admin.Close()
		t.Fatalf("build scoped dsn: %v", err)
	}

	return scoped, func() {
		if _, err := admin.Exec(`DROP SCHEMA "` + schema + `" CASCADE`); err != nil {
			t.Errorf("drop schema %s: %v", schema, err)
		}
		admin.Close()
	}
}

// withSearchPath returns base with a connection option that pins search_path to
// schema, handling both the URL and keyword DSN forms.
func withSearchPath(base, schema string) (string, error) {
	opt := "-c search_path=" + schema
	if strings.Contains(base, "://") {
		u, err := url.Parse(base)
		if err != nil {
			return "", err
		}
		q := u.Query()
		q.Set("options", opt)
		u.RawQuery = q.Encode()
		return u.String(), nil
	}
	return base + " options='" + opt + "'", nil
}

// repoFile resolves a path relative to the repository root (this package lives
// two levels below it).
func repoFile(name string) string {
	return filepath.Join("..", "..", name)
}

func newArgs(dsn, dir string) *Args {
	drv := driverName
	return &Args{Args: cli.Args{
		Directory:      dir,
		DataSourceName: dsn,
		Driver:         &drv,
	}}
}

// TestInitStampsToHead exercises the `init` path against a real database: the
// full schema.sql applies and the version table lands on the head migration, so
// a subsequent `up` has nothing to do.
func TestInitStampsToHead(t *testing.T) {
	dsn, cleanup := scratchDSN(t)
	defer cleanup()

	a := newArgs(dsn, repoFile("migrations"))
	a.Init = &InitArgs{Schema: repoFile("schema.sql")}
	if err := initDatabase(a); err != nil {
		t.Fatalf("initDatabase: %v", err)
	}

	p, err := cli.ProviderFromArgs(&a.Args)
	if err != nil {
		t.Fatalf("provider: %v", err)
	}
	defer p.Close()

	ctx := context.Background()
	cur, err := p.Current(ctx)
	if err != nil {
		t.Fatalf("current: %v", err)
	}
	sources := p.ListSources()
	if len(sources) == 0 {
		t.Fatal("no migration sources found")
	}
	if head := sources[len(sources)-1].Version; cur != head {
		t.Errorf("current = %d after init, want head %d", cur, head)
	}

	applied, err := p.Up(ctx)
	if err != nil {
		t.Fatalf("up after init: %v", err)
	}
	if len(applied) != 0 {
		t.Errorf("up after init applied %d migrations, want 0", len(applied))
	}
}

// TestUpFromEmpty exercises the upgrade path: replaying migrations/*.sql on an
// empty schema reaches the same head version init stamps to.
func TestUpFromEmpty(t *testing.T) {
	dsn, cleanup := scratchDSN(t)
	defer cleanup()

	a := newArgs(dsn, repoFile("migrations"))
	p, err := cli.ProviderFromArgs(&a.Args)
	if err != nil {
		t.Fatalf("provider: %v", err)
	}
	defer p.Close()

	ctx := context.Background()
	applied, err := p.Up(ctx)
	if err != nil {
		t.Fatalf("up: %v", err)
	}
	if len(applied) == 0 {
		t.Fatal("up applied no migrations on an empty schema")
	}

	cur, err := p.Current(ctx)
	if err != nil {
		t.Fatalf("current: %v", err)
	}
	sources := p.ListSources()
	if head := sources[len(sources)-1].Version; cur != head {
		t.Errorf("current = %d after up, want head %d", cur, head)
	}

	// The migrations must produce the tables the design's schema declares.
	db, err := p.DB()
	if err != nil {
		t.Fatalf("db: %v", err)
	}
	for _, table := range []string{"space", "document_id", "proposal", "index_stamp", "digest_mark"} {
		var n int
		if err := db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&n); err != nil {
			t.Errorf("table %s missing after up: %v", table, err)
		}
	}

	// And agent_token must be gone: 0005 drops it, and a database that still had
	// it would still have a second door into the write plane.
	if err := db.QueryRow(`SELECT count(*) FROM agent_token`).Scan(new(int)); err == nil {
		t.Error("agent_token survived the migrations; agent credentials come from tokens.sr.ht")
	}
}