Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" 

Module for accessing a Docker v2 Registry 

""" 

 

import base64 

import hashlib 

import json 

import sys 

 

try: 

import urllib.parse as urlparse 

from urllib.parse import urlencode 

except ImportError: 

# pylint: disable=import-error,no-name-in-module,wrong-import-order 

from urllib import urlencode 

import urlparse 

 

from jwcrypto import jwk, jws 

import requests 

import www_authenticate 

# pylint: disable=wildcard-import 

from dxf import exceptions 

 

_schema2_mimetype = 'application/vnd.docker.distribution.manifest.v2+json' 

 

26 ↛ 29line 26 didn't jump to line 29, because the condition on line 26 was never falseif sys.version_info < (3, 0): 

_binary_type = str 

else: 

_binary_type = bytes 

# pylint: disable=redefined-builtin 

long = int 

 

def _to_bytes_2and3(s): 

return s if isinstance(s, _binary_type) else s.encode('utf-8') 

 

def hash_bytes(buf): 

""" 

Hash bytes using the same method the registry uses (currently SHA-256). 

 

:param buf: Bytes to hash 

:type buf: binary str 

 

:rtype: str 

:returns: Hex-encoded hash of file's content 

""" 

sha256 = hashlib.sha256() 

sha256.update(buf) 

return sha256.hexdigest() 

 

def hash_file(filename): 

""" 

Hash a file using the same method the registry uses (currently SHA-256). 

 

:param filename: Name of file to hash 

:type filename: str 

 

:rtype: str 

:returns: Hex-encoded hash of file's content 

""" 

sha256 = hashlib.sha256() 

with open(filename, 'rb') as f: 

for chunk in iter(lambda: f.read(8192), b''): 

sha256.update(chunk) 

return sha256.hexdigest() 

 

def _raise_for_status(r): 

# pylint: disable=no-member 

if r.status_code == requests.codes.unauthorized: 

raise exceptions.DXFUnauthorizedError() 

r.raise_for_status() 

 

class _ReportingFile(object): 

def __init__(self, dgst, f, cb): 

self._dgst = dgst 

self._f = f 

self._cb = cb 

self._size = requests.utils.super_len(f) 

cb(dgst, b'', self._size) 

# define __iter__ so requests thinks we're a stream 

# (models.py, PreparedRequest.prepare_body) 

def __iter__(self): 

assert not "called" 

# define fileno, tell and mode so requests can find length 

# (utils.py, super_len) 

def fileno(self): 

return self._f.fileno() 

def tell(self): 

return self._f.tell() 

@property 

def mode(self): 

return self._f.mode 

def read(self, n): 

chunk = self._f.read(n) 

if chunk: 

self._cb(self._dgst, chunk, self._size) 

return chunk 

 

class _ReportingChunks(object): 

# pylint: disable=too-few-public-methods 

def __init__(self, dgst, data, cb): 

self._dgst = dgst 

self._data = data 

self._cb = cb 

def __iter__(self): 

for chunk in self._data: 

106 ↛ 108line 106 didn't jump to line 108, because the condition on line 106 was never false if chunk: 

self._cb(self._dgst, chunk) 

yield chunk 

 

class PaginatingResponse(object): 

# pylint: disable=too-few-public-methods 

def __init__(self, dxf_obj, req_meth, path, header, **kwargs): 

self._meth = getattr(dxf_obj, req_meth) 

self._path = path 

self._header = header 

self._kwargs = kwargs 

def __iter__(self): 

while self._path: 

response = self._meth('get', self._path, **self._kwargs) 

self._kwargs = {} 

for v in response.json()[self._header]: 

yield v 

nxt = response.links.get('next') 

self._path = nxt['url'] if nxt else None 

 

class DXFBase(object): 

# pylint: disable=too-many-instance-attributes 

""" 

Class for communicating with a Docker v2 registry. 

Contains only operations which aren't related to repositories. 

 

Can act as a context manager. For each context entered, a new 

