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
|
package main
import (
"bufio"
"errors"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// sqlite3Bin resolves the sqlite3 CLI the same way the code under test does.
func sqlite3Bin() string {
if b := os.Getenv("SQLITE3"); b != "" {
return b
}
return "sqlite3"
}
// openHeldWALDB creates a cookie jar at path, fills it with the given cookies,
// and returns with the data sitting in an *uncheckpointed* -wal file.
//
// Getting a WAL to persist takes some care: sqlite3 checkpoints and deletes the
// -wal when the last connection closes cleanly, which would make the test pass
// against buggy code that ignores the -wal. So we keep a connection open for
// the duration of the test (via a live sqlite3 subprocess reading from a pipe),
// which is also what Firefox actually does. The returned function closes it.
func openHeldWALDB(t *testing.T, path string, cookies map[string]string) func() {
t.Helper()
cmd := exec.Command(sqlite3Bin(), path)
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatalf("stdin pipe: %v", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
t.Fatalf("stdout pipe: %v", err)
}
if err := cmd.Start(); err != nil {
t.Fatalf("starting sqlite3: %v", err)
}
var script strings.Builder
script.WriteString("PRAGMA journal_mode=WAL;\n")
// Never checkpoint on our own, so everything written below stays in the
// -wal and is invisible to a reader that only looks at the main file.
script.WriteString("PRAGMA wal_autocheckpoint=0;\n")
script.WriteString(`CREATE TABLE moz_cookies (
id INTEGER PRIMARY KEY, name TEXT, value TEXT, host TEXT);` + "\n")
for name, value := range cookies {
script.WriteString("INSERT INTO moz_cookies (name, value, host) VALUES ('" +
name + "', '" + value + "', '.claude.ai');\n")
}
// Echo a sentinel so we can wait for the writes to have landed rather than
// sleeping and hoping.
script.WriteString("SELECT 'READY';\n")
if _, err := io.WriteString(stdin, script.String()); err != nil {
t.Fatalf("writing script: %v", err)
}
scanner := bufio.NewScanner(stdout)
ready := false
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) == "READY" {
ready = true
break
}
}
if !ready {
t.Fatalf("sqlite3 setup did not reach READY")
}
return func() {
stdin.Close()
_ = cmd.Wait()
}
}
// TestReadCookiesSeesUncheckpointedWAL is the regression test for the bug this
// tool shipped with: it copied only cookies.sqlite and ignored cookies.sqlite-wal,
// so cookies written by Firefox but not yet checkpointed were invisible. Since
// a freshly minted sessionKey is exactly such a write, the tool would keep
// reporting "not logged in" after a successful login, and the user's fix (log
// in again) appeared to do nothing.
func TestReadCookiesSeesUncheckpointedWAL(t *testing.T) {
profileDir := t.TempDir()
db := filepath.Join(profileDir, "cookies.sqlite")
want := map[string]string{
"sessionKey": "sk-test-12345",
"cf_clearance": "cf-test-67890",
"lastActiveOrg": "org-test-abcde",
}
closeDB := openHeldWALDB(t, db, want)
defer closeDB()
// Guard the guard: if there is no -wal, or the main file already contains
// the rows, the test would pass vacuously against the old buggy code.
if _, err := os.Stat(db + "-wal"); err != nil {
t.Fatalf("expected an uncheckpointed -wal to exist: %v", err)
}
mainOnly := queryMainFileOnly(t, db)
if strings.Contains(mainOnly, "sessionKey") {
t.Fatalf("test setup is not exercising the bug: the main database file "+
"already contains the cookies, got %q", mainOnly)
}
got, err := readCookiesFromDB(db, t.TempDir(), "testprofile")
if err != nil {
t.Fatalf("readCookiesFromDB: %v", err)
}
for name, value := range want {
if got[name] != value {
t.Errorf("cookie %q = %q, want %q", name, got[name], value)
}
}
}
// queryMainFileOnly reads the database while deliberately ignoring the -wal
// (immutable=1), i.e. exactly what the old implementation effectively did.
func queryMainFileOnly(t *testing.T, db string) string {
t.Helper()
out, err := exec.Command(sqlite3Bin(),
"file:"+db+"?immutable=1", cookieQuery).Output()
if err != nil {
// A brand-new WAL-mode database may have no readable main file yet;
// that also means the cookies are not in it, which is what we assert.
return ""
}
return string(out)
}
// TestReadCookiesFromDBIgnoresOtherHosts checks the query filters by host, so a
// sessionKey belonging to some other site can never be sent to claude.ai.
func TestReadCookiesFromDBIgnoresOtherHosts(t *testing.T) {
profileDir := t.TempDir()
db := filepath.Join(profileDir, "cookies.sqlite")
closeDB := openHeldWALDB(t, db, map[string]string{"sessionKey": "mine"})
defer closeDB()
insert := exec.Command(sqlite3Bin(), db,
`INSERT INTO moz_cookies (name, value, host) VALUES ('sessionKey','theirs','.example.com');`)
if out, err := insert.CombinedOutput(); err != nil {
t.Fatalf("inserting foreign cookie: %v: %s", err, out)
}
got, err := readCookiesFromDB(db, t.TempDir(), "testprofile")
if err != nil {
t.Fatalf("readCookiesFromDB: %v", err)
}
if got["sessionKey"] != "mine" {
t.Errorf("sessionKey = %q, want %q", got["sessionKey"], "mine")
}
}
// TestReadCookiesFromDBMissingFile checks that an unreadable profile surfaces
// an error (so the caller skips it) instead of silently yielding no cookies,
// which would be indistinguishable from "logged out".
func TestReadCookiesFromDBMissingFile(t *testing.T) {
_, err := readCookiesFromDB(
filepath.Join(t.TempDir(), "does-not-exist.sqlite"), t.TempDir(), "gone")
if err == nil {
t.Fatal("expected an error for a missing cookie database, got nil")
}
}
// TestHintForDistinguishesLoginFromRefresh pins the distinction that motivated
// splitting the error taxonomy: being logged out and having a stale session
// need different advice, and conflating them told the user to reload a page
// when they actually had to log in.
func TestHintForDistinguishesLoginFromRefresh(t *testing.T) {
if got := hintFor(errNotLoggedIn); got != loginHint {
t.Errorf("hintFor(errNotLoggedIn) = %q, want the login hint", got)
}
if got := hintFor(errStaleCredentials); got != refreshHint {
t.Errorf("hintFor(errStaleCredentials) = %q, want the refresh hint", got)
}
// The hints must actually differ, otherwise the split is cosmetic.
if loginHint == refreshHint {
t.Error("loginHint and refreshHint are identical")
}
}
// TestParseCookieRows covers the tab-separated parsing, including values that
// contain characters the format could plausibly trip over.
func TestParseCookieRows(t *testing.T) {
// cf_clearance values contain '.', '-' and '_'; none may be truncated.
in := "sessionKey\tsk-ant-abc._-123\ncf_clearance\tv1.x-y_z\n\n"
got := parseCookieRows(in)
if got["sessionKey"] != "sk-ant-abc._-123" {
t.Errorf("sessionKey = %q", got["sessionKey"])
}
if got["cf_clearance"] != "v1.x-y_z" {
t.Errorf("cf_clearance = %q", got["cf_clearance"])
}
if len(got) != 2 {
t.Errorf("got %d cookies, want 2 (blank lines must be skipped)", len(got))
}
}
// TestParseCookieRowsEmpty checks the logged-out case parses to no cookies
// rather than a bogus entry.
func TestParseCookieRowsEmpty(t *testing.T) {
if got := parseCookieRows(""); len(got) != 0 {
t.Errorf("parseCookieRows(%q) = %v, want empty", "", got)
}
if got := parseCookieRows("\n \n"); len(got) != 0 {
t.Errorf("parseCookieRows(whitespace) = %v, want empty", got)
}
}
// serveCookiesOnce runs the extractor the way claude-usage-cookies@.service
// does — one connection, handed over as stdin/stdout — against a fake HOME
// whose only Firefox profile has the given cookies, and returns the socket
// path to dial.
func serveCookiesOnce(t *testing.T, cookies map[string]string) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
if cookies != nil {
profile := filepath.Join(home, ".mozilla", "firefox", "abcd.default")
if err := os.MkdirAll(profile, 0o700); err != nil {
t.Fatal(err)
}
t.Cleanup(openHeldWALDB(t, filepath.Join(profile, "cookies.sqlite"), cookies))
}
sock := filepath.Join(t.TempDir(), "cookies.sock")
l, err := net.Listen("unix", sock)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
conn, err := l.Accept()
if err != nil {
return
}
defer conn.Close()
if err := runCookiesServer(conn, conn); err != nil {
t.Errorf("runCookiesServer: %v", err)
}
}()
return sock
}
// TestGetCookiesRoundTrip checks the whole hand-over between the two halves:
// what the extractor reads out of the jar is what the fetcher receives.
func TestGetCookiesRoundTrip(t *testing.T) {
sock := serveCookiesOnce(t, map[string]string{
"sessionKey": "sk-test-12345",
"cf_clearance": "cf-test-67890",
"lastActiveOrg": "org-test-abcde",
})
got, err := getCookies(sock)
if err != nil {
t.Fatalf("getCookies: %v", err)
}
want := []candidate{{
Profile: "abcd.default",
SessionKey: "sk-test-12345",
CfClearance: "cf-test-67890",
LastActiveOrg: "org-test-abcde",
}}
if len(got) != 1 || got[0] != want[0] {
t.Errorf("getCookies = %+v, want %+v", got, want)
}
}
// TestGetCookiesNotLoggedIn checks that "no sessionKey" survives the trip as
// errNotLoggedIn, so the varlink service still tells the user to log in rather
// than to reload.
func TestGetCookiesNotLoggedIn(t *testing.T) {
sock := serveCookiesOnce(t, nil)
_, err := getCookies(sock)
if !errors.Is(err, errNotLoggedIn) {
t.Fatalf("getCookies error = %v, want errNotLoggedIn", err)
}
if hintFor(err) != loginHint {
t.Errorf("hint = %q, want the login hint", hintFor(err))
}
}
// TestGetCookiesNoExtractor checks that a missing extractor socket is not
// mistaken for being logged out: the fix is to start a unit, and the error
// must say which.
func TestGetCookiesNoExtractor(t *testing.T) {
_, err := getCookies(filepath.Join(t.TempDir(), "absent.sock"))
if err == nil {
t.Fatal("expected an error")
}
if errors.Is(err, errNotLoggedIn) {
t.Errorf("missing socket reported as not logged in: %v", err)
}
if !strings.Contains(err.Error(), "claude-usage-cookies.socket") {
t.Errorf("error does not name the socket unit to start: %v", err)
}
}
// TestSnapshotRetriesAreBounded guards against the retry loop hanging: a
// permanently failing profile must give up promptly rather than block the
// refresh loop.
func TestSnapshotRetriesAreBounded(t *testing.T) {
start := time.Now()
_, err := readCookiesFromDB(
filepath.Join(t.TempDir(), "nope.sqlite"), t.TempDir(), "nope")
if err == nil {
t.Fatal("expected an error")
}
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Errorf("retries took %s, expected to give up quickly", elapsed)
}
}
|