authn

package
v0.20.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2024 License: Apache-2.0 Imports: 14 Imported by: 3

README

authn

GoDoc

This README outlines how we acquire and use credentials when interacting with a registry.

As much as possible, we attempt to emulate docker's authentication behavior and configuration so that this library "just works" if you've already configured credentials that work with docker; however, when things don't work, a basic understanding of what's going on can help with debugging.

The official documentation for how authentication with docker works is (reasonably) scattered across several different sites and GitHub repositories, so we've tried to summarize the relevant bits here.

tl;dr for consumers of this package

By default, pkg/v1/remote uses Anonymous credentials (i.e. none), which for most registries will only allow read access to public images.

To use the credentials found in your Docker config file, you can use the DefaultKeychain, e.g.:

package main

import (
	"fmt"

	"github.com/schidstorm/go-containerregistry/pkg/authn"
	"github.com/schidstorm/go-containerregistry/pkg/name"
	"github.com/schidstorm/go-containerregistry/pkg/v1/remote"
)

func main() {
	ref, err := name.ParseReference("registry.example.com/private/repo")
	if err != nil {
		panic(err)
	}

	// Fetch the manifest using default credentials.
	img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain))
	if err != nil {
		panic(err)
	}

	// Prints the digest of registry.example.com/private/repo
	fmt.Println(img.Digest)
}

The DefaultKeychain will use credentials as described in your Docker config file -- usually ~/.docker/config.json, or %USERPROFILE%\.docker\config.json on Windows -- or the location described by the DOCKER_CONFIG environment variable, if set.

If those are not found, DefaultKeychain will look for credentials configured using Podman's expectation that these are found in ${XDG_RUNTIME_DIR}/containers/auth.json.

See below for more information about what is configured in this file.

Emulating Cloud Provider Credential Helpers

pkg/v1/google.Keychain provides a Keychain implementation that emulates docker-credential-gcr to find credentials in the environment. See google.NewEnvAuthenticator and google.NewGcloudAuthenticator for more information.

To emulate other credential helpers without requiring them to be available as executables, NewKeychainFromHelper provides an adapter that takes a Go implementation satisfying a subset of the credentials.Helper interface, and makes it available as a Keychain.

This means that you can emulate, for example, Amazon ECR's docker-credential-ecr-login credential helper using the same implementation:

import (
	ecr "github.com/awslabs/amazon-ecr-credential-helper/ecr-login"
	"github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api"

	"github.com/schidstorm/go-containerregistry/pkg/authn"
	"github.com/schidstorm/go-containerregistry/pkg/v1/remote"
)

func main() {
	// ...
	ecrHelper := ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}}
	img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.NewKeychainFromHelper(ecrHelper)))
	if err != nil {
		panic(err)
	}
	// ...
}

Likewise, you can emulate Azure's ACR docker-credential-acr-env credential helper:

import (
	"github.com/chrismellard/docker-credential-acr-env/pkg/credhelper"

	"github.com/schidstorm/go-containerregistry/pkg/authn"
	"github.com/schidstorm/go-containerregistry/pkg/v1/remote"
)

func main() {
	// ...
	acrHelper := credhelper.NewACRCredentialsHelper()
	img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.NewKeychainFromHelper(acrHelper)))
	if err != nil {
		panic(err)
	}
	// ...
}

Using Multiple Keychains

NewMultiKeychain allows you to specify multiple Keychain implementations, which will be checked in order when credentials are needed.

For example:

kc := authn.NewMultiKeychain(
    authn.DefaultKeychain,
    google.Keychain,
    authn.NewKeychainFromHelper(ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}}),
    authn.NewKeychainFromHelper(acr.ACRCredHelper{}),
)

This multi-keychain will:

  • first check for credentials found in the Docker config file, as describe above, then
  • check for GCP credentials available in the environment, as described above, then
  • check for ECR credentials by emulating the ECR credential helper, then
  • check for ACR credentials by emulating the ACR credential helper.

If any keychain implementation is able to provide credentials for the request, they will be used, and further keychain implementations will not be consulted.

If no implementations are able to provide credentials, Anonymous credentials will be used.

Docker Config Auth

What follows attempts to gather useful information about Docker's config.json and make it available in one place.

If you have questions, please file an issue.

Plaintext

The config file is where your credentials are stored when you invoke docker login, e.g. the contents may look something like this:

{
	"auths": {
		"registry.example.com": {
			"auth": "QXp1cmVEaWFtb25kOmh1bnRlcjI="
		}
	}
}

