Files
Heimdall/scripts/ci/dockerhub-tag-digest.py
T

66 lines
3.0 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Resolve the canonical digest for an immutable Docker Hub repository tag."""
import json
import os
import re
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
def endpoint(name, default, path):
value = os.environ.get(name, default).rstrip('/')
if not value.startswith('https://') or '@' in value:
raise SystemExit('Registry endpoint must be HTTPS')
return value + path
def main():
if len(sys.argv) != 3:
raise SystemExit('usage: dockerhub-tag-digest.py REPOSITORY IMMUTABLE_TAG')
repository, tag = sys.argv[1:]
if not re.fullmatch(r'[a-z0-9._-]+/[a-z0-9._-]+', repository):
raise SystemExit('Invalid Docker Hub repository')
if not re.fullmatch(r'sha-[0-9a-f]{40}', tag):
raise SystemExit('Expected an immutable full-commit image tag')
username = os.environ.get('DOCKERHUB_USERNAME', '')
password = os.environ.get('DOCKERHUB_TOKEN', '')
if not username or not password:
raise SystemExit('Docker Hub credentials are required to resolve image digest')
token_url = endpoint('DOCKER_REGISTRY_TOKEN_URL', 'https://auth.docker.io',
'/token?' + urlencode({'service': 'registry.docker.io',
'scope': 'repository:' + repository + ':pull'}))
registry_url = endpoint('DOCKER_REGISTRY_URL', 'https://registry-1.docker.io',
'/v2/' + repository + '/manifests/' + tag)
import base64
credentials = base64.b64encode((username + ':' + password).encode()).decode('ascii')
try:
token_request = Request(token_url, headers={'Authorization': 'Basic ' + credentials,
'Accept': 'application/json'})
with urlopen(token_request, timeout=30) as response:
token_data = json.load(response)
bearer = token_data.get('token') or token_data.get('access_token')
if not isinstance(bearer, str) or not bearer:
raise SystemExit('Docker Hub did not return a registry bearer token')
manifest_request = Request(registry_url, headers={
'Authorization': 'Bearer ' + bearer,
'Accept': ', '.join([
'application/vnd.oci.image.index.v1+json',
'application/vnd.docker.distribution.manifest.list.v2+json',
'application/vnd.oci.image.manifest.v1+json',
'application/vnd.docker.distribution.manifest.v2+json',
]),
})
with urlopen(manifest_request, timeout=30) as response:
digest = response.headers.get('Docker-Content-Digest', '')
except (HTTPError, URLError, TimeoutError, OSError, ValueError):
raise SystemExit('Unable to resolve immutable Docker Hub image digest')
if not re.fullmatch(r'sha256:[0-9a-f]{64}', digest):
raise SystemExit('Docker Hub returned an invalid image digest')
print(digest)
if __name__ == '__main__':
main()