`requests.Session <http://docs.python-requests.org/en/latest/user/advanced/#session-objects>`_ 

is obtained. Connections to the same host are shared by the session. 

When the context exits, all the session's connections are closed. 

 

If you don't use :class:`DXFBase` as a context manager, each request 

uses an ephemeral session. If you don't read all the data from an iterator 

returned by :meth:`DXF.pull_blob` then the underlying connection won't be 

closed until Python garbage collects the iterator. 

""" 

def __init__(self, host, auth=None, insecure=False, auth_host=None, tlsverify=True): 

# pylint: disable=too-many-arguments 

""" 

:param host: Host name of registry. Can contain port numbers. e.g. ``registry-1.docker.io``, ``localhost:5000``. 

:type host: str 

 

:param auth: Authentication function to be called whenever authentication to the registry is required. Receives the :class:`DXFBase` object and a HTTP response object. It should call :meth:`authenticate` with a username, password and ``response`` before it returns. 

:type auth: function(dxf_obj, response) 

 

:param insecure: Use HTTP instead of HTTPS (which is the default) when connecting to the registry. 

:type insecure: bool 

 

:param auth_host: Host to use for token authentication. If set, overrides host returned by then registry. 

:type auth_host: str 

 

:param tlsverify: When set to False, do not verify TLS certificate. 

:type tlsverify: bool 

""" 

self._base_url = ('http' if insecure else 'https') + '://' + host + '/v2/' 

self._auth = auth 

self._insecure = insecure 

self._auth_host = auth_host 

self._token = None 

self._headers = {} 

self._repo = None 

self._sessions = [requests] 

self._tlsverify = tlsverify 

if not tlsverify: 

try: 

from requests.packages import urllib3 

except ImportError: 

import urllib3 

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 

 

 

@property 

def token(self): 

""" 

str: Authentication token. This will be obtained automatically when 

you call :meth:`authenticate`. If you've obtained a token 

previously, you can also set it but be aware tokens expire quickly. 

""" 

return self._token 

 

@token.setter 

def token(self, value): 

self._token = value 

self._headers = { 

'Authorization': 'Bearer ' + value 

} 

 

def _base_request(self, method, path, **kwargs): 

def make_kwargs(): 

r = {'allow_redirects': True, 'verify': self._tlsverify} 

r.update(kwargs) 

if 'headers' not in r: 

r['headers'] = {} 

r['headers'].update(self._headers) 

return r 

url = urlparse.urljoin(self._base_url, path) 

r = getattr(self._sessions[0], method)(url, **make_kwargs()) 

# pylint: disable=no-member 

if r.status_code == requests.codes.unauthorized and self._auth: 

headers = self._headers 

self._auth(self, r) 

207 ↛ 209line 207 didn't jump to line 209, because the condition on line 207 was never false if self._headers != headers: 

r = getattr(self._sessions[0], method)(url, **make_kwargs()) 

_raise_for_status(r) 

return r 

 

def authenticate(self, 

username=None, password=None, 

actions=None, response=None, 

authorization=None): 

# pylint: disable=too-many-arguments 

""" 

Authenticate to the registry using a username and password, 

an authorization header or otherwise as the anonymous user. 

 

:param username: User name to authenticate as. 

:type username: str 

 

:param password: User's password. 

:type password: str 

 

:param actions: If you know which types of operation you need to make on the registry, specify them here. Valid actions are ``pull``, ``push`` and ``*``. 

:type actions: list 

 

:param response: When the ``auth`` function you passed to :class:`DXFBase`'s constructor is called, it is passed a HTTP response object. Pass it back to :meth:`authenticate` to have it automatically detect which actions are required. 

:type response: requests.Response 

 

:param authorization: ``Authorization`` header value. 

:type authorization: str 

 

:rtype: str 

:returns: Authentication token, if the registry supports bearer tokens. Otherwise ``None``, and HTTP Basic auth is used. 

