From 7ca66e3cfc60edc16f1ba6a7cc87bc4cda5166e9 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 3 Jun 2022 13:58:33 +0200 Subject: [PATCH] api: add registry.EncodeAuthConfig Based on EncodeAuthToBase64 in docker/cli; https://github.com/docker/cli/blob/1f4111d2bf3dbd9b6f5252c551621af84401b691/cli/command/registry.go#L30-L37 Signed-off-by: Sebastiaan van Stijn --- api/types/registry/authconfig.go | 13 +++++++++++++ api/types/registry/authconfig_test.go | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/api/types/registry/authconfig.go b/api/types/registry/authconfig.go index 3389196d71..97a924e374 100644 --- a/api/types/registry/authconfig.go +++ b/api/types/registry/authconfig.go @@ -33,6 +33,19 @@ type AuthConfig struct { RegistryToken string `json:"registrytoken,omitempty"` } +// EncodeAuthConfig serializes the auth configuration as a base64url encoded +// RFC4648, section 5) JSON string for sending through the X-Registry-Auth header. +// +// For details on base64url encoding, see: +// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 +func EncodeAuthConfig(authConfig AuthConfig) (string, error) { + buf, err := json.Marshal(authConfig) + if err != nil { + return "", errInvalidParameter{err} + } + return base64.URLEncoding.EncodeToString(buf), nil +} + // DecodeAuthConfig decodes base64url encoded (RFC4648, section 5) JSON // authentication information as sent through the X-Registry-Auth header. // diff --git a/api/types/registry/authconfig_test.go b/api/types/registry/authconfig_test.go index 6070977c17..9fdea080af 100644 --- a/api/types/registry/authconfig_test.go +++ b/api/types/registry/authconfig_test.go @@ -51,3 +51,9 @@ func TestDecodeAuthConfigBody(t *testing.T) { assert.NilError(t, err) assert.Equal(t, *token, expected) } + +func TestEncodeAuthConfig(t *testing.T) { + token, err := EncodeAuthConfig(expected) + assert.NilError(t, err) + assert.Equal(t, token, encoded) +}