1

I want to retrieve a list of images from Google Cloud Docker Registry via https://gcr.io http API.

I found a way to do it from command line like this:

curl -u _token:$(gcloud auth print-access-token) https://gcr.io/v2/{project}/{repo}/tags/list

But I want to do it in programmatically in Python. Here is what I tried so far:

The below works, but I can't find a way to retrieve authentication token without calling gcloud shell cmd.

import requests
import subprocess

command = "gcloud auth print-access-token"
pswd= subprocess.check_output(command, shell=True).decode().strip()

repo = "repo"
project = "myproject"
user = "_token"
url = "https://gcr.io/v2/{project}/{repo}/tags/list".format(project=project, repo=repo)
r = requests.get(url, auth=(user, pswd))
print (r.status_code, r.headers['content-type'], r.encoding, r.text)

In addition, I have also tried to perform the request using authenticated httplib2:

import httplib2
from oauth2client.client import GoogleCredentials
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default()

scopes = "https://www.googleapis.com/auth/cloud-platform"

credentials = credentials.create_scoped(scopes)

http = credentials.authorize(http)
print (http.request("https://gcr.io/v2/healthshield-dev/dl/tags/list"))

The result is b'{"errors":[{"code":"UNAUTHORIZED","message":"Not Authorized."}]}'

Can anybody share with me his experience with this?

Ark-kun
  • 6,358
  • 2
  • 34
  • 70
worroc
  • 117
  • 8

1 Answers1

0

I was able to accomplish what you need to do here, but in Java, should be fairly simple to translate to Python. This is what I did:

  1. Use the Google OAuth2 API Client Library for Java (https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests) to get the token used to auth for the gcr.io/v2 request. Section "Other", I used a jsonKeyFile setup for a Service Account.

Python Client Library -> https://developers.google.com/api-client-library/python/guide/aaa_oauth

        GoogleCredential credential = GoogleCredential.fromStream(keyFileInputStream).createScoped(Collections.singleton(ContainerScopes.CLOUD_PLATFORM));

        credential.refreshToken();
        String token = credential.getAccessToken();
  1. Now with the token, just make a GET request to https://gcr.io/v2/xxxx/tags/list

Note that with curl -u you are passing the credentials as _token:value so you will need to encode it into a Basic authentication header that you would need to set in the request. This is what I did (kinda):

String encoding = Base64Encoder.encode("_token:"+token);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encoding);

Hope this helps.

evargas
  • 71
  • 1
  • 1
  • 6