oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "bytes"
5 "context"
6 "database/sql"
7 "encoding/json"
8 "io"
9 "net/url"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo"
17 _ "modernc.org/sqlite"
18)
19
20func checkFixture(t *testing.T, wal bool) (string, *sql.DB) {
21 t.Helper()
22 path := filepath.Join(t.TempDir(), "live ? database.db")
23 d, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String())
24 if err != nil {
25 t.Fatal(err)
26 }
27 t.Cleanup(func() { d.Close() })
28 if wal {
29 if _, err = d.Exec("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0"); err != nil {
30 t.Fatal(err)
31 }
32 }
33 if _, err = d.Exec("CREATE TABLE private_rows (value TEXT); INSERT INTO private_rows VALUES ('never-print-row-contents')"); err != nil {
34 t.Fatal(err)
35 }
36 return path, d
37}
38func decodeCheck(t *testing.T, b *bytes.Buffer) dbCheckSummary {
39 t.Helper()
40 var v dbCheckSummary
41 if b.Len() > 4096 || strings.Contains(b.String(), "never-print") || strings.Contains(b.String(), "private_rows") {
42 t.Fatalf("unsafe output: %q", b.String())
43 }
44 if err := json.Unmarshal(b.Bytes(), &v); err != nil {
45 t.Fatal(err)
46 }
47 return v
48}
49func TestCheckDBLiveWALAndReadOnly(t *testing.T) {
50 path, d := checkFixture(t, true)
51 var b bytes.Buffer
52 if code := checkDB(context.Background(), &b, path); code != 0 {
53 t.Fatalf("code=%d %s", code, b.String())
54 }
55 v := decodeCheck(t, &b)
56 if v.Status != "ok" || v.QuickCheck != "ok" || v.IntegrityCheck != "ok" || v.ErrorCount != 0 || v.PageCount == nil || *v.PageCount < 2 || v.PageSize == nil || v.JournalMode == nil || *v.JournalMode != "wal" || v.WALBytes == nil || *v.WALBytes <= 0 {
57 t.Fatalf("summary %+v", v)
58 }
59 ro, err := openCheckDB(path)
60 if err != nil {
61 t.Fatal(err)
62 }
63 defer ro.Close()
64 // Turn off query_only if present: mode=ro itself must refuse writes.
65 _, _ = ro.Exec("PRAGMA query_only=OFF")
66 if _, err = ro.Exec("INSERT INTO private_rows VALUES ('forbidden')"); err == nil {
67 t.Fatal("write allowed")
68 }
69 // The committed table exists only in WAL until the live writer closes.
70 var count int
71 if err = ro.QueryRow("SELECT count(*) FROM private_rows").Scan(&count); err != nil || count != 1 {
72 t.Fatalf("WAL not read: count=%d err=%v", count, err)
73 }
74 if _, err = d.Exec("INSERT INTO private_rows VALUES ('still writable')"); err != nil {
75 t.Fatal(err)
76 }
77}
78func TestCheckDBCorruptBTree(t *testing.T) {
79 path, d := checkFixture(t, false)
80 var page, size int
81 if err := d.QueryRow("SELECT rootpage FROM sqlite_schema WHERE name='private_rows'").Scan(&page); err != nil {
82 t.Fatal(err)
83 }
84 if err := d.QueryRow("PRAGMA page_size").Scan(&size); err != nil {
85 t.Fatal(err)
86 }
87 d.Close()
88 data, err := os.ReadFile(path)
89 if err != nil {
90 t.Fatal(err)
91 }
92 data[(page-1)*size] = 0xff // Invalid b-tree page type, leaving the header intact.
93 if err = os.WriteFile(path, data, 0600); err != nil {
94 t.Fatal(err)
95 }
96 var b bytes.Buffer
97 if code := checkDB(context.Background(), &b, path); code == 0 {
98 t.Fatal("corruption passed")
99 }
100 v := decodeCheck(t, &b)
101
102 if v.Status != "failed" || v.ErrorCount == 0 || v.QuickCheck != "findings_and_error" || v.IntegrityCheck != "findings_and_error" {
103 t.Fatalf("corruption summary %+v", v)
104 }
105}
106func TestCheckDBMissingAndNoBoot(t *testing.T) {
107 t.Setenv("EQUIPO_ORIGIN", "")
108 t.Setenv("EQUIPO_INSTANCE_KEY", "")
109 for _, tc := range []struct{ path, message string }{
110 {"", equipo.CopyDBPathMissing},
111 {filepath.Join(t.TempDir(), "missing-private-path"), equipo.CopyDBPathMissing},
112 {t.TempDir(), equipo.CopyDBPathInvalid},
113 {"relative.db", equipo.CopyDBPathInvalid},
114 {"file:/secret?mode=rw", equipo.CopyDBPathInvalid},
115 } {
116 path := tc.path
117 t.Setenv("CARLOS_DB", path)
118 var b, diag bytes.Buffer
119 if code := commandMain([]string{"check-db"}, &b, &diag, nil); code == 0 || diag.Len() != 0 {
120 t.Fatalf("boot or success: %d %s", code, diag.String())
121 }
122 if v := decodeCheck(t, &b); v.Message != tc.message || v.ErrorCount == 0 {
123 t.Fatalf("missing error %+v", v)
124 }
125 if strings.Contains(b.String(), "private-path") {
126 t.Fatal("path leaked")
127 }
128 }
129 path, _ := checkFixture(t, true)
130 t.Setenv("CARLOS_DB", path)
131 var b, diag bytes.Buffer
132 if code := commandMain([]string{"check-db"}, &b, &diag, nil); code != 0 || diag.Len() != 0 {
133 t.Fatalf("boot: %d %s", code, diag.String())
134 }
135 b.Reset()
136 if code := commandMain([]string{"check-db", "extra"}, &b, &diag, nil); code == 0 || diag.Len() != 0 {
137 t.Fatal("invalid arguments booted")
138 }
139}
140func TestCheckDBPrivacyAndBounds(t *testing.T) {
141 v := dbCheckSummary{}
142 for i := 0; i < 500; i++ {
143 v.finding("*** in database main ***\nTree 12 page 345 cell 0: secret-value row 765\nnever-print-row-contents")
144 }
145 if len(v.Issues) != 5 {
146 t.Fatalf("issue bound %d", len(v.Issues))
147 }
148 raw, _ := json.Marshal(v)
149 if strings.Contains(string(raw), "secret") || strings.Contains(string(raw), "765") || len(raw) > 4096 {
150 t.Fatalf("unsafe: %s", raw)
151 }
152 if v.Issues[0].BTree == nil || *v.Issues[0].BTree != 12 || v.Issues[0].Page == nil || *v.Issues[0].Page != 345 {
153 t.Fatalf("lost coordinates: %+v", v.Issues)
154 }
155}
156func TestCheckDBTimeout(t *testing.T) {
157 path, _ := checkFixture(t, true)
158 ctx, cancel := context.WithCancel(context.Background())
159 cancel()
160 var b bytes.Buffer
161 if code := checkDB(ctx, &b, path); code == 0 {
162 t.Fatal("cancel passed")
163 }
164 v := decodeCheck(t, &b)
165 if v.Message == "" || v.Status != "failed" {
166 t.Fatal(v)
167 }
168 if dbCheckLimit != 60*time.Second {
169 t.Fatal("deadline changed")
170 }
171}
172
173func TestCheckDBFindingsVersusErrorAndCap(t *testing.T) {
174 _, d := checkFixture(t, false)
175 tx, err := d.Begin()
176 if err != nil {
177 t.Fatal(err)
178 }
179 defer tx.Rollback()
180 s := dbCheckSummary{}
181 // Exercise the result consumer independently of SQLite's constraint checks.
182 query := `WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<250) SELECT 'Tree 12 page 345: never-print-row-contents' FROM n`
183 if got := s.check(context.Background(), tx, query); got != "findings" || s.ErrorCount != 100 || !s.LimitReached || len(s.Issues) != 5 {
184 t.Fatalf("bad cap or result: %s %+v", got, s)
185 }
186 s = dbCheckSummary{}
187 if got := s.check(context.Background(), tx, "SELECT * FROM missing_private_table"); got != "error" || s.ErrorCount != 1 {
188 t.Fatalf("query failure=%s %+v", got, s)
189 }
190}
191func TestCheckDBOwnDeadlineAndOutputFailure(t *testing.T) {
192 path, _ := checkFixture(t, true)
193 var b bytes.Buffer
194 if checkDBWithin(context.Background(), &b, path, 0) == 0 {
195 t.Fatal("own deadline missing")
196 }
197 if v := decodeCheck(t, &b); v.Message != equipo.CopyDBTimeout {
198 t.Fatal(v)
199 }
200 if checkDB(context.Background(), rejectDBOutput{}, path) == 0 {
201 t.Fatal("output error ignored")
202 }
203}
204
205type rejectDBOutput struct{}
206
207func (rejectDBOutput) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
208