""" 

if self._insecure: 

raise exceptions.DXFAuthInsecureError() 

if response is None: 

response = self._sessions[0].get(self._base_url, verify=self._tlsverify) 

# pylint: disable=no-member 

244 ↛ 245line 244 didn't jump to line 245, because the condition on line 244 was never true if response.status_code != requests.codes.unauthorized: 

raise exceptions.DXFUnexpectedStatusCodeError(response.status_code, 

requests.codes.unauthorized) 

parsed = www_authenticate.parse(response.headers['www-authenticate']) 

if username is not None and password is not None: 

headers = { 

'Authorization': 'Basic ' + base64.b64encode(_to_bytes_2and3(username + ':' + password)).decode('utf-8') 

} 

elif authorization is not None: 

headers = { 

'Authorization': authorization 

} 

else: 

headers = {} 

if 'bearer' in parsed: 

info = parsed['bearer'] 

if actions and self._repo: 

scope = 'repository:' + self._repo + ':' + ','.join(actions) 

else: 

scope = info['scope'] 

url_parts = list(urlparse.urlparse(info['realm'])) 

query = urlparse.parse_qs(url_parts[4]) 

query.update({ 

'service': info['service'], 

'scope': scope 

}) 

url_parts[4] = urlencode(query, True) 

url_parts[0] = 'https' 

if self._auth_host: 

url_parts[1] = self._auth_host 

auth_url = urlparse.urlunparse(url_parts) 

r = self._sessions[0].get(auth_url, headers=headers, verify=self._tlsverify) 

_raise_for_status(r) 

self.token = r.json()['token'] 

return self._token 

else: 

self._headers = headers 

 

def list_repos(self, batch_size=None, iterate=False): 

""" 

List all repositories in the registry. 

 

:param batch_size: Number of repository names to ask the server for at a time. 

:type batch_size: int 

 

:param iterate: Whether to return iterator over the names or a list of all the names. 

:type iterate: bool 

 

:rtype: list or iterator of strings 

:returns: Repository names. 

""" 

it = PaginatingResponse(self, '_base_request', 

'_catalog', 'repositories', 

params={'n': batch_size}) 

return it if iterate else list(it) 

 

def __enter__(self): 

assert self._sessions 

session = requests.Session() 

session.__enter__() 

self._sessions.insert(0, session) 

return self 

 

def __exit__(self, *args): 

assert len(self._sessions) > 1 

session = self._sessions.pop(0) 

return session.__exit__(*args) 

 

class DXF(DXFBase): 

""" 

Class for operating on a Docker v2 repositories. 

""" 

def __init__(self, host, repo, auth=None, insecure=False, auth_host=None, tlsverify=True): 

# pylint: disable=too-many-arguments 

""" 

:param host: Host name of registry. Can contain port numbers. e.g. ``registry-1.docker.io``, ``localhost:5000``. 

:type host: str 

 

:param repo: Name of the repository to access on the registry. Typically this is of the form ``username/reponame`` but for your own registries you don't actually have to stick to that. 

:type repo: str 

 

:param auth: Authentication function to be called whenever authentication to the registry is required. Receives the :class:`DXF` object and a HTTP response object. It should call :meth:`DXFBase.authenticate` with a username, password and ``response`` before it returns. 

:type auth: function(dxf_obj, response) 

 

:param insecure: Use HTTP instead of HTTPS (which is the default) when connecting to the registry. 

:type insecure: bool 

 

:param auth_host: Host to use for token authentication. If set, overrides host returned by then registry. 

:type auth_host: str 

 

:param tlsverify: When set to False do not verify TLS certificate 

:type tlsverify: bool 

""" 

super(DXF, self).__init__(host, auth, insecure, auth_host, tlsverify) 

self._repo = repo 

 

def _request(self, method, path, **kwargs): 

return super(DXF, self)._base_request(method, self._repo + '/' + path, **kwargs) 

 

def push_blob(self, 

filename=None, 

progress=None, 

data=None, digest=None, 

check_exists=True): 

# pylint: disable=too-many-arguments 

""" 

