-
Notifications
You must be signed in to change notification settings - Fork 33
/
registry-client-v2.js
1659 lines (1519 loc) · 57.4 KB
/
registry-client-v2.js
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
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright 2016 Joyent, Inc.
*/
/*
* Docker Registry API v2 client. See the README for an intro.
*
* <https://docs.docker.com/registry/spec/api/>
*/
var assert = require('assert-plus');
var base64url = require('base64url');
var bunyan = require('bunyan');
var crypto = require('crypto');
var fmt = require('util').format;
var jwkToPem = require('jwk-to-pem');
var mod_jws = require('jws');
var querystring = require('querystring');
var restifyClients = require('restify-clients');
var restifyErrors = require('restify-errors');
var strsplit = require('strsplit');
var mod_url = require('url');
var vasync = require('vasync');
var common = require('./common');
var DockerJsonClient = require('./docker-json-client');
var errors = require('./errors');
// --- Globals
// https://github.com/docker/docker/blob/77da5d8/registry/config_unix.go#L10
var DEFAULT_V2_REGISTRY = 'https://registry-1.docker.io';
var MEDIATYPE_MANIFEST_V2
= 'application/vnd.docker.distribution.manifest.v2+json';
var MEDIATYPE_MANIFEST_LIST_V2
= 'application/vnd.docker.distribution.manifest.list.v2+json';
// --- internal support functions
function _createLogger(log) {
assert.optionalObject(log, 'log');
if (log) {
// TODO avoid this .child if already have the serializers, e.g. for
// recursive call.
return log.child({
serializers: restifyClients.bunyan.serializers
});
} else {
return bunyan.createLogger({
name: 'registry',
serializers: restifyClients.bunyan.serializers
});
}
}
function _basicAuthHeader(username, password) {
var buffer = new Buffer(username + ':' + password, 'utf8');
return 'Basic ' + buffer.toString('base64');
}
/*
* Set the "Authorization" HTTP header into the headers object from the given
* auth info.
* - Bearer auth if `token`.
* - Else, Basic auth if `username`.
* - Else, if the authorization key exists, then it is removed from headers.
*/
function _setAuthHeaderFromAuthInfo(headers, authInfo) {
if (authInfo.token) {
headers.authorization = 'Bearer ' + authInfo.token;
} else if (authInfo.username) {
headers.authorization = _basicAuthHeader(authInfo.username,
authInfo.password);
} else if (headers.authorization) {
delete headers.authorization;
}
}
/**
* Special handling of errors from the registry server.
*
* Some registry errors will use a custom error format, so detect those
* and convert these as necessary.
*
* Example JSON response for a missing repo:
* {
* "jse_shortmsg": "",
* "jse_info": {},
* "message": "{\"errors\":[{\"code\":\"UNAUTHORIZED\",\"message\":\"...}\n",
* "body": {
* "errors": [{
* "code": "UNAUTHORIZED",
* "message": "authentication required",
* "detail": [{
* "Type": "repository",
* "Class": "",
* "Name": "library/idontexist",
* "Action": "pull"
* }]
* }]
* }
* }
*
* Example JSON response for bad username/password:
* {
* "statusCode": 401,
* "jse_shortmsg":"",
* "jse_info":{},
* "message":"{\"details\":\"incorrect username or password\"}\n",
* "body":{
* "details": "incorrect username or password"
* }
* }
*
* Example AWS token error:
* {
* "statusCode": 400,
* "errors": [
* {
* "code": "DENIED",
* "message": "Your Authorization Token is invalid."
* }
* ]
* }
*/
function _getRegistryErrorMessage(err) {
if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) {
return err.body.errors[0].message;
} else if (err.body && err.body.details) {
return err.body.details;
} else if (Array.isArray(err.errors) && err.errors[0].message) {
return err.errors[0].message;
} else if (err.message) {
return err.message;
}
return err.toString();
}
/**
* Parse a WWW-Authenticate header like this:
*
* // JSSTYLED
* www-authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io"
* www-authenticate: Basic realm="registry456.example.com"
*
* into an object like this:
*
* {
* scheme: 'Bearer',
* parms: {
* realm: 'https://auth.docker.io/token',
* service: 'registry.docker.io'
* }
* }
*
* Note: This doesn't handle *multiple* challenges. I've not seen a concrete
* example of that.
*/
function _parseWWWAuthenticate(header) {
var parsers = require('www-authenticate/lib/parsers');
var parsed = new parsers.WWW_Authenticate(header);
if (parsed.err) {
throw new Error('could not parse WWW-Authenticate header "' + header
+ '": ' + parsed.err);
}
return parsed;
}
/**
* Get an auth token.
*
* See: docker/docker.git:registry/token.go
*/
function _getToken(opts, cb) {
assert.string(opts.indexName, 'opts.indexName'); // used for error messages
assert.string(opts.realm, 'opts.realm');
assert.optionalString(opts.service, 'opts.service');
assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
assert.optionalString(opts.username, 'opts.username');
assert.optionalString(opts.password, 'opts.password');
// HTTP client opts:
assert.object(opts.log, 'opts.log');
assert.optionalObject(opts.agent, 'opts.agent');
// assert.optional object or bool(opts.proxy, 'opts.proxy');
assert.optionalBool(opts.insecure, 'opts.insecure');
assert.optionalString(opts.userAgent, 'opts.userAgent');
var log = opts.log;
// - add https:// prefix (or http) if none on 'realm'
var tokenUrl = opts.realm;
var match = /^(\w+):\/\//.exec(tokenUrl);
if (!match) {
tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
} else if (['http', 'https'].indexOf(match[1]) === -1) {
return cb(new Error(fmt('unsupported scheme for ' +
'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
}
// - GET $realm
// ?service=$service
// (&scope=$scope)*
// (&account=$username)
// Authorization: Basic ...
var headers = {};
var query = {};
if (opts.service) {
query.service = opts.service;
}
if (opts.scopes && opts.scopes.length) {
query.scope = opts.scopes; // intentionally singular 'scope'
}
if (opts.username) {
query.account = opts.username;
_setAuthHeaderFromAuthInfo(headers, {
username: opts.username,
password: opts.password
});
}
if (Object.keys(query).length) {
tokenUrl += '?' + querystring.stringify(query);
}
log.trace({tokenUrl: tokenUrl}, '_getToken: url');
var parsedUrl = mod_url.parse(tokenUrl);
var client = new DockerJsonClient({
url: parsedUrl.protocol + '//' + parsedUrl.host,
log: log,
agent: opts.agent,
proxy: opts.proxy,
rejectUnauthorized: !opts.insecure,
userAgent: opts.userAgent || common.DEFAULT_USERAGENT
});
client.get({
path: parsedUrl.path,
headers: headers
}, function (err, req, res, body) {
client.close();
if (err) {
if (err.statusCode === 401) {
// Convert *all* 401 errors to use a generic error constructor
// with a simple error message.
var errMsg = _getRegistryErrorMessage(err);
return cb(new errors.UnauthorizedError(errMsg));
}
return cb(err);
} else if (!body.token) {
return cb(new errors.UnauthorizedError(err, 'authorization ' +
'server did not include a token in the response'));
}
cb(null, body.token);
});
}
/* BEGIN JSSTYLED */
/*
* Parse out a JWS (JSON Web Signature) from the given Docker manifest
* endpoint response. This JWS is used for both 'Docker-Content-Digest' header
* verification and JWS signing verification.
*
* This mimicks:
* func ParsePrettySignature(content []byte, signatureKey string)
* (*JSONSignature, error)
* in "docker/vendor/src/github.com/docker/libtrust/jsonsign.go"
*
* @returns {Object} JWS object with 'payload' and 'signatures' fields.
* @throws {InvalidContentError} if there is a problem parsing the manifest
* body.
*
*
* # Design
*
* tl;dr: Per <https://docs.docker.com/registry/spec/api/#digest-header>
* the payload used for the digest is a little obtuse for the getManifest
* endpoint: It is the raw JSON body (the raw content because indentation
* and key order matters) minus the "signatures" key. The "signatures"
* key is always the last one. The byte offset at which to strip and a
* suffix to append is included in the JWS "protected" header.
*
*
* A longer explanation:
*
* Let's use the following (clipped for clarity) sample getManifest
* request/response to a Docker v2 Registry API (in this case Docker Hub):
*
* GET /v2/library/alpine/manifests/latest HTTP/1.1
* ...
*
* HTTP/1.1 200 OK
* docker-content-digest: sha256:08a98db12e...fe0d
* ...
*
* {
* "schemaVersion": 1,
* "name": "library/alpine",
* "tag": "latest",
* "architecture": "amd64",
* "fsLayers": [
* {
* "blobSum": "sha256:c862d82a67...d58"
* }
* ],
* "history": [
* {
* "v1Compatibility": "{\"id\":\"31f6...4492}\n"
* }
* ],
* "signatures": [
* {
* "header": {
* "jwk": {
* "crv": "P-256",
* "kid": "OIH7:HQFS:44FK:45VB:3B53:OIAG:TPL4:ATF5:6PNE:MGHN:NHQX:2GE4",
* "kty": "EC",
* "x": "Cu_UyxwLgHzE9rvlYSmvVdqYCXY42E9eNhBb0xNv0SQ",
* "y": "zUsjWJkeKQ5tv7S-hl1Tg71cd-CqnrtiiLxSi6N_yc8"
* },
* "alg": "ES256"
* },
* "signature": "JV1F_gXAsUEp_e2WswSdHjvI0veC-f6EEYuYJZhgIPpN-LQ5-IBSOX7Ayq1gv1m2cjqPy3iXYc2HeYgCQTxM-Q",
* "protected": "eyJmb3JtYXRMZW5ndGgiOjE2NzUsImZvcm1hdFRhaWwiOiJDbjAiLCJ0aW1lIjoiMjAxNS0wOS0xMFQyMzoyODowNloifQ"
* }
* ]
* }
*
*
* We will be talking about specs from the IETF JavaScript Object Signing
* and Encryption (JOSE) working group
* <https://datatracker.ietf.org/wg/jose/documents/>. The relevant ones
* with Docker registry v2 (a.k.a. docker/distribution) are:
*
* 1. JSON Web Signature (JWS): https://tools.ietf.org/html/rfc7515
* 2. JSON Web Key (JWK): https://tools.ietf.org/html/rfc7517
*
*
* Docker calls the "signatures" value the "JWS", a JSON Web Signature.
* That's mostly accurate. A JWS, using the JSON serialization that
* Docker is using, looks like:
*
* {
* "payload": "<base64url-encoded payload bytes>",
* "signatures": [
* {
* "signature": "<base64url-encoded signature>",
* // One or both of "protected" and "header" must be
* // included, and an "alg" key (the signing algoritm)
* // must be in one of them.
* "protected": "<base64url-encoded header key/value pairs
* included in the signature>",
* "header": {
* <key/value pairs *not* included in the signature>
* }
* }
* ]
* }
*
* (I'm eliding some details: If there is only one signature, then the
* signature/protected/et al fields can be raised to the top-level. There
* is a "compact" serialization that we don't need to worry about,
* other than most node.js JWS modules don't directly support the JSON
* serialization. There are other optional signature fields.)
*
* I said "mostly accurate", because the "payload" is missing. Docker
* flips the JWS inside out, so that the "signatures" are include *in
* the payload*. The "protected" header provides some data needed to
* tease the signing payload out of the HTTP response body. Using our
* example:
*
* $ echo eyJmb3JtYXRMZW5ndGgiOjE2NzUsImZvcm1hdFRhaWwiOiJDbjAiLCJ0aW1lIjoiMjAxNS0wOS0xMFQyMzoyODowNloifQ | ./node_modules/.bin/base64url --decode
* {"formatLength":1675,"formatTail":"Cn0","time":"2015-09-10T23:28:06Z"}
*
* Here "formatLength" is a byte count into the response body to extract
* and "formatTail" is a base64url-encoded suffix to append to that. In
* practice the "formatLength" is up to comma before the "signatures" key
* and "formatLength" is:
*
* > base64url.decode('Cn0')
* '\n}'
*
* Meaning the signing payload is typically the equivalent of
* `delete body["signatures"]`:
*
* {
* "schemaVersion": 1,
* "name": "library/alpine",
* "tag": "latest",
* "architecture": "amd64",
* "fsLayers": ...,
* "history": ...
* }
*
* However, whitespace is significant because we are just signing bytes,
* so the raw response body must be manipulated. An odd factoid is that
* docker/libtrust seems to default to 3-space indentation:
* <https://github.com/docker/libtrust/blob/9cbd2a1374f46905c68a4eb3694a130610adc62a/jsonsign.go#L450>
* Perhaps to avoid people getting lucky.
*
*/
/* END JSSTYLED */
function _jwsFromManifest(manifest, body) {
assert.object(manifest, 'manifest');
assert.buffer(body, 'body');
var formatLength;
var formatTail;
var jws = {
signatures: []
};
for (var i = 0; i < manifest.signatures.length; i++) {
var sig = manifest.signatures[i];
try {
var protectedHeader = JSON.parse(
base64url.decode(sig['protected']));
} catch (protectedErr) {
throw new restifyErrors.InvalidContentError(protectedErr, fmt(
'could not parse manifest "signatures[%d].protected": %j',
i, sig['protected']));
}
if (isNaN(protectedHeader.formatLength)) {
throw new restifyErrors.InvalidContentError(fmt(
'invalid "formatLength" in "signatures[%d].protected": %j',
i, protectedHeader.formatLength));
} else if (formatLength === undefined) {
formatLength = protectedHeader.formatLength;
} else if (protectedHeader.formatLength !== formatLength) {
throw new restifyErrors.InvalidContentError(fmt(
'conflicting "formatLength" in "signatures[%d].protected": %j',
i, protectedHeader.formatLength));
}
if (!protectedHeader.formatTail ||
typeof (protectedHeader.formatTail) !== 'string')
{
throw new restifyErrors.InvalidContentError(fmt(
'missing "formatTail" in "signatures[%d].protected"', i));
}
var formatTail_ = base64url.decode(protectedHeader.formatTail);
if (formatTail === undefined) {
formatTail = formatTail_;
} else if (formatTail_ !== formatTail) {
throw new restifyErrors.InvalidContentError(fmt(
'conflicting "formatTail" in "signatures[%d].protected": %j',
i, formatTail_));
}
var jwsSig = {
header: {
alg: sig.header.alg,
chain: sig.header.chain
},
signature: sig.signature,
'protected': sig['protected']
};
if (sig.header.jwk) {
try {
jwsSig.header.jwk = jwkToPem(sig.header.jwk);
} catch (jwkErr) {
throw new restifyErrors.InvalidContentError(jwkErr, fmt(
'error in "signatures[%d].header.jwk": %s',
i, jwkErr.message));
}
}
jws.signatures.push(jwsSig);
}
jws.payload = Buffer.concat([
body.slice(0, formatLength),
new Buffer(formatTail)
]);
return jws;
}
/*
* Parse the 'Docker-Content-Digest' header.
*
* @throws {BadDigestError} if the value is missing or malformed
* @returns ...
*/
function _parseDockerContentDigest(dcd) {
if (!dcd) {
throw new restifyErrors.BadDigestError(
'missing "Docker-Content-Digest" header');
}
// E.g. docker-content-digest: sha256:887f7ecfd0bda3...
var parts = strsplit(dcd, ':', 2);
if (parts.length !== 2) {
throw new restifyErrors.BadDigestError(
'could not parse "Docker-Content-Digest" header: ' + dcd);
}
var hash;
try {
hash = crypto.createHash(parts[0]);
} catch (hashErr) {
throw new restifyErrors.BadDigestError(hashErr, fmt(
'"Docker-Content-Digest" header error: %s: %s',
hashErr.message, dcd));
}
var expectedDigest = parts[1];
return {
raw: dcd,
hash: hash,
algorithm: parts[0],
expectedDigest: expectedDigest
};
}
/*
* Verify the 'Docker-Content-Digest' header for a getManifest response.
*
* @throws {BadDigestError} if the digest doesn't check out.
*/
function _verifyManifestDockerContentDigest(res, jws) {
var dcdInfo = _parseDockerContentDigest(
res.headers['docker-content-digest']);
dcdInfo.hash.update(jws.payload);
var digest = dcdInfo.hash.digest('hex');
if (dcdInfo.expectedDigest !== digest) {
res.log.trace({expectedDigest: dcdInfo.expectedDigest,
header: dcdInfo.raw, digest: digest},
'Docker-Content-Digest failure');
throw new restifyErrors.BadDigestError('Docker-Content-Digest');
}
}
/*
* Verify a manifest JWS (JSON Web Signature)
*
* This mimicks
* func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error)
* in "docker/vendor/src/github.com/docker/distribution/manifest/verify.go"
* which calls
* func (js *JSONSignature) Verify() ([]PublicKey, error)
* in "docker/vendor/src/github.com/docker/libtrust/jsonsign.go"
*
* TODO: find an example with `signatures.*.header.chain` to test that path
*
* @param jws {Object} A JWS object parsed from `_jwsFromManifest`.
* @throws {errors.ManifestVerificationError} if there is a problem.
*/
function _verifyJws(jws) {
var encodedPayload = base64url(jws.payload);
/*
* Disallow the "none" algorithm because while the `jws` module might have
* a guard against
* // JSSTYLED
* https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
* why bother allowing it?
*/
var disallowedAlgs = ['none'];
for (var i = 0; i < jws.signatures.length; i++) {
var jwsSig = jws.signatures[i];
var alg = jwsSig.header.alg;
if (disallowedAlgs.indexOf(alg) !== -1) {
throw new errors.ManifestVerificationError(
{jws: jws, i: i}, 'disallowed JWS signature algorithm:', alg);
}
// TODO: Find Docker manifest example using 'header.chain'
// and implement this. See "jsonsign.go#Verify".
if (jwsSig.header.chain) {
throw new errors.InternalError({jws: jws, i: i},
'JWS verification with a cert "chain" is not implemented: %j',
jwsSig.header.chain);
}
// `mod_jws.verify` takes the JWS compact representation.
var jwsCompact = jwsSig['protected'] + '.' + encodedPayload +
'.' + jwsSig.signature;
var verified = mod_jws.verify(jwsCompact, alg, jwsSig.header.jwk);
if (!verified) {
throw new errors.ManifestVerificationError(
{jws: jws, i: i}, 'JWS signature %d failed verification', i);
}
}
}
// --- other exports
/**
* Ping the base URL.
* See: <https://docs.docker.com/registry/spec/api/#base>
*
* @param opts {Object} Required members are listed first.
* - opts.index {String|Object} Required. One of an index *name* (e.g.
* "docker.io", "quay.io") that `parseIndex` will handle, an index
* *url* (e.g. the default from `docker login` is
* 'https://index.docker.io/v1/'), or an index *object* as returned by
* `parseIndex`. For backward compatibility, `opts.indexName` may be
* used instead of `opts.index`.
* --
* - opts.log {Bunyan Logger} Optional.
* --
* TODO: document other options
* @param cb {Function} `function (err, body, res, req)`
* `err` is set if there was a problem getting a ping response. `res` is
* the response object. Use `res.statusCode` to infer information:
* 404 This registry URL does not support the v2 API.
* 401 Authentication is required (or failed). Use the
* WWW-Authenticate header for the appropriate auth method.
* This `res` can be passed to `login()` to handle
* authenticating.
* 200 Successful authentication. The response body is `body`
* if wanted.
*/
function ping(opts, cb) {
assert.func(cb, 'cb');
assert.object(opts, 'opts');
assert.ok(opts.index || opts.indexName,
'opts.index or opts.indexName is required');
assert.optionalObject(opts.log, 'opts.log');
// HTTP client basic options:
assert.optionalBool(opts.insecure, 'opts.insecure');
assert.optionalBool(opts.rejectUnauthorized, 'opts.rejectUnauthorized');
assert.optionalString(opts.userAgent, 'opts.userAgent');
assert.optionalObject(opts.agent, 'opts.agent');
// assert.optional object or bool(opts.proxy, 'opts.proxy');
var index = opts.index || opts.indexName;
if (typeof (index) === 'string') {
try {
index = common.parseIndex(index);
} catch (indexNameErr) {
cb(indexNameErr);
return;
}
} else {
assert.object(index, 'opts.index');
}
var log = _createLogger(opts.log);
log.trace({index: index, scope: opts.scope, insecure: opts.insecure},
'ping');
/*
* We have to special case usage of the "official" docker.io to
* https://registry-1.docker.io
* because:
* GET /v2/ HTTP/1.1
* Host: index.docker.io
*
* HTTP/1.1 301 Moved Permanently
* location: https://registry.hub.docker.com/v2/
* and:
* $ curl -i https://registry.hub.docker.com/v2/
* HTTP/1.1 404 NOT FOUND
*/
var registryUrl;
if (index.official) {
registryUrl = DEFAULT_V2_REGISTRY;
} else {
registryUrl = common.urlFromIndex(index);
}
/*
* We allow either opts.rejectUnauthorized (for passed in http client
* options where `insecure` -> `rejectUnauthorized` translation has
* already been done) or opts.insecure (this module's chosen name
* for this thing).
*/
var rejectUnauthorized;
if (opts.insecure !== undefined && opts.rejectUnauthorized !== undefined) {
throw new assert.AssertionError(
'cannot set both opts.insecure and opts.rejectUnauthorized');
} else if (opts.insecure !== undefined) {
rejectUnauthorized = !opts.insecure;
} else if (opts.rejectUnauthorized !== undefined) {
rejectUnauthorized = opts.rejectUnauthorized;
}
var client = new DockerJsonClient({
url: registryUrl,
log: opts.log,
userAgent: opts.userAgent || common.DEFAULT_USERAGENT,
rejectUnauthorized: rejectUnauthorized,
agent: opts.agent,
proxy: opts.proxy
});
client.get({
path: '/v2/',
// Ping should be fast. We don't want 15s of retrying.
retry: false,
connectTimeout: 10000
}, function _afterPing(err, req, res, body) {
client.close();
cb(err, body, res, req);
});
}
/**
* Login V2
*
* Typically one does not need to call this function directly because most
* methods of a `RegistryClientV2` will automatically login as necessary.
* Once exception is the `ping` method, which intentionally does not login.
* That is because the point of the ping is to determine quickly if the
* registry supports v2, which doesn't require the extra work of logging in.
*
* This attempts to reproduce the logic of "docker.git:registry/auth.go#loginV2"
*
* @param opts {Object}
* - opts.index {String|Object} Required. One of an index *name* (e.g.
* "docker.io", "quay.io") that `parseIndex` will handle, an index
* *url* (e.g. the default from `docker login` is
* 'https://index.docker.io/v1/'), or an index *object* as returned by
* `parseIndex`. For backward compatibility, `opts.indexName` may be
* used instead of `opts.index`.
* - opts.username {String} Optional. Username and password are optional
* to allow `RegistryClientV2` to use `login` in the common case when
* there may or may not be auth required.
* - opts.password {String} Optional, but required if `opts.username` is
* provided.
* - opts.scope {String} Optional. A scope string passed in for
* bearer/token auth. If this is just a login request where the token
* won't be used, then the empty string (the default) is sufficient.
* // JSSTYLED
* See <https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md#requesting-a-token>
* - opts.pingRes {Object} Optional. The response object from an earlier
* `ping()` call. This can be used to save re-pinging.
* - opts.pingErr {Object} Required if `pingRes` given. The error
* object for `pingRes`.
* ...
* @param cb {Function} `function (err, result)`
* On success, `result` is an object with:
* status a string description of the login result status
* authInfo an object with authentication info, examples:
* {type: 'basic', username: '...', password: '...'}
* {type: 'bearer', token: '...'}
* which can be the empty object when no auth is needed:
* {}
*/
function login(opts, cb) {
assert.object(opts, 'opts');
assert.ok(opts.index || opts.indexName,
'opts.index or opts.indexName is required');
assert.optionalString(opts.username, 'opts.username');
if (opts.username) {
assert.string(opts.password,
'opts.password required if username given');
} else {
assert.optionalString(opts.password, 'opts.password');
}
assert.optionalString(opts.scope, 'opts.scope');
assert.optionalString(opts.userAgent, 'opts.userAgent');
assert.optionalBool(opts.insecure, 'opts.insecure');
assert.optionalObject(opts.pingRes, 'opts.pingRes');
if (opts.pingRes && opts.pingRes.statusCode !== 200) {
assert.object(opts.pingErr, 'opts.pingErr');
} else {
assert.optionalObject(opts.pingErr, 'opts.pingErr');
}
assert.optionalObject(opts.log, 'opts.log');
assert.optionalString(opts.userAgent, 'opts.userAgent');
assert.optionalObject(opts.agent, 'opts.agent');
// assert.optional object or bool(opts.proxy, 'opts.proxy');
assert.func(cb, 'cb');
var index = opts.index || opts.indexName;
if (typeof (index) === 'string') {
try {
index = common.parseIndex(index);
} catch (indexNameErr) {
cb(indexNameErr);
return;
}
} else {
assert.object(index, 'opts.index');
}
var log = _createLogger(opts.log);
log.trace({index: index, username: opts.username,
password: (opts.password ? '(censored)' : '(none)'),
scope: opts.scope, insecure: opts.insecure}, 'login');
var scope = opts.scope || '';
var authInfo;
var context = {
pingErr: opts.pingErr
};
vasync.pipeline({arg: context, funcs: [
function ensureChalHeader(ctx, next) {
if (opts.pingRes) {
ctx.chalHeader = opts.pingRes.headers['www-authenticate'];
if (ctx.chalHeader) {
return next();
}
}
ping(opts, function (err, _, res, req) {
if (!err) {
assert.equal(res.statusCode, 200,
'ping success without 200');
// No authorization is necessary.
authInfo = {};
next(true); // early pipeline abort
} else if (res && res.statusCode === 401) {
var chalHeader = res.headers['www-authenticate'];
// DOCKER-627 hack for quay.io
if (!chalHeader && req._headers.host === 'quay.io') {
/* JSSTYLED */
chalHeader = 'Bearer realm="https://quay.io/v2/auth",service="quay.io"';
}
if (!chalHeader) {
next(new errors.UnauthorizedError(
'missing WWW-Authenticate header in 401 ' +
'response to "GET /v2/" (see ' +
/* JSSTYLED */
'https://docs.docker.com/registry/spec/api/#api-version-check)'));
return;
}
ctx.pingErr = err;
ctx.chalHeader = chalHeader;
next();
} else {
next(err);
}
});
},
function parseAuthChallenge(ctx, next) {
try {
ctx.authChallenge = _parseWWWAuthenticate(ctx.chalHeader);
} catch (chalErr) {
return next(new errors.UnauthorizedError(chalErr));
}
next();
},
function basicAuth(ctx, next) {
if (ctx.authChallenge.scheme.toLowerCase() !== 'basic') {
return next();
}
authInfo = {
type: 'basic',
username: opts.username,
password: opts.password
};
next(true);
},
function bearerAuth(ctx, next) {
if (ctx.authChallenge.scheme.toLowerCase() !== 'bearer') {
return next();
}
log.debug({challenge: ctx.authChallenge},
'login: get Bearer auth token');
_getToken({
indexName: index.name,
realm: ctx.authChallenge.parms.realm,
service: ctx.authChallenge.parms.service,
scopes: scope ? [scope] : [],
username: opts.username,
password: opts.password,
// HTTP client opts:
log: log,
agent: opts.agent,
proxy: opts.proxy,
userAgent: opts.userAgent,
insecure: opts.insecure
}, function (err, token) {
if (err) {
return next(err);
}
log.debug({token: token}, 'login: Bearer auth token');
authInfo = {
type: 'bearer',
token: token
};
next(true); // early pipeline abort
});
},
function unknownAuthScheme(ctx, next) {
next(new errors.UnauthorizedError('unsupported auth scheme: "%s"',
ctx.authChallenge.scheme));
}
]}, function (err) {
if (err === true) { // early abort
err = null;
}
log.trace({err: err, success: !err}, 'login: done');
if (err) {
cb(err);
} else {
assert.object(authInfo, 'authInfo');
cb(null, {
status: 'Login Succeeded',
authInfo: authInfo
});
}
});
}
/**
* Calculate the 'Docker-Content-Digest' header for the given manifest.
*
* @returns {String} The docker digest string.
* @throws {InvalidContentError} if there is a problem parsing the manifest.
*/
function digestFromManifestStr(manifestStr) {
assert.string(manifestStr, 'manifestStr');
var hash = crypto.createHash('sha256');
var digestPrefix = 'sha256:';
var manifest;
try {
manifest = JSON.parse(manifestStr);
} catch (err) {
throw new restifyErrors.InvalidContentError(err, fmt(
'could not parse manifest: %s', manifestStr));
}
if (manifest.schemaVersion === 1) {
try {
var manifestBuffer = Buffer(manifestStr);
var jws = _jwsFromManifest(manifest, manifestBuffer);
hash.update(jws.payload, 'binary');
return digestPrefix + hash.digest('hex');
} catch (verifyErr) {
if (!(verifyErr instanceof restifyErrors.InvalidContentError)) {
throw verifyErr;
}
// Couldn't parse (or doesn't have) the signatures section,
// fall through.
}
}
hash.update(manifestStr);
return digestPrefix + hash.digest('hex');
}
// --- RegistryClientV2
/**
* Create a new Docker Registry V2 client for a particular repository.
*
* @param opts.insecure {Boolean} Optional. Default false. Set to true
* to *not* fail on an invalid or self-signed server certificate.
* ... TODO: lots more to document
*
*/
function RegistryClientV2(opts) {
var self = this;
assert.object(opts, 'opts');
// One of `opts.name` or `opts.repo`.
assert.ok((opts.name || opts.repo) && !(opts.name && opts.repo),
'exactly one of opts.name or opts.repo must be given');
if (opts.name) {
assert.string(opts.name, 'opts.name');
} else {
assert.object(opts.repo, 'opts.repo');
}
assert.optionalObject(opts.log, 'opts.log');
assert.optionalString(opts.username, 'opts.username');
if (opts.username) {
assert.string(opts.password,
'opts.password required if username given');
} else {
assert.optionalString(opts.password, 'opts.password');
}
assert.optionalString(opts.token, 'opts.token'); // for Bearer auth
assert.optionalBool(opts.insecure, 'opts.insecure');
assert.optionalString(opts.scheme, 'opts.scheme');
assert.optionalBool(opts.acceptManifestLists, 'opts.acceptManifestLists');