-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.test.ts
More file actions
1047 lines (967 loc) · 40.9 KB
/
Copy pathauth.test.ts
File metadata and controls
1047 lines (967 loc) · 40.9 KB
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { createMockClient, mockResponse, createTestProgram, runCommand } from "./test-helpers.js";
import type { MockClient } from "./test-helpers.js";
vi.mock("../src/helpers.js", () => ({
createClient: vi.fn(),
getFormat: vi.fn(),
outputResponse: vi.fn(),
withErrorHandler: (fn: (...args: unknown[]) => unknown) => fn,
resolveOptions: vi.fn(),
}));
vi.mock("../src/input.js", () => ({
parseJsonInput: vi.fn(),
}));
vi.mock("../src/output.js", () => ({
printSuccess: vi.fn(),
printError: vi.fn(),
printInfo: vi.fn(),
printWarning: vi.fn(),
printOutput: vi.fn(),
printCount: vi.fn(),
}));
vi.mock("../src/commands/help.js", () => ({
addExamples: vi.fn(),
addNotes: vi.fn(),
}));
vi.mock("../src/config.js", () => ({
loadConfig: vi.fn(() => ({})),
saveConfig: vi.fn(),
getCurrentProfile: vi.fn(() => "default"),
validateUrl: vi.fn((url: string) => url.replace(/\/+$/, "") + "/"),
}));
vi.mock("../src/prompt.js", () => ({
isInteractive: vi.fn(),
promptEmail: vi.fn(),
promptPassword: vi.fn(),
promptTenantSelection: vi.fn(),
}));
vi.mock("../src/token.js", () => ({
getTokenStatus: vi.fn(),
formatDuration: vi.fn(),
}));
vi.mock("../src/oauth.js", () => ({
clientCredentialsGrant: vi.fn(),
}));
import { createClient, getFormat, outputResponse, resolveOptions } from "../src/helpers.js";
import { printSuccess, printError, printInfo, printWarning } from "../src/output.js";
import { loadConfig, saveConfig, getCurrentProfile, validateUrl } from "../src/config.js";
import { isInteractive, promptEmail, promptPassword, promptTenantSelection } from "../src/prompt.js";
import { getTokenStatus, formatDuration } from "../src/token.js";
import { clientCredentialsGrant } from "../src/oauth.js";
import { registerAuthCommands } from "../src/commands/auth.js";
describe("auth commands", () => {
let client: MockClient;
let exitSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.clearAllMocks();
client = createMockClient();
vi.mocked(createClient).mockReturnValue(client as never);
vi.mocked(getFormat).mockReturnValue("json");
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "test-token",
format: "json",
} as never);
vi.mocked(loadConfig).mockReturnValue({});
exitSpy = vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit");
});
delete process.env.GDB_OAUTH_CLIENT_ID;
delete process.env.GDB_OAUTH_CLIENT_SECRET;
});
afterEach(() => {
exitSpy.mockRestore();
delete process.env.GDB_OAUTH_CLIENT_ID;
delete process.env.GDB_OAUTH_CLIENT_SECRET;
});
function makeProgram() {
return createTestProgram((prog) => registerAuthCommands(prog));
}
describe("auth login --client-credentials", () => {
it("performs OAuth client credentials flow with --client-id and --client-secret", async () => {
vi.mocked(clientCredentialsGrant).mockResolvedValue({
access_token: "oauth-token-123",
token_type: "Bearer",
expires_in: 3600,
});
const program = makeProgram();
await runCommand(program, [
"auth", "login",
"--client-credentials",
"--client-id", "myid",
"--client-secret", "mysecret",
]);
expect(clientCredentialsGrant).toHaveBeenCalledWith({
baseUrl: "http://localhost:3000",
clientId: "myid",
clientSecret: "mysecret",
scope: undefined,
});
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "oauth-token-123" }),
"default",
);
expect(printSuccess).toHaveBeenCalledWith(expect.stringContaining("Login successful"));
});
it("passes scope when provided", async () => {
vi.mocked(clientCredentialsGrant).mockResolvedValue({
access_token: "oauth-token",
token_type: "Bearer",
expires_in: 3600,
});
const program = makeProgram();
await runCommand(program, [
"auth", "login",
"--client-credentials",
"--client-id", "myid",
"--client-secret", "mysecret",
"--scope", "read write",
]);
expect(clientCredentialsGrant).toHaveBeenCalledWith(
expect.objectContaining({ scope: "read write" }),
);
});
it("prints error and exits when clientId/secret are missing", async () => {
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login", "--client-credentials"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("Client ID and secret"));
expect(exitSpy).toHaveBeenCalledWith(1);
});
it("falls back to env vars for clientId/secret", async () => {
process.env.GDB_OAUTH_CLIENT_ID = "env-id";
process.env.GDB_OAUTH_CLIENT_SECRET = "env-secret";
vi.mocked(clientCredentialsGrant).mockResolvedValue({
access_token: "env-token",
token_type: "Bearer",
expires_in: 3600,
});
const program = makeProgram();
await runCommand(program, ["auth", "login", "--client-credentials"]);
expect(clientCredentialsGrant).toHaveBeenCalledWith(
expect.objectContaining({ clientId: "env-id", clientSecret: "env-secret" }),
);
});
it("prints error and exits when URL is not configured", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: undefined,
profile: "default",
} as never);
const program = makeProgram();
await expect(
runCommand(program, [
"auth", "login",
"--client-credentials",
"--client-id", "myid",
"--client-secret", "mysecret",
]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("No URL configured"));
});
});
describe("auth login (email/password)", () => {
it("prompts for email and password interactively", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("prompt@example.com");
vi.mocked(promptPassword).mockResolvedValue("promptpass");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "interactive-token", refreshToken: "ref-xyz" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(promptEmail).toHaveBeenCalled();
expect(promptPassword).toHaveBeenCalled();
expect(client.rawRequest).toHaveBeenCalledWith("POST", "/auth/login", {
body: { email: "prompt@example.com", password: "promptpass" },
skipTenantHeader: true,
});
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "interactive-token", refreshToken: "ref-xyz" }),
"default",
);
expect(printSuccess).toHaveBeenCalledWith(expect.stringContaining("Login successful"));
});
it("prints error and exits when URL is not configured (without prompting)", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: undefined,
profile: "default",
} as never);
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("No URL configured"));
expect(exitSpy).toHaveBeenCalledWith(1);
// Must NOT prompt for credentials
expect(promptEmail).not.toHaveBeenCalled();
expect(promptPassword).not.toHaveBeenCalled();
});
it("prints error and exits when URL is invalid (without prompting)", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: "not-a-url",
profile: "default",
} as never);
vi.mocked(validateUrl).mockImplementationOnce(() => {
throw new Error('Invalid URL: "not-a-url". URL must start with http:// or https://.');
});
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("Invalid URL"));
expect(exitSpy).toHaveBeenCalledWith(1);
expect(promptEmail).not.toHaveBeenCalled();
expect(promptPassword).not.toHaveBeenCalled();
});
it("prints error and exits when non-interactive", async () => {
vi.mocked(isInteractive).mockReturnValue(false);
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(
expect.stringContaining("Interactive terminal required"),
);
expect(exitSpy).toHaveBeenCalledWith(1);
});
it("includes tenantId in the request body when --tenant-id is provided", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tenant-token" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login", "--tenant-id", "my-tenant"]);
expect(client.rawRequest).toHaveBeenCalledWith("POST", "/auth/login", {
body: { email: "user@example.com", password: "pass123", tenantId: "my-tenant" },
skipTenantHeader: true,
});
});
it("sends skipTenantHeader to prevent NGSILD-Tenant on login", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(client.rawRequest).toHaveBeenCalledWith("POST", "/auth/login", expect.objectContaining({
skipTenantHeader: true,
}));
});
it("prints error and exits when no token in response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(mockResponse({ message: "ok" }));
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith("No token received from server.");
});
it("saves refreshToken when present in response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", refreshToken: "ref" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok", refreshToken: "ref" }),
"default",
);
});
it("deletes refreshToken when not present in response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
const configObj = { refreshToken: "old-refresh" } as Record<string, unknown>;
vi.mocked(loadConfig).mockReturnValue(configObj as never);
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(configObj.refreshToken).toBeUndefined();
expect(saveConfig).toHaveBeenCalled();
});
it("saves tenantId as service when present in login response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "ed945710-fb96-4d17-811b-425abcb9b70e" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok", service: "ed945710-fb96-4d17-811b-425abcb9b70e" }),
"default",
);
});
it("does not set service when tenantId is absent from login response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
const savedConfig = vi.mocked(saveConfig).mock.calls[0][0] as Record<string, unknown>;
expect(savedConfig).not.toHaveProperty("service");
});
it("removes existing service when tenantId is absent from login response", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
vi.mocked(loadConfig).mockReturnValue({ service: "old-tenant" } as never);
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
const savedConfig = vi.mocked(saveConfig).mock.calls[0][0] as Record<string, unknown>;
expect(savedConfig).not.toHaveProperty("service");
});
it("reads token from data.token when accessToken is not present", async () => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
client.rawRequest.mockResolvedValue(
mockResponse({ token: "legacy-token" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "legacy-token" }),
"default",
);
});
});
describe("auth login (multi-tenant)", () => {
beforeEach(() => {
vi.mocked(isInteractive).mockReturnValue(true);
vi.mocked(promptEmail).mockResolvedValue("user@example.com");
vi.mocked(promptPassword).mockResolvedValue("pass123");
});
it("shows tenant selection when availableTenants has multiple entries", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
vi.mocked(promptTenantSelection).mockResolvedValue(undefined);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(promptTenantSelection).toHaveBeenCalledWith(tenants, "city_a");
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok", service: "city_a" }),
"default",
);
});
it("re-logins with selected tenant when user picks a different one", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-a", tenantId: "city_a", availableTenants: tenants }),
)
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-b", refreshToken: "ref-b", tenantId: "city_b" }),
);
vi.mocked(promptTenantSelection).mockResolvedValue("city_b");
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(client.rawRequest).toHaveBeenCalledTimes(2);
expect(client.rawRequest).toHaveBeenLastCalledWith("POST", "/auth/login", {
body: { email: "user@example.com", password: "pass123", tenantId: "city_b" },
skipTenantHeader: true,
});
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok-b", refreshToken: "ref-b", service: "city_b" }),
"default",
);
});
it("skips tenant selection when --tenant-id is explicitly provided", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login", "--tenant-id", "city_a"]);
expect(promptTenantSelection).not.toHaveBeenCalled();
});
it("skips tenant selection when only one tenant is available", async () => {
const tenants = [{ tenantId: "city_a", role: "tenant_admin" }];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(promptTenantSelection).not.toHaveBeenCalled();
});
it("prints error and exits when re-login returns no token", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-a", tenantId: "city_a", availableTenants: tenants }),
)
.mockResolvedValueOnce(
mockResponse({ message: "ok" }), // no token
);
vi.mocked(promptTenantSelection).mockResolvedValue("city_b");
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith("Re-login failed: no token received for selected tenant.");
expect(exitSpy).toHaveBeenCalledWith(1);
});
it("keeps original token when user selects current tenant", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok-a", tenantId: "city_a", availableTenants: tenants }),
);
vi.mocked(promptTenantSelection).mockResolvedValue("city_a");
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
// Should not re-login since selectedTenantId === currentTenantId
expect(client.rawRequest).toHaveBeenCalledTimes(1);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok-a", service: "city_a" }),
"default",
);
});
it("saves tenantId and availableTenants to config", async () => {
const tenants = [
{ tenantId: "city_a", name: "Smart City A", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
vi.mocked(promptTenantSelection).mockResolvedValue(undefined);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "city_a",
availableTenants: [
{ tenantId: "city_a", name: "Smart City A", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
],
}),
"default",
);
});
it("resolves tenant by name via --service flag", async () => {
const tenants = [
{ tenantId: "tid-aaa", name: "demo_smartcity", role: "tenant_admin" },
{ tenantId: "tid-bbb", name: "demo_bousai", role: "user" },
];
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "test-token",
format: "json",
service: "demo_bousai",
} as never);
client.rawRequest
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-a", tenantId: "tid-aaa", availableTenants: tenants }),
)
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-b", refreshToken: "ref-b", tenantId: "tid-bbb" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
// Should NOT prompt — resolved by --service name
expect(promptTenantSelection).not.toHaveBeenCalled();
// Should re-login with resolved tenantId
expect(client.rawRequest).toHaveBeenLastCalledWith("POST", "/auth/login", {
body: { email: "user@example.com", password: "pass123", tenantId: "tid-bbb" },
skipTenantHeader: true,
});
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok-b", service: "tid-bbb", tenantId: "tid-bbb" }),
"default",
);
});
it("resolves tenant by tenantId via --service flag", async () => {
const tenants = [
{ tenantId: "city_a", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "test-token",
format: "json",
service: "city_b",
} as never);
client.rawRequest
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-a", tenantId: "city_a", availableTenants: tenants }),
)
.mockResolvedValueOnce(
mockResponse({ accessToken: "tok-b", tenantId: "city_b" }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(promptTenantSelection).not.toHaveBeenCalled();
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "tok-b", service: "city_b" }),
"default",
);
});
it("prints error when --service tenant name not found", async () => {
const tenants = [
{ tenantId: "city_a", name: "Smart City A", role: "tenant_admin" },
{ tenantId: "city_b", role: "user" },
];
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "test-token",
format: "json",
service: "nonexistent",
} as never);
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
const program = makeProgram();
await expect(
runCommand(program, ["auth", "login"]),
).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(
expect.stringContaining('Tenant "nonexistent" not found'),
);
});
it("includes tenant label in success message", async () => {
const tenants = [
{ tenantId: "city_a", name: "Smart City A", role: "tenant_admin" },
];
client.rawRequest.mockResolvedValue(
mockResponse({ accessToken: "tok", tenantId: "city_a", availableTenants: tenants }),
);
const program = makeProgram();
await runCommand(program, ["auth", "login"]);
expect(printSuccess).toHaveBeenCalledWith(
"Login successful (tenant: Smart City A). Token saved to config.",
);
});
});
describe("auth logout", () => {
it("notifies server and clears token from config", async () => {
vi.mocked(loadConfig).mockReturnValue({ token: "old-token" } as never);
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "old-token",
} as never);
client.rawRequest.mockResolvedValue(mockResponse(undefined, 204));
const program = makeProgram();
await runCommand(program, ["auth", "logout"]);
expect(client.rawRequest).toHaveBeenCalledWith("POST", "/auth/logout");
expect(saveConfig).toHaveBeenCalled();
expect(printSuccess).toHaveBeenCalledWith(expect.stringContaining("Logged out"));
});
it("ignores server error and still clears token", async () => {
vi.mocked(loadConfig).mockReturnValue({ token: "old-token" } as never);
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
token: "old-token",
} as never);
client.rawRequest.mockRejectedValue(new Error("Network error"));
const program = makeProgram();
await runCommand(program, ["auth", "logout"]);
expect(saveConfig).toHaveBeenCalled();
expect(printSuccess).toHaveBeenCalledWith(expect.stringContaining("Logged out"));
});
it("skips server call when no token or url", async () => {
vi.mocked(loadConfig).mockReturnValue({} as never);
vi.mocked(resolveOptions).mockReturnValue({
url: undefined,
profile: "default",
} as never);
const program = makeProgram();
await runCommand(program, ["auth", "logout"]);
expect(client.rawRequest).not.toHaveBeenCalled();
expect(saveConfig).toHaveBeenCalled();
expect(printSuccess).toHaveBeenCalledWith(expect.stringContaining("Logged out"));
});
});
describe("me command", () => {
it("prints info when not logged in (no token or apiKey)", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
} as never);
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printInfo).toHaveBeenCalledWith(expect.stringContaining("Not logged in"));
expect(client.rawRequest).not.toHaveBeenCalled();
});
it("fetches /me and outputs response when logged in", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({ token: "valid-token" } as never);
vi.mocked(getTokenStatus).mockReturnValue({
expiresAt: new Date("2025-12-31T00:00:00Z"),
isExpired: false,
isExpiringSoon: false,
remainingMs: 86400000,
} as never);
vi.mocked(formatDuration).mockReturnValue("1 day");
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(client.rawRequest).toHaveBeenCalledWith("GET", "/me");
expect(outputResponse).toHaveBeenCalled();
expect(printInfo).toHaveBeenCalledWith(expect.stringContaining("Token expires:"));
expect(printInfo).toHaveBeenCalledWith(expect.stringContaining("Profile:"));
});
it("suppresses human-readable logs for json format", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(getFormat).mockReturnValue("json");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(outputResponse).toHaveBeenCalled();
expect(getTokenStatus).not.toHaveBeenCalled();
});
it("shows expired token status", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({ token: "expired-token" } as never);
vi.mocked(getTokenStatus).mockReturnValue({
expiresAt: new Date("2020-01-01T00:00:00Z"),
isExpired: true,
isExpiringSoon: false,
remainingMs: 0,
} as never);
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printError).toHaveBeenCalledWith(expect.stringContaining("expired"));
});
it("shows expiring-soon token status", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({ token: "expiring-token" } as never);
vi.mocked(getTokenStatus).mockReturnValue({
expiresAt: new Date("2025-12-31T00:00:00Z"),
isExpired: false,
isExpiringSoon: true,
remainingMs: 300000,
} as never);
vi.mocked(formatDuration).mockReturnValue("5 minutes");
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printWarning).toHaveBeenCalledWith(expect.stringContaining("Token expires:"));
});
it("shows profile from resolvedOptions profile when available", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({} as never);
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "staging",
token: "tok",
} as never);
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printInfo).toHaveBeenCalledWith("Profile: staging");
});
it("falls back to getCurrentProfile when profile not in options", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({} as never);
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: undefined,
token: "tok",
} as never);
vi.mocked(getCurrentProfile).mockReturnValue("custom-profile");
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printInfo).toHaveBeenCalledWith("Profile: custom-profile");
});
it("handles token without expiresAt", async () => {
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
vi.mocked(loadConfig).mockReturnValue({ token: "no-exp-token" } as never);
vi.mocked(getTokenStatus).mockReturnValue({
expiresAt: undefined,
isExpired: false,
isExpiringSoon: false,
remainingMs: undefined,
} as never);
vi.mocked(getFormat).mockReturnValue("table");
const program = makeProgram();
await runCommand(program, ["me"]);
expect(printWarning).not.toHaveBeenCalled();
});
it("works with apiKey instead of token", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
apiKey: "my-api-key",
} as never);
vi.mocked(loadConfig).mockReturnValue({} as never);
vi.mocked(getFormat).mockReturnValue("table");
client.rawRequest.mockResolvedValue(mockResponse({ email: "user@example.com" }));
const program = makeProgram();
await runCommand(program, ["me"]);
expect(client.rawRequest).toHaveBeenCalledWith("GET", "/me");
});
});
describe("auth nonce", () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ nonce: "abc123", challenge: "deadbeef", difficulty: 4 }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
apiKey: "gdb_testkey",
} as never);
});
afterEach(() => {
fetchSpy.mockRestore();
});
it("requests nonce with API key in body and outputs response", async () => {
const program = makeProgram();
await runCommand(program, ["auth", "nonce"]);
expect(fetchSpy).toHaveBeenCalledWith(
expect.stringContaining("/auth/nonce"),
expect.objectContaining({
method: "POST",
body: JSON.stringify({ api_key: "gdb_testkey" }),
headers: expect.objectContaining({ "Origin": expect.any(String) }),
}),
);
expect(outputResponse).toHaveBeenCalled();
});
it("uses apiKey from resolvedOptions when --api-key flag is not provided", async () => {
const program = makeProgram();
await runCommand(program, ["auth", "nonce"]);
expect(fetchSpy).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
body: JSON.stringify({ api_key: "gdb_testkey" }),
}),
);
});
it("errors when no API key is available", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
} as never);
const program = makeProgram();
await expect(runCommand(program, ["auth", "nonce"])).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("API key is required"));
});
it("errors when no URL is configured", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: undefined,
profile: "default",
apiKey: "gdb_key",
} as never);
const program = makeProgram();
await expect(runCommand(program, ["auth", "nonce"])).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("No URL configured"));
});
it("throws on non-ok response with body", async () => {
fetchSpy.mockResolvedValue(
new Response("Bad Request", { status: 400 }),
);
const program = makeProgram();
await expect(runCommand(program, ["auth", "nonce"])).rejects.toThrow("Nonce request failed: Bad Request");
});
it("throws with HTTP status fallback when response body is empty", async () => {
fetchSpy.mockResolvedValue(
new Response("", { status: 403 }),
);
const program = makeProgram();
await expect(runCommand(program, ["auth", "nonce"])).rejects.toThrow("Nonce request failed: HTTP 403");
});
});
describe("auth token-exchange", () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
apiKey: "gdb_testkey",
} as never);
});
afterEach(() => {
if (fetchSpy) fetchSpy.mockRestore();
});
it("performs full nonce → PoW → token exchange flow", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const urlStr = String(url);
if (urlStr.includes("/auth/nonce")) {
return new Response(
JSON.stringify({ nonce: "test-nonce", challenge: "abcd1234", difficulty: 1 }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
if (urlStr.includes("/oauth/token")) {
return new Response(
JSON.stringify({ access_token: "jwt-from-exchange", token_type: "Bearer", expires_in: 3600 }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
return new Response("Not Found", { status: 404 });
});
const program = makeProgram();
await runCommand(program, ["auth", "token-exchange", "--api-key", "gdb_mykey"]);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(printInfo).toHaveBeenCalledWith(expect.stringContaining("Solving PoW"));
expect(outputResponse).toHaveBeenCalled();
expect(printSuccess).toHaveBeenCalledWith("Token exchange successful.");
});
it("saves token to config with --save", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const urlStr = String(url);
if (urlStr.includes("/auth/nonce")) {
return new Response(
JSON.stringify({ nonce: "test-nonce", challenge: "abcd1234", difficulty: 1 }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
return new Response(
JSON.stringify({ access_token: "saved-jwt", token_type: "Bearer" }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
});
const program = makeProgram();
await runCommand(program, ["auth", "token-exchange", "--save"]);
expect(saveConfig).toHaveBeenCalledWith(
expect.objectContaining({ token: "saved-jwt" }),
"default",
);
expect(printSuccess).toHaveBeenCalledWith("Token exchange successful. Token saved to config.");
});
it("errors when no API key is available", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: "http://localhost:3000",
profile: "default",
} as never);
const program = makeProgram();
await expect(runCommand(program, ["auth", "token-exchange"])).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("API key is required"));
});
it("errors when no URL is configured", async () => {
vi.mocked(resolveOptions).mockReturnValue({
url: undefined,
profile: "default",
apiKey: "gdb_key",
} as never);
const program = makeProgram();
await expect(runCommand(program, ["auth", "token-exchange"])).rejects.toThrow("process.exit");
expect(printError).toHaveBeenCalledWith(expect.stringContaining("No URL configured"));
});
it("throws when nonce request fails with body", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("Server Error", { status: 500 }),
);
const program = makeProgram();
await expect(runCommand(program, ["auth", "token-exchange"])).rejects.toThrow("Nonce request failed: Server Error");
});
it("throws when nonce request fails with empty body", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("", { status: 500 }),
);
const program = makeProgram();
await expect(runCommand(program, ["auth", "token-exchange"])).rejects.toThrow("Nonce request failed: HTTP 500");
});
it("throws when token exchange request fails with body", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const urlStr = String(url);
if (urlStr.includes("/auth/nonce")) {
return new Response(
JSON.stringify({ nonce: "test-nonce", challenge: "abcd1234", difficulty: 1 }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
return new Response("Invalid PoW", { status: 400 });
});
const program = makeProgram();
await expect(runCommand(program, ["auth", "token-exchange"])).rejects.toThrow("Token exchange failed: Invalid PoW");
});
it("throws when token exchange request fails with empty body", async () => {
fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const urlStr = String(url);
if (urlStr.includes("/auth/nonce")) {
return new Response(
JSON.stringify({ nonce: "test-nonce", challenge: "abcd1234", difficulty: 1 }),
{ status: 200, headers: { "Content-Type": "application/json" } },