Upload a file to the registry and return its (SHA-256) hash. 

 

The registry is content-addressable so the file's content (aka blob) 

can be retrieved later by passing the hash to :meth:`pull_blob`. 

 

:param filename: File to upload. 

:type filename: str 

 

:param data: Data to upload if ``filename`` isn't given. The data is uploaded in chunks and you must also pass ``digest``. 

:type data: Generator or iterator 

 

:param digest: Hash of the data to be uploaded in ``data``, if specified. 

:type digest: str (hex-encoded SHA-256) 

 

:param progress: Optional function to call as the upload progresses. The function will be called with the hash of the file's content (or ``digest``), the blob just read from the file (or chunk from ``data``) and if ``filename`` is specified the total size of the file. 

:type progress: function(dgst, chunk, size) 

 

:param check_exists: Whether to check if a blob with the same hash already exists in the registry. If so, it won't be uploaded again. 

:type check_exists: bool 

 

:rtype: str 

:returns: Hash of file's content. 

""" 

if filename is None: 

dgst = digest 

else: 

dgst = hash_file(filename) 

if check_exists: 

try: 

self._request('head', 'blobs/sha256:' + dgst) 

return dgst 

except requests.exceptions.HTTPError as ex: 

# pylint: disable=no-member 

383 ↛ 384line 383 didn't jump to line 384, because the condition on line 383 was never true if ex.response.status_code != requests.codes.not_found: 

raise 

r = self._request('post', 'blobs/uploads/') 

upload_url = r.headers['Location'] 

url_parts = list(urlparse.urlparse(upload_url)) 

query = urlparse.parse_qs(url_parts[4]) 

query.update({'digest': 'sha256:' + dgst}) 

url_parts[4] = urlencode(query, True) 

url_parts[0] = 'http' if self._insecure else 'https' 

upload_url = urlparse.urlunparse(url_parts) 

if filename is None: 

data = _ReportingChunks(dgst, data, progress) if progress else data 

self._base_request('put', upload_url, data=data) 

else: 

with open(filename, 'rb') as f: 

data = _ReportingFile(dgst, f, progress) if progress else f 

self._base_request('put', upload_url, data=data) 

return dgst 

 

# pylint: disable=no-self-use 

def pull_blob(self, digest, size=False, chunk_size=None): 

""" 

Download a blob from the registry given the hash of its content. 

 

:param digest: Hash of the blob's content. 

:type digest: str 

 

:param size: Whether to return the size of the blob too. 

:type size: bool 

 

:param chunk_size: Number of bytes to download at a time. Defaults to 8192. 

:type chunk_size: int 

 

:rtype: iterator 

:returns: If ``size`` is falsey, a byte string iterator over the blob's content. If ``size`` is truthy, a tuple containing the iterator and the blob's size. 

""" 

if chunk_size is None: 

chunk_size = 8192 

r = self._request('get', 'blobs/sha256:' + digest, stream=True) 

class Chunks(object): 

# pylint: disable=too-few-public-methods 

def __iter__(self): 

sha256 = hashlib.sha256() 

for chunk in r.iter_content(chunk_size): 

sha256.update(chunk) 

yield chunk 

dgst = sha256.hexdigest() 

if dgst != digest: 

raise exceptions.DXFDigestMismatchError(dgst, digest) 

return (Chunks(), long(r.headers['content-length'])) if size else Chunks() 

 

def blob_size(self, digest): 

""" 

Return the size of a blob in the registry given the hash of its content. 

 

:param digest: Hash of the blob's content. 

:type digest: str 

 

:rtype: long 

:returns: Whether the blob exists. 

""" 

r = self._request('head', 'blobs/sha256:' + digest) 

return long(r.headers['content-length']) 

 

def del_blob(self, digest): 

""" 

Delete a blob from the registry given the hash of its content. 

 

