forked from CodesWhat/drydock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_test_upstream.ts
More file actions
2967 lines (2633 loc) · 101 KB
/
Copy pathdocker_test_upstream.ts
File metadata and controls
2967 lines (2633 loc) · 101 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 type { Mocked } from 'vitest';
import * as event from '../../../event/index.js';
import { fullName } from '../../../model/container.js';
import * as registry from '../../../registry/index.js';
import * as storeContainer from '../../../store/container.js';
import { mockConstructor } from '../../../test/mock-constructor.js';
import { _resetRegistryWebhookFreshStateForTests } from '../../registry-webhook-fresh.js';
import {
filterRecreatedContainerAliases as testable_filterRecreatedContainerAliases,
getLabel as testable_getLabel,
pruneOldContainers as testable_pruneOldContainers,
} from './container-init.js';
import Docker, { testable_normalizeConfigNumberValue } from './Docker.js';
import {
getContainerDisplayName as testable_getContainerDisplayName,
getContainerName as testable_getContainerName,
getImageForRegistryLookup as testable_getImageForRegistryLookup,
getImageReferenceCandidatesFromPattern as testable_getImageReferenceCandidatesFromPattern,
getImgsetSpecificity as testable_getImgsetSpecificity,
getInspectValueByPath as testable_getInspectValueByPath,
getOldContainers as testable_getOldContainers,
shouldUpdateDisplayNameFromContainerName as testable_shouldUpdateDisplayNameFromContainerName,
} from './docker-helpers.js';
import { normalizeContainer as testable_normalizeContainer } from './image-comparison.js';
import {
filterBySegmentCount as testable_filterBySegmentCount,
getCurrentPrefix as testable_getCurrentPrefix,
getFirstDigitIndex as testable_getFirstDigitIndex,
} from './tag-candidates.js';
const mockDdEnvVars = vi.hoisted(() => ({}) as Record<string, string | undefined>);
const mockDetectSourceRepoFromImageMetadata = vi.hoisted(() => vi.fn());
const mockResolveSourceRepoForContainer = vi.hoisted(() => vi.fn());
const mockGetFullReleaseNotesForContainer = vi.hoisted(() => vi.fn());
const mockToContainerReleaseNotes = vi.hoisted(() => vi.fn((notes) => notes));
vi.mock('../../../configuration/index.js', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../configuration/index.js')>()),
ddEnvVars: mockDdEnvVars,
}));
vi.mock('../../../release-notes/index.js', () => ({
detectSourceRepoFromImageMetadata: (...args: unknown[]) =>
mockDetectSourceRepoFromImageMetadata(...args),
resolveSourceRepoForContainer: (...args: unknown[]) => mockResolveSourceRepoForContainer(...args),
getFullReleaseNotesForContainer: (...args: unknown[]) =>
mockGetFullReleaseNotesForContainer(...args),
toContainerReleaseNotes: (...args: unknown[]) => mockToContainerReleaseNotes(...args),
}));
// Mock all dependencies
vi.mock('dockerode');
vi.mock('node-cron');
vi.mock('just-debounce');
vi.mock('../../../event');
vi.mock('../../../store/container');
vi.mock('../../../registry/index.js');
vi.mock('../../../model/container');
vi.mock('../../../tag');
vi.mock('../../../prometheus/watcher');
vi.mock('parse-docker-image-name');
vi.mock('node:fs');
vi.mock('axios');
vi.mock('./maintenance.js', () => ({
isInMaintenanceWindow: vi.fn(() => true),
getNextMaintenanceWindow: vi.fn(() => undefined),
}));
vi.mock('./socket-version-probe.js', () => ({
probeSocketApiVersion: vi.fn().mockResolvedValue(undefined),
}));
import mockFs from 'node:fs';
import axios from 'axios';
import mockDockerode from 'dockerode';
import mockDebounce from 'just-debounce';
import mockCron from 'node-cron';
import mockParse from 'parse-docker-image-name';
import * as mockPrometheus from '../../../prometheus/watcher.js';
import * as mockTag from '../../../tag/index.js';
import * as maintenance from './maintenance.js';
import {
applyRemoteOidcTokenPayload,
getOidcGrantType,
handleTokenErrorResponse,
initializeRemoteOidcStateFromConfiguration,
isRemoteOidcTokenRefreshRequired,
OIDC_DEVICE_URL_PATHS,
OIDC_GRANT_TYPE_PATHS,
performDeviceCodeFlow,
pollDeviceCodeToken,
refreshRemoteOidcAccessToken,
} from './oidc.js';
const mockAxios = axios as Mocked<typeof axios>;
// --- Shared factory functions to reduce test duplication ---
/** Base OIDC auth configuration for remote Docker API tests. */
function createOidcConfig(oidcOverrides = {}, configOverrides = {}) {
return {
host: 'docker-api.example.com',
port: 443,
protocol: 'https',
auth: {
type: 'oidc',
oidc: {
tokenurl: 'https://idp.example.com/oauth/token',
...oidcOverrides,
},
},
...configOverrides,
};
}
/** Device flow OIDC config (adds deviceurl + clientid to base OIDC). */
function createDeviceFlowConfig(oidcOverrides = {}, configOverrides = {}) {
return createOidcConfig(
{
deviceurl: 'https://idp.example.com/oauth/device/code',
clientid: 'dd-device-client',
...oidcOverrides,
},
configOverrides,
);
}
/** Standard device authorization response from the IdP. */
function createDeviceCodeResponse(overrides = {}) {
return {
device_code: 'device-code-123',
user_code: 'ABCD-1234',
verification_uri: 'https://idp.example.com/device',
interval: 1,
expires_in: 300,
...overrides,
};
}
/** Token response from the IdP. */
function createTokenResponse(overrides = {}) {
return {
access_token: 'test-token',
expires_in: 3600,
...overrides,
};
}
/** Creates a mock log object with commonly needed methods. */
function createMockLog(methods = ['info', 'warn', 'debug', 'error']) {
const log = {};
for (const m of methods) {
log[m] = vi.fn();
}
return log;
}
/** Creates a mock log with a child() that returns another mock log. */
function createMockLogWithChild(childMethods = ['info', 'warn', 'debug', 'error']) {
const childLog = createMockLog(childMethods);
return {
child: vi.fn().mockReturnValue(childLog),
...createMockLog(['info', 'warn', 'debug', 'error']),
_child: childLog,
};
}
function createDockerOidcStateAdapter(docker) {
return {
get accessToken() {
return docker.remoteOidcAccessToken;
},
set accessToken(value) {
docker.remoteOidcAccessToken = value;
},
get refreshToken() {
return docker.remoteOidcRefreshToken;
},
set refreshToken(value) {
docker.remoteOidcRefreshToken = value;
},
get accessTokenExpiresAt() {
return docker.remoteOidcAccessTokenExpiresAt;
},
set accessTokenExpiresAt(value) {
docker.remoteOidcAccessTokenExpiresAt = value;
},
get deviceCodeCompleted() {
return docker.remoteOidcDeviceCodeCompleted;
},
set deviceCodeCompleted(value) {
docker.remoteOidcDeviceCodeCompleted = value;
},
};
}
function createDockerOidcContext(docker) {
return {
watcherName: docker.name,
log: docker.log,
state: createDockerOidcStateAdapter(docker),
getOidcAuthString: (paths) => docker.getOidcAuthString(paths),
getOidcAuthNumber: (paths) => docker.getOidcAuthNumber(paths),
normalizeNumber: testable_normalizeConfigNumberValue,
sleep: (ms) => docker.sleep(ms),
};
}
describe('Docker Watcher', () => {
let docker;
let mockDockerApi;
let mockSchedule;
let mockContainer;
let mockImage;
beforeEach(async () => {
vi.clearAllMocks();
_resetRegistryWebhookFreshStateForTests();
// Setup dockerode mock
mockDockerApi = {
listContainers: vi.fn(),
getContainer: vi.fn(),
getEvents: vi.fn(),
getImage: vi.fn(),
getService: vi.fn(),
modem: {
headers: {},
},
};
mockDockerode.mockImplementation(mockConstructor(mockDockerApi));
// Setup cron mock
mockSchedule = {
stop: vi.fn(),
};
mockCron.schedule.mockReturnValue(mockSchedule);
// Setup debounce mock
mockDebounce.mockImplementation((fn) => fn);
// Setup container mock
mockContainer = {
inspect: vi.fn(),
};
mockDockerApi.getContainer.mockReturnValue(mockContainer);
// Setup image mock
mockImage = {
inspect: vi.fn(),
};
mockDockerApi.getImage.mockReturnValue(mockImage);
// Setup store mock
storeContainer.getContainers.mockReturnValue([]);
storeContainer.getContainer.mockReturnValue(undefined);
storeContainer.insertContainer.mockImplementation((c) => c);
storeContainer.updateContainer.mockImplementation((c) => c);
storeContainer.deleteContainer.mockImplementation(() => {});
// Setup registry mock
registry.getState.mockReturnValue({ registry: {} });
// Setup event mock
event.emitWatcherStart.mockImplementation(() => {});
event.emitWatcherStop.mockImplementation(() => {});
event.emitContainerReport.mockImplementation(() => {});
event.emitContainerReports.mockImplementation(() => {});
// Setup tag mock
mockTag.parse.mockReturnValue({ major: 1, minor: 0, patch: 0 });
mockTag.isGreater.mockReturnValue(false);
mockTag.transform.mockImplementation((transform, tag) => tag);
// Setup prometheus mock
const mockGauge = { set: vi.fn() };
mockPrometheus.getWatchContainerGauge.mockReturnValue(mockGauge);
mockPrometheus.getMaintenanceSkipCounter.mockReturnValue({
labels: vi.fn().mockReturnValue({ inc: vi.fn() }),
});
mockPrometheus.getLoggerInitFailureCounter.mockReturnValue({
labels: vi.fn().mockReturnValue({ inc: vi.fn() }),
});
// Setup maintenance helpers
maintenance.isInMaintenanceWindow.mockReturnValue(true);
maintenance.getNextMaintenanceWindow.mockReturnValue(undefined);
// Setup parse mock
mockParse.mockReturnValue({
domain: 'docker.io',
path: 'library/nginx',
tag: '1.0.0',
});
mockAxios.post.mockResolvedValue({
data: {
access_token: 'oidc-token',
expires_in: 300,
},
} as any);
// Setup fullName mock
fullName.mockReturnValue('test_container');
docker = new Docker();
});
afterEach(async () => {
vi.useRealTimers();
if (docker) {
await docker.deregisterComponent();
}
});
describe('Configuration', () => {
test('should create instance', async () => {
expect(docker).toBeDefined();
expect(docker).toBeInstanceOf(Docker);
});
test('should have correct configuration schema', async () => {
const schema = docker.getConfigurationSchema();
expect(schema).toBeDefined();
});
test('should validate configuration', async () => {
const config = { socket: '/var/run/docker.sock' };
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should validate configuration with watchall option', async () => {
const config = { socket: '/var/run/docker.sock', watchall: true };
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should validate configuration with custom cron', async () => {
const config = {
socket: '/var/run/docker.sock',
cron: '*/5 * * * *',
};
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should validate configuration with imgset presets', async () => {
const config = {
socket: '/var/run/docker.sock',
imgset: {
homeassistant: {
image: 'ghcr.io/home-assistant/home-assistant',
tag: {
include: String.raw`^\d+\.\d+\.\d+$`,
},
display: {
icon: 'mdi-home-assistant',
},
link: {
template: 'https://example.com/changelog/${major}',
},
},
},
};
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should validate configuration with oidc remote auth', async () => {
const config = createOidcConfig(
{
clientid: 'dd-client',
clientsecret: 'super-secret',
scope: 'docker.read',
},
{ host: 'docker-proxy.example.com' },
);
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should validate configuration with insecure remote auth override', async () => {
const config = {
host: 'docker-proxy.example.com',
port: 443,
protocol: 'https',
auth: {
type: 'bearer',
bearer: 'test-token',
insecure: true,
},
};
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
});
describe('Recent event history helpers', () => {
test('should convert docker event timestamps from timeNano and time', () => {
const toEventTimestamp = (docker as any).toEventTimestamp.bind(docker);
expect(toEventTimestamp({ timeNano: 1_700_000_000_123_000_000 })).toBe(
new Date(1_700_000_000_123).toISOString(),
);
expect(toEventTimestamp({ time: 1_700_000_000_123 })).toBe(
new Date(1_700_000_000_123).toISOString(),
);
expect(toEventTimestamp({ time: 1_700 })).toBe(new Date(1_700_000).toISOString());
});
test('should record recent docker events with status and scope fallbacks', () => {
const recordRecentDockerEvent = (docker as any).recordRecentDockerEvent.bind(docker);
docker.recentDockerEvents = [];
recordRecentDockerEvent({
timeNano: 1_700_000_000_123_000_000,
Action: 'start',
Type: 'container',
id: 'event-1',
Actor: { ID: 'actor-1' },
});
recordRecentDockerEvent({
time: 1_700,
status: 'die',
scope: 'local',
id: 'event-2',
Actor: { ID: 'actor-2' },
});
expect(docker.recentDockerEvents).toHaveLength(2);
expect(docker.recentDockerEvents[0]).toMatchObject({
action: 'start',
type: 'container',
id: 'event-1',
actorId: 'actor-1',
});
expect(docker.recentDockerEvents[1]).toMatchObject({
action: 'die',
type: 'local',
id: 'event-2',
actorId: 'actor-2',
});
});
});
describe('Initialization', () => {
test('should initialize docker client with socket', async () => {
await docker.register('watcher', 'docker', 'test', {
socket: '/var/run/docker.sock',
});
expect(mockDockerode).toHaveBeenCalledWith({
socketPath: '/var/run/docker.sock',
});
});
test('should initialize with host configuration', async () => {
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 2376,
});
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 2376,
});
});
test('should initialize with SSL configuration', async () => {
mockFs.readFileSync.mockReturnValue('cert-content');
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 2376,
cafile: '/ca.pem',
certfile: '/cert.pem',
keyfile: '/key.pem',
});
expect(mockFs.readFileSync).toHaveBeenCalledTimes(3);
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 2376,
ca: 'cert-content',
cert: 'cert-content',
key: 'cert-content',
});
});
test('should initialize with HTTPS bearer auth configuration', async () => {
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 443,
protocol: 'https',
auth: {
type: 'bearer',
bearer: 'my-secret-token',
},
});
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 443,
protocol: 'https',
headers: {
Authorization: 'Bearer my-secret-token',
},
});
});
test('should initialize with HTTPS basic auth configuration', async () => {
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 443,
protocol: 'https',
auth: {
type: 'basic',
user: 'john',
password: 'doe',
},
});
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 443,
protocol: 'https',
headers: {
Authorization: 'Basic am9objpkb2U=',
},
});
});
test('should initialize with OIDC access token when provided', async () => {
await docker.register(
'watcher',
'docker',
'test',
createOidcConfig(
{
accesstoken: 'seed-access-token',
expiresin: 300,
},
{ host: 'localhost' },
),
);
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 443,
protocol: 'https',
headers: {
Authorization: 'Bearer seed-access-token',
},
});
});
test('should keep watcher registered but block remote sync when auth is configured without HTTPS', async () => {
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 2375,
protocol: 'http',
auth: {
type: 'bearer',
bearer: 'my-secret-token',
},
});
expect(docker.remoteAuthBlockedReason).toContain('HTTPS is required for remote auth');
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 2375,
protocol: 'http',
});
});
test('should allow insecure auth fallback when auth.insecure=true', async () => {
await docker.register('watcher', 'docker', 'test', {
host: 'localhost',
port: 2375,
protocol: 'http',
auth: {
type: 'bearer',
bearer: 'my-secret-token',
insecure: true,
},
});
expect(mockDockerode).toHaveBeenCalledWith({
host: 'localhost',
port: 2375,
protocol: 'http',
});
});
test('should schedule cron job on init', async () => {
await docker.register('watcher', 'docker', 'test', {
cron: '0 * * * *',
});
await docker.init();
expect(mockCron.schedule).toHaveBeenCalledWith('0 * * * *', expect.any(Function), {
maxRandomDelay: 60000,
});
});
test('should warn about deprecated watchdigest', async () => {
await docker.register('watcher', 'docker', 'test', {
watchdigest: true,
});
const mockLog = { warn: vi.fn(), info: vi.fn() };
docker.log = mockLog;
await docker.init();
expect(mockLog.warn).toHaveBeenCalledWith(expect.stringContaining('deprecated'));
});
test('should warn about deprecated watchatstart when env var is explicitly set', async () => {
mockDdEnvVars.DD_WATCHER_TEST_WATCHATSTART = 'true';
try {
await docker.register('watcher', 'docker', 'test', {
watchatstart: true,
});
const mockLog = { warn: vi.fn(), info: vi.fn() };
docker.log = mockLog;
await docker.init();
expect(mockLog.warn).toHaveBeenCalledWith(
expect.stringContaining(
'DD_WATCHER_TEST_WATCHATSTART environment variable is deprecated',
),
);
} finally {
delete mockDdEnvVars.DD_WATCHER_TEST_WATCHATSTART;
}
});
test('should not warn about watchatstart when env var is not explicitly set', async () => {
await docker.register('watcher', 'docker', 'test', {
watchatstart: true,
});
const mockLog = { warn: vi.fn(), info: vi.fn() };
docker.log = mockLog;
await docker.init();
expect(mockLog.warn).not.toHaveBeenCalledWith(
expect.stringContaining('WATCHATSTART environment variable is deprecated'),
);
});
test('should setup docker events listener', async () => {
await docker.register('watcher', 'docker', 'test', {
watchevents: true,
});
await docker.init();
expect(mockDebounce).toHaveBeenCalled();
});
test('should not setup events when disabled', async () => {
await docker.register('watcher', 'docker', 'test', {
watchevents: false,
});
await docker.init();
expect(mockDebounce).not.toHaveBeenCalled();
});
test('should keep watchatstart enabled when watcher state already exists in store', async () => {
storeContainer.getContainers.mockReturnValue([{ id: 'existing' }]);
await docker.register('watcher', 'docker', 'test', {
watchatstart: true,
watchevents: false,
});
await docker.init();
expect(docker.configuration.watchatstart).toBe(true);
expect(docker.watchCronTimeout).toBeDefined();
});
test('should keep watchatstart disabled when explicitly set to false', async () => {
storeContainer.getContainers.mockReturnValue([]);
await docker.register('watcher', 'docker', 'test', {
watchatstart: false,
});
await docker.init();
expect(docker.configuration.watchatstart).toBe(false);
});
test('should execute scheduled cron callback by delegating to watchFromCron', async () => {
storeContainer.getContainers.mockReturnValue([]);
await docker.register('watcher', 'docker', 'test', {
watchatstart: false,
});
docker.watchFromCron = vi.fn().mockResolvedValue([]);
await docker.init();
const scheduledCallback = mockCron.schedule.mock.calls[0][1];
await scheduledCallback();
expect(docker.watchFromCron).toHaveBeenCalledTimes(1);
});
});
describe('Deregistration', () => {
test('should stop cron and clear timeouts on deregister', async () => {
await docker.register('watcher', 'docker', 'test', {});
await docker.init();
await docker.deregisterComponent();
expect(mockSchedule.stop).toHaveBeenCalled();
});
test('should stop watchCron when it is set explicitly', async () => {
const stop = vi.fn();
docker.watchCron = { stop };
await docker.deregisterComponent();
expect(stop).toHaveBeenCalled();
expect(docker.watchCron).toBeUndefined();
});
test('should clear watch/listen timeouts when they are set', async () => {
await docker.register('watcher', 'docker', 'test', {});
const clearTimeoutSpy = vi.spyOn(globalThis, 'clearTimeout');
docker.watchCronTimeout = setTimeout(() => {}, 10_000) as any;
docker.listenDockerEventsTimeout = setTimeout(() => {}, 10_000) as any;
try {
await docker.deregisterComponent();
expect(clearTimeoutSpy).toHaveBeenCalledTimes(2);
} finally {
clearTimeoutSpy.mockRestore();
}
});
test('should safely deregister when cron and timeouts are unset', async () => {
docker.watchCron = undefined;
docker.watchCronTimeout = undefined;
docker.listenDockerEventsTimeout = undefined;
await expect(docker.deregisterComponent()).resolves.toBeUndefined();
});
});
describe('OIDC Remote Auth', () => {
test('should fetch oidc access token before listing containers', async () => {
mockDockerApi.listContainers.mockResolvedValue([]);
await docker.register(
'watcher',
'docker',
'test',
createOidcConfig({
clientid: 'dd-client',
clientsecret: 'dd-secret',
scope: 'docker.read',
}),
);
await docker.getContainers();
expect(mockAxios.post).toHaveBeenCalledWith(
'https://idp.example.com/oauth/token',
expect.stringContaining('grant_type=client_credentials'),
expect.objectContaining({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}),
);
expect(mockDockerApi.modem.headers.Authorization).toBe('Bearer oidc-token');
expect(mockDockerApi.listContainers).toHaveBeenCalled();
});
test('should use refresh_token grant when refresh token is available', async () => {
mockDockerApi.listContainers.mockResolvedValue([]);
await docker.register(
'watcher',
'docker',
'test',
createOidcConfig({
refreshtoken: 'refresh-token-1',
}),
);
await docker.getContainers();
const tokenRequestBody = mockAxios.post.mock.calls[0][1];
expect(tokenRequestBody).toContain('grant_type=refresh_token');
expect(tokenRequestBody).toContain('refresh_token=refresh-token-1');
});
test('should reuse cached oidc token until close to expiry', async () => {
mockDockerApi.listContainers.mockResolvedValue([]);
mockAxios.post.mockResolvedValue({
data: createTokenResponse({
access_token: 'cached-token',
}),
} as any);
await docker.register('watcher', 'docker', 'test', createOidcConfig());
await docker.getContainers();
await docker.getContainers();
expect(mockAxios.post).toHaveBeenCalledTimes(1);
expect(mockDockerApi.listContainers).toHaveBeenCalledTimes(2);
});
});
describe('OIDC Device Code Flow', () => {
test('should not expose legacy OIDC passthrough helper methods', async () => {
await docker.register('watcher', 'docker', 'test', createOidcConfig());
expect(docker.getOidcGrantType).toBeUndefined();
expect(docker.initializeRemoteOidcStateFromConfiguration).toBeUndefined();
expect(docker.isRemoteOidcTokenRefreshRequired).toBeUndefined();
expect(docker.applyRemoteOidcTokenPayload).toBeUndefined();
expect(docker.performDeviceCodeFlow).toBeUndefined();
expect(docker.handleTokenErrorResponse).toBeUndefined();
expect(docker.pollDeviceCodeToken).toBeUndefined();
expect(docker.refreshRemoteOidcAccessToken).toBeUndefined();
});
test('should validate configuration with device flow oidc settings', async () => {
const config = createDeviceFlowConfig(
{ scope: 'docker.read' },
{ host: 'docker-proxy.example.com' },
);
expect(() => docker.validateConfiguration(config)).not.toThrow();
});
test('should auto-detect device_code grant type when deviceurl is configured', async () => {
await docker.register('watcher', 'docker', 'test', createDeviceFlowConfig());
const grantType = getOidcGrantType({
configuredGrantType: docker.getOidcAuthString(OIDC_GRANT_TYPE_PATHS),
refreshToken: docker.remoteOidcRefreshToken,
deviceUrl: docker.getOidcAuthString(OIDC_DEVICE_URL_PATHS),
});
expect(grantType).toBe('urn:ietf:params:oauth:grant-type:device_code');
});
test('should prefer refresh_token grant over device_code when refresh token exists', async () => {
await docker.register(
'watcher',
'docker',
'test',
createDeviceFlowConfig({
refreshtoken: 'existing-refresh-token',
}),
);
const context = createDockerOidcContext(docker);
initializeRemoteOidcStateFromConfiguration(context);
const grantType = getOidcGrantType({
configuredGrantType: docker.getOidcAuthString(OIDC_GRANT_TYPE_PATHS),
refreshToken: context.state.refreshToken,
deviceUrl: docker.getOidcAuthString(OIDC_DEVICE_URL_PATHS),
});
expect(grantType).toBe('refresh_token');
});
test('should perform device code flow: request device code and poll for token', async () => {
mockDockerApi.listContainers.mockResolvedValue([]);
// First call: device authorization endpoint returns device_code
// Second call: token endpoint returns authorization_pending
// Third call: token endpoint returns access_token
let postCallCount = 0;
mockAxios.post.mockImplementation((url) => {
postCallCount++;
if (url === 'https://idp.example.com/oauth/device/code') {
return Promise.resolve({ data: createDeviceCodeResponse() });
}
if (url === 'https://idp.example.com/oauth/token' && postCallCount === 2) {
return Promise.reject({
response: { data: { error: 'authorization_pending' } },
});
}
return Promise.resolve({
data: createTokenResponse({
access_token: 'device-flow-token',
refresh_token: 'device-flow-refresh',
}),
});
});
await docker.register(
'watcher',
'docker',
'test',
createDeviceFlowConfig({
scope: 'docker.read',
}),
);
// Mock sleep to avoid real delays in tests
docker.sleep = vi.fn().mockResolvedValue(undefined);
await docker.getContainers();
// Verify device authorization request
expect(mockAxios.post).toHaveBeenCalledWith(
'https://idp.example.com/oauth/device/code',
expect.stringContaining('client_id=dd-device-client'),
expect.objectContaining({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}),
);
// Verify token polling request included device_code
const tokenCalls = mockAxios.post.mock.calls.filter(
(call) => call[0] === 'https://idp.example.com/oauth/token',
);
expect(tokenCalls.length).toBeGreaterThanOrEqual(1);
expect(tokenCalls[0][1]).toContain(
'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code',
);
expect(tokenCalls[0][1]).toContain('device_code=device-code-123');
// Verify the token was set
expect(docker.remoteOidcAccessToken).toBe('device-flow-token');
expect(docker.remoteOidcRefreshToken).toBe('device-flow-refresh');
expect(docker.remoteOidcDeviceCodeCompleted).toBe(true);
expect(mockDockerApi.modem.headers.Authorization).toBe('Bearer device-flow-token');
});
test('should handle slow_down error by increasing poll interval', async () => {
mockDockerApi.listContainers.mockResolvedValue([]);
let postCallCount = 0;
mockAxios.post.mockImplementation((url) => {
postCallCount++;
if (url === 'https://idp.example.com/oauth/device/code') {
return Promise.resolve({
data: createDeviceCodeResponse({
device_code: 'device-code-456',
user_code: 'EFGH-5678',
}),
});
}
if (postCallCount === 2) {
return Promise.reject({
response: { data: { error: 'slow_down' } },
});
}
return Promise.resolve({
data: createTokenResponse({
access_token: 'slow-down-token',
}),
});
});
await docker.register('watcher', 'docker', 'test', createDeviceFlowConfig());
docker.sleep = vi.fn().mockResolvedValue(undefined);
await docker.getContainers();
// First sleep with original interval (1s), second with increased (1s + 5s = 6s)
expect(docker.sleep).toHaveBeenCalledTimes(2);
expect(docker.sleep).toHaveBeenNthCalledWith(1, 1000);
expect(docker.sleep).toHaveBeenNthCalledWith(2, 6000);
expect(docker.remoteOidcAccessToken).toBe('slow-down-token');
});
test('should cancel device code polling when watcher is deregistered during sleep', async () => {
mockAxios.post.mockImplementation((url) => {
if (url === 'https://idp.example.com/oauth/device/code') {
return Promise.resolve({
data: createDeviceCodeResponse({
device_code: 'cancel-code',
user_code: 'CANC-1234',
interval: 1,
expires_in: 60,
}),
});
}
return Promise.resolve({
data: createTokenResponse({
access_token: 'should-not-be-used',
}),
});
});
docker.name = 'test';
docker.type = 'docker';
docker.log = createMockLog(['info', 'warn', 'debug', 'error']);
docker.configuration = docker.validateConfiguration(createDeviceFlowConfig()) as any;
docker.dockerApi = mockDockerApi as any;
docker.sleep = vi.fn().mockImplementation(async () => {
await docker.deregisterComponent();
});
await expect(docker.ensureRemoteAuthHeaders()).rejects.toThrow(
'cancelled because watcher was deregistered',
);
const tokenCalls = mockAxios.post.mock.calls.filter(
(call) => call[0] === 'https://idp.example.com/oauth/token',
);
expect(tokenCalls).toHaveLength(0);
expect(docker.remoteOidcAccessToken).toBeUndefined();
});
test.each([
[
'expired_token',
'expired-device-code',
'XXXX-0000',
'device code expired before user authorization',
],
['access_denied', 'denied-device-code', 'DENY-0001', 'user denied the authorization request'],
])('should throw on %s error', async (errorCode, deviceCode, userCode, expectedMessage) => {
mockDockerApi.listContainers.mockResolvedValue([]);
mockAxios.post.mockImplementation((url) => {
if (url === 'https://idp.example.com/oauth/device/code') {
return Promise.resolve({
data: createDeviceCodeResponse({
device_code: deviceCode,
user_code: userCode,