The auths map has an entry per registry, and the auth field contains your username and password encoded as HTTP 'Basic' Auth.

NOTE: This means that your credentials are stored in plaintext:

$ echo "QXp1cmVEaWFtb25kOmh1bnRlcjI=" | base64 -d
AzureDiamond:hunter2

For what it's worth, this config file is equivalent to:

{
	"auths": {
		"registry.example.com": {
			"username": "AzureDiamond",
			"password": "hunter2"
		}
	}
}

... which is useful to know if e.g. your CI system provides you a registry username and password via environment variables and you want to populate this file manually without invoking docker login.

Helpers

If you log in like this, docker will warn you that you should use a credential helper, and you should!

To configure a global credential helper:

{
	"credsStore": "osxkeychain"
}

To configure a per-registry credential helper:

{
	"credHelpers": {
		"gcr.io": "gcr"
	}
}

We use github.com/docker/cli/cli/config.Load to parse the config file and invoke any necessary credential helpers. This handles the logic of taking a ConfigFile + registry domain and producing an AuthConfig, which determines how we authenticate to the registry.

Credential Helpers

The credential helper protocol allows you to configure a binary that supplies credentials for the registry, rather than hard-coding them in the config file.

The protocol has several verbs, but the one we most care about is get.

For example, using the following config file:

{
	"credHelpers": {
		"gcr.io": "gcr",
		"eu.gcr.io": "gcr"
	}
}

To acquire credentials for gcr.io, we look in the credHelpers map to find the credential helper for gcr.io is gcr. By appending that value to docker-credential-, we can get the name of the binary we need to use.

For this example, that's docker-credential-gcr, which must be on our $PATH. We'll then invoke that binary to get credentials:

$ echo "gcr.io" | docker-credential-gcr get
{"Username":"_token","Secret":"<long access token>"}

You can configure the same credential helper for multiple registries, which is why we need to pass the domain in via STDIN, e.g. if we were trying to access eu.gcr.io, we'd do this instead:

$ echo "eu.gcr.io" | docker-credential-gcr get
{"Username":"_token","Secret":"<long access token>"}
Debugging credential helpers

If a credential helper is configured but doesn't seem to be working, it can be challenging to debug. Implementing a fake credential helper lets you poke around to make it easier to see where the failure is happening.

This "implements" a credential helper with hard-coded values:

#!/usr/bin/env bash
echo '{"Username":"<token>","Secret":"hunter2"}'

This implements a credential helper that prints the output of docker-credential-gcr to both stderr and whatever called it, which allows you to snoop on another credential helper:

#!/usr/bin/env bash
docker-credential-gcr $@ | tee >(cat 1>&2)

Put those files somewhere on your path, naming them e.g. docker-credential-hardcoded and docker-credential-tee, then modify the config file to use them:

{
	"credHelpers": {
		"gcr.io": "tee",
		"eu.gcr.io": "hardcoded"
	}
}

The docker-credential-tee trick works with both crane and docker:

$ crane manifest gcr.io/google-containers/pause > /dev/null
{"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":"<redacted>"}

$ docker pull gcr.io/google-containers/pause
Using default tag: latest
{"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":"<redacted>"}
latest: Pulling from google-containers/pause
a3ed95caeb02: Pull complete
4964c72cd024: Pull complete
Digest: sha256:a78c2d6208eff9b672de43f880093100050983047b7b0afe0217d3656e1b0d5f
Status: Downloaded newer image for gcr.io/google-containers/pause:latest
gcr.io/google-containers/pause:latest

The Registry

There are two methods for authenticating against a registry: token and oauth2.

Both methods are used to acquire an opaque Bearer token (or RegistryToken) to use in the Authorization header. The registry will return a 401 Unauthorized during the version check (or during normal operations) with Www-Authenticate challenge indicating how to proceed.

Token

If we get back an AuthConfig containing a Username/Password or Auth, we'll use the token method for authentication:

basic

OAuth 2

If we get back an AuthConfig containing an IdentityToken we'll use the oauth2 method for authentication:

oauth