:param digest: Hash of the blob's content. 

:type digest: str 

""" 

self._request('delete', 'blobs/sha256:' + digest) 

 

# For dtuf; highly unlikely anyone else will want this 

def make_manifest(self, *digests): 

layers = [{ 

'mediaType': 'application/octet-stream', 

'size': self.blob_size(dgst), 

'digest': 'sha256:' + dgst 

} for dgst in digests] 

return json.dumps({ 

'schemaVersion': 2, 

'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 

# V2 Schema 2 insists on a config dependency. We're just using the 

# registry as a blob store so to save us uploading extra blobs, 

# use the first layer. 

'config': { 

'mediaType': 'application/octet-stream', 

'size': layers[0]['size'], 

'digest': layers[0]['digest'] 

}, 

'layers': layers 

}, sort_keys=True) 

 

def set_manifest(self, alias, manifest_json): 

""" 

Give a name (alias) to a manifest. 

 

:param alias: Alias name 

:type alias: str 

 

:param manifest_json: A V2 Schema 2 manifest JSON string 

:type digests: list 

""" 

self._request('put', 

'manifests/' + alias, 

data=manifest_json, 

headers={'Content-Type': _schema2_mimetype}) 

 

def set_alias(self, alias, *digests): 

# pylint: disable=too-many-locals 

""" 

Give a name (alias) to a set of blobs. Each blob is specified by 

the hash of its content. 

 

:param alias: Alias name 

:type alias: str 

 

:param digests: List of blob hashes. 

:type digests: list of strings 

 

:rtype: str 

:returns: The registry manifest used to define the alias. You almost definitely won't need this. 

""" 

try: 

manifest_json = self.make_manifest(*digests) 

self.set_manifest(alias, manifest_json) 

return manifest_json 

except requests.exceptions.HTTPError as ex: 

# pylint: disable=no-member 

513 ↛ 514line 513 didn't jump to line 514, because the condition on line 513 was never true if ex.response.status_code != requests.codes.bad_request: 

raise 

manifest_json = self.make_unsigned_manifest(alias, *digests) 

signed_json = _sign_manifest(manifest_json) 

self._request('put', 'manifests/' + alias, data=signed_json) 

return signed_json 

 

def _get_manifest(self, alias): 

r = self._request('get', 

'manifests/' + alias, 

headers={'Accept': _schema2_mimetype + ', ' + 

_schema1_mimetype}) 

return r, r.content.decode('utf-8') 

 

def get_manifest(self, alias): 

""" 

Get the manifest for an alias 

 

:param alias: Alias name. 

:type alias: str 

 

:rtype: str 

:returns: The manifest as string(JSON) 

""" 

_, manifest = self._get_manifest(alias) 

return manifest 

 

def get_alias(self, 

alias=None, 

manifest=None, 

verify=True, 

sizes=False): 

""" 

Get the blob hashes assigned to an alias. 

 

:param alias: Alias name. You almost definitely will only need to pass this argument. 

:type alias: str 

 

:param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. 

:type manifest: str 

 

:param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). 

:type verify: bool 

 

:param sizes: Whether to return sizes of the blobs along with their hashes 

:type sizes: bool 

 

:rtype: list 

:returns: If ``sizes`` is falsey, a list of blob hashes (strings) which are assigned to the alias. If ``sizes`` is truthy, a list of (hash,size) tuples for each blob. 

""" 

if alias: 

r, manifest = self._get_manifest(alias) 

dcd = r.headers['docker-content-digest'] 

else: 

dcd = None 

parsed_manifest = json.loads(manifest) 

if parsed_manifest['schemaVersion'] == 1: 

dgsts = _verify_manifest(manifest, parsed_manifest, dcd, verify) 

if not sizes: 

return dgsts 

return [(dgst, self.blob_size(dgst)) for dgst in dgsts] 

else: 

if dcd: 

method, expected_dgst = dcd.split(':') 

577 ↛ 578line 577 didn't jump to line 578, because the condition on line 577 was never true if method != 'sha256': 

raise exceptions.DXFUnexpectedDigestMethodError(method, 'sha256') 

hasher = hashlib.new(method) 

hasher.update(r.content) 

dgst = hasher.hexdigest() 

582 ↛ 583line 582 didn't jump to line 583, because the condition on line 582 was never true if dgst != expected_dgst: 

raise exceptions.DXFDigestMismatchError(dgst, expected_dgst) 

 

r = [] 

for layer in parsed_manifest['layers']: 

method, dgst = layer['digest'].split(':') 

588 ↛ 589line 588 didn't jump to line 589, because the condition on line 588 was never true if method != 'sha256': 

raise exceptions.DXFUnexpectedDigestMethodError(method, 'sha256') 

r.append((dgst, layer['size']) if sizes else dgst) 

return r 

 

def _get_dcd(self, alias): 

'''get the Docker Content Digest ID 

 

:param str alias: alias name 

:rtype: str 

''' 

# https://docs.docker.com/registry/spec/api/#deleting-an-image 

# Note When deleting a manifest from a registry version 2.3 or later, 

# the following header must be used when HEAD or GET-ing the manifest 

# to obtain the correct digest to delete: 

# Accept: application/vnd.docker.distribution.manifest.v2+json 

return self._request( 

'head', 

'manifests/{}'.format(alias), 

headers={'Accept': _schema2_mimetype}, 

).headers.get('Docker-Content-Digest') 

 

def del_alias(self, alias): 

""" 

Delete an alias from the registry. The blobs it points to won't be deleted. Use :meth:`del_blob` for that. 

 

.. Note:: 

On private registry, garbage collection might need to be run manually; see: 

https://docs.docker.com/registry/garbage-collection/ 

 

:param alias: Alias name. 

:type alias: str 

 

:rtype: list 

:returns: A list of blob hashes (strings) which were assigned to the alias. 

""" 

dcd = self._get_dcd(alias) 

dgsts = self.get_alias(alias) 

self._request('delete', 'manifests/{}'.format(dcd)) 

return dgsts 

 

def list_aliases(self, batch_size=None, iterate=False): 

""" 

List all aliases defined in the repository. 

 

:param batch_size: Number of alias names to ask the server for at a time. 

:type batch_size: int 

 

:param iterate: Whether to return iterator over the names or a list of all the names. 

:type iterate: bool 

 

:rtype: list or iterator of strings 

:returns: Alias names. 

""" 

it = PaginatingResponse(self, '_request', 

'tags/list', 'tags', 

params={'n': batch_size}) 

return it if iterate else list(it) 

 

# v1 schema support functions below 

 

def make_unsigned_manifest(self, alias, *digests): 

return json.dumps({ 

'schemaVersion': 1, 

'name': self._repo, 

'tag': alias, 

'fsLayers': [{'blobSum': 'sha256:' + dgst} for dgst in digests], 

'history': [{'v1Compatibility': '{}'} for dgst in digests] 

}, sort_keys=True) 

 

_schema1_mimetype = 'application/vnd.docker.distribution.manifest.v1+json' 

 

def _urlsafe_b64encode(s): 

return base64.urlsafe_b64encode(_to_bytes_2and3(s)).rstrip(b'=').decode('utf-8') 

 

def _pad64(s): 

return s + b'=' * (-len(s) % 4) 

 

def _urlsafe_b64decode(s): 

return base64.urlsafe_b64decode(_pad64(_to_bytes_2and3(s))) 

 

def _import_key(expkey): 

670 ↛ 671line 670 didn't jump to line 671, because the condition on line 670 was never true if expkey['kty'] != 'EC': 

raise exceptions.DXFUnexpectedKeyTypeError(expkey['kty'], 'EC') 

672 ↛ 673line 672 didn't jump to line 673, because the condition on line 672 was never true if expkey['crv'] != 'P-256': 

raise exceptions.DXFUnexpectedKeyTypeError(expkey['crv'], 'P-256') 

return jwk.JWK(kty='EC', crv='P-256', x=expkey['x'], y=expkey['y']) 

 

def _sign_manifest(manifest_json): 

format_length = manifest_json.rfind('}') 

format_tail = manifest_json[format_length:] 

key = jwk.JWK.generate(kty='EC', crv='P-256') 

jwstoken = jws.JWS(manifest_json.encode('utf-8')) 

jkey = json.loads(key.export_public()) 

# Docker expects 32 bytes for x and y 

jkey['x'] = _urlsafe_b64encode(_urlsafe_b64decode(jkey['x']).rjust(32, b'\0')) 

jkey['y'] = _urlsafe_b64encode(_urlsafe_b64decode(jkey['y']).rjust(32, b'\0')) 

jwstoken.add_signature(key, None, { 

'formatLength': format_length, 

'formatTail': _urlsafe_b64encode(format_tail) 

}, { 

'jwk': jkey, 

'alg': 'ES256' 

}) 

return manifest_json[:format_length] + \ 

', "signatures": [' + jwstoken.serialize() + ']' + \ 

format_tail 

 

def _verify_manifest(content, 

manifest, 

content_digest=None, 

verify=True): 

# pylint: disable=too-many-locals,too-many-branches 

 

# Adapted from https://github.com/joyent/node-docker-registry-client 

 

if verify or ('signatures' in manifest): 

signatures = [] 

for sig in manifest['signatures']: 

protected64 = sig['protected'] 

protected = _urlsafe_b64decode(protected64).decode('utf-8') 

protected_header = json.loads(protected) 

 

format_length = protected_header['formatLength'] 

format_tail64 = protected_header['formatTail'] 

format_tail = _urlsafe_b64decode(format_tail64).decode('utf-8') 

 

alg = sig['header']['alg'] 

716 ↛ 717line 716 didn't jump to line 717, because the condition on line 716 was never true if alg.lower() == 'none': 

raise exceptions.DXFDisallowedSignatureAlgorithmError('none') 

718 ↛ 719line 718 didn't jump to line 719, because the condition on line 718 was never true if sig['header'].get('chain'): 

raise exceptions.DXFSignatureChainNotImplementedError() 

 

signatures.append({ 

'alg': alg, 

'signature': sig['signature'], 

'protected64': protected64, 

'key': _import_key(sig['header']['jwk']), 

'format_length': format_length, 

'format_tail': format_tail 

}) 

 

payload = content[:signatures[0]['format_length']] + \ 

signatures[0]['format_tail'] 

payload64 = _urlsafe_b64encode(payload) 

else: 

payload = content 

 

if content_digest: 

method, expected_dgst = content_digest.split(':') 

738 ↛ 739line 738 didn't jump to line 739, because the condition on line 738 was never true if method != 'sha256': 

raise exceptions.DXFUnexpectedDigestMethodError(method, 'sha256') 

hasher = hashlib.new(method) 

hasher.update(payload.encode('utf-8')) 

dgst = hasher.hexdigest() 

743 ↛ 744line 743 didn't jump to line 744, because the condition on line 743 was never true if dgst != expected_dgst: 

raise exceptions.DXFDigestMismatchError(dgst, expected_dgst) 

 

if verify: 

for sig in signatures: 

jwstoken = jws.JWS() 

jwstoken.deserialize(json.dumps({ 

'payload': payload64, 

'protected': sig['protected64'], 

'signature': sig['signature'] 

}), sig['key'], sig['alg']) 

 

dgsts = [] 

for layer in manifest['fsLayers']: 

method, dgst = layer['blobSum'].split(':') 

758 ↛ 759line 758 didn't jump to line 759, because the condition on line 758 was never true if method != 'sha256': 

raise exceptions.DXFUnexpectedDigestMethodError(method, 'sha256') 

dgsts.append(dgst) 

return dgsts