This happens when a credential helper returns a response with the Username set to <token> (no, that's not a placeholder, the literal string "<token>"). It is unclear why: moby/moby#36926.

We only support the oauth2 grant_type for refresh_token (#629), since it's impossible to determine from the registry response whether we should use oauth, and the token method for authentication is widely implemented by registries.

Documentation

Overview

Package authn defines different methods of authentication for talking to a container registry.

Index

Constants

View Source
const (
	// DefaultAuthKey is the key used for dockerhub in config files, which
	// is hardcoded for historical reasons.
	DefaultAuthKey = "https://" + name.DefaultRegistry + "/v1/"
)

Variables

View Source
var (
	// DefaultKeychain implements Keychain by interpreting the docker config file.
	DefaultKeychain = &defaultKeychain{}
)

Functions

This section is empty.

Types

type AuthConfig

type AuthConfig struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Auth     string `json:"auth,omitempty"`

	// IdentityToken is used to authenticate the user and get
	// an access token for the registry.
	IdentityToken string `json:"identitytoken,omitempty"`

	// RegistryToken is a bearer token to be sent to a registry
	RegistryToken string `json:"registrytoken,omitempty"`
}

AuthConfig contains authorization information for connecting to a Registry Inlined what we use from github.com/docker/cli/cli/config/types

func Authorization

func Authorization(ctx context.Context, authn Authenticator) (*AuthConfig, error)

Authorization calls AuthorizationContext with ctx if the given Authenticator implements ContextAuthenticator, otherwise it calls Resolve with the given Resource.

func (AuthConfig) MarshalJSON

func (a AuthConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*AuthConfig) UnmarshalJSON

func (a *AuthConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type Authenticator

type Authenticator interface {
	// Authorization returns the value to use in an http transport's Authorization header.
	Authorization() (*AuthConfig, error)
}

Authenticator is used to authenticate Docker transports.

var Anonymous Authenticator = &anonymous{}

Anonymous is a singleton Authenticator for providing anonymous auth.

func FromConfig

func FromConfig(cfg AuthConfig) Authenticator

FromConfig returns an Authenticator that just returns the given AuthConfig.

func Resolve

func Resolve(ctx context.Context, keychain Keychain, target Resource) (Authenticator, error)

Resolve calls ResolveContext with ctx if the given Keychain implements ContextKeychain, otherwise it calls Resolve with the given Resource.

type Basic

type Basic struct {
	Username string
	Password string
}

Basic implements Authenticator for basic authentication.

func (*Basic) Authorization

func (b *Basic) Authorization() (*AuthConfig, error)

Authorization implements Authenticator.

type Bearer

type Bearer struct {
	Token string `json:"token"`
}

Bearer implements Authenticator for bearer authentication.

func (*Bearer) Authorization

func (b *Bearer) Authorization() (*AuthConfig, error)

Authorization implements Authenticator.

type ContextAuthenticator

type ContextAuthenticator interface {
	// Authorization returns the value to use in an http transport's Authorization header.
	AuthorizationContext(context.Context) (*AuthConfig, error)
}

ContextAuthenticator is like Authenticator, but allows for context to be passed in.

type ContextKeychain

type ContextKeychain interface {
	ResolveContext(context.Context, Resource) (Authenticator, error)
}

ContextKeychain is like Keychain, but allows for context to be passed in.

type Helper

type Helper interface {
	Get(serverURL string) (string, string, error)
}

Helper is a subset of the Docker credential helper credentials.Helper interface used by NewKeychainFromHelper.

See: https://pkg.go.dev/github.com/docker/docker-credential-helpers/credentials#Helper

type Keychain

type Keychain interface {
	// Resolve looks up the most appropriate credential for the specified target.
	Resolve(Resource) (Authenticator, error)
}

Keychain is an interface for resolving an image reference to a credential.

func NewKeychainFromHelper

func NewKeychainFromHelper(h Helper) Keychain

NewKeychainFromHelper returns a Keychain based on a Docker credential helper implementation that can Get username and password credentials for a given server URL.

func NewMultiKeychain

func NewMultiKeychain(kcs ...Keychain) Keychain

NewMultiKeychain composes a list of keychains into one new keychain.

func RefreshingKeychain

func RefreshingKeychain(inner Keychain, duration time.Duration) Keychain

type Resource

type Resource interface {
	// String returns the full string representation of the target, e.g.
	// gcr.io/my-project or just gcr.io.
	String() string

	// RegistryStr returns just the registry portion of the target, e.g. for
	// gcr.io/my-project, this should just return gcr.io. This is needed to
	// pull out an appropriate hostname.
	RegistryStr() string
}

Resource represents a registry or repository that can be authenticated against.

Directories

Path Synopsis
Package github provides a keychain for the GitHub Container Registry.
Package github provides a keychain for the GitHub Container Registry.
k8schain module
kubernetes module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL