Handle private docker registry auth

This adds support for private docker registries, by adding
an optional `registryAuth` field in the CreateFunctionRequest.
Auth must be passed as base64-encoded basic auth, similar to
how done in Docker file store credentials (~/.docker/config.json).
Credentials are then passed to swarm at service creation.
This commit is contained in:
Sebastien Guilloux
2017-05-30 15:32:05 +02:00
committed by Alex Ellis
parent 6f68b72c21
commit 9e711b3b5d
5 changed files with 222 additions and 0 deletions

View File

@ -5,19 +5,24 @@ package handlers
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"io/ioutil"
"github.com/alexellis/faas/gateway/metrics"
"github.com/alexellis/faas/gateway/requests"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/docker/docker/registry"
"github.com/prometheus/client_golang/prometheus"
io_prometheus_client "github.com/prometheus/client_model/go"
)
@ -160,6 +165,16 @@ func MakeNewFunctionHandler(metricsOptions metrics.MetricOptions, c *client.Clie
// w.WriteHeader(http.StatusNotImplemented)
options := types.ServiceCreateOptions{}
if len(request.RegistryAuth) > 0 {
auth, err := BuildEncodedAuthConfig(request.RegistryAuth, request.Image)
if err != nil {
log.Println("Error while building registry auth configuration", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid registry auth"))
return
}
options.EncodedRegistryAuth = auth
}
spec := makeSpec(&request)
response, err := c.ServiceCreate(context.Background(), spec, options)
@ -208,3 +223,43 @@ func makeSpec(request *requests.CreateFunctionRequest) swarm.ServiceSpec {
return spec
}
func BuildEncodedAuthConfig(basicAuthB64 string, dockerImage string) (string, error) {
// extract registry server address
distributionRef, err := reference.ParseNormalizedNamed(dockerImage)
if err != nil {
return "", err
}
repoInfo, err := registry.ParseRepositoryInfo(distributionRef)
if err != nil {
return "", err
}
// extract registry user & password
user, password, err := userPasswordFromBasicAuth(basicAuthB64)
if err != nil {
return "", err
}
// build encoded registry auth config
buf, err := json.Marshal(types.AuthConfig{
Username: user,
Password: password,
ServerAddress: repoInfo.Index.Name,
})
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buf), nil
}
func userPasswordFromBasicAuth(basicAuthB64 string) (string, string, error) {
c, err := base64.StdEncoding.DecodeString(basicAuthB64)
if err != nil {
return "", "", err
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return "", "", errors.New("Invalid basic auth")
}
return cs[:s], cs[s+1:], nil
}

View File

@ -18,6 +18,11 @@ type CreateFunctionRequest struct {
// EnvVars provides overrides for functions.
EnvVars map[string]string `json:"envVars"`
// RegistryAuth is the registry authentication (optional)
// in the same encoded format as Docker native credentials
// (see ~/.docker/config.json)
RegistryAuth string `json:"registryAuth,omitempty"`
}
type DeleteFunctionRequest struct {

View File

@ -0,0 +1,73 @@
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"github.com/alexellis/faas/gateway/handlers"
"github.com/docker/docker/api/types"
)
func TestBuildEncodedAuthConfig(t *testing.T) {
// custom repository with valid data
assertValidEncodedAuthConfig(t, "user", "password", "my.repository.com/user/imagename", "my.repository.com")
assertValidEncodedAuthConfig(t, "user", "weird:password:", "my.repository.com/user/imagename", "my.repository.com")
assertValidEncodedAuthConfig(t, "userWithNoPassword", "", "my.repository.com/user/imagename", "my.repository.com")
assertValidEncodedAuthConfig(t, "", "", "my.repository.com/user/imagename", "my.repository.com")
// docker hub default repository
assertValidEncodedAuthConfig(t, "user", "password", "user/imagename", "docker.io")
assertValidEncodedAuthConfig(t, "", "", "user/imagename", "docker.io")
// invalid base64 basic auth
assertEncodedAuthError(t, "invalidBasicAuth", "my.repository.com/user/imagename")
// invalid docker image name
assertEncodedAuthError(t, b64BasicAuth("user", "password"), "")
assertEncodedAuthError(t, b64BasicAuth("user", "password"), "invalid name")
}
func assertValidEncodedAuthConfig(t *testing.T, user, password, imageName, expectedRegistryHost string) {
encodedAuthConfig, err := handlers.BuildEncodedAuthConfig(b64BasicAuth(user, password), imageName)
if err != nil {
t.Log("Unexpected error while building auth config with correct values")
t.Fail()
}
authConfig := &types.AuthConfig{}
authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuthConfig))
if err := json.NewDecoder(authJSON).Decode(authConfig); err != nil {
t.Log("Invalid encoded auth", err)
t.Fail()
}
if user != authConfig.Username {
t.Log("Auth config username mismatch", user, authConfig.Username)
t.Fail()
}
if password != authConfig.Password {
t.Log("Auth config password mismatch", password, authConfig.Password)
t.Fail()
}
if expectedRegistryHost != authConfig.ServerAddress {
t.Log("Auth config registry server address mismatch", expectedRegistryHost, authConfig.ServerAddress)
t.Fail()
}
}
func assertEncodedAuthError(t *testing.T, b64BasicAuth, imageName string) {
_, err := handlers.BuildEncodedAuthConfig(b64BasicAuth, imageName)
if err == nil {
t.Log("Expected an error to be returned")
t.Fail()
}
}
func b64BasicAuth(user, password string) string {
return base64.StdEncoding.EncodeToString([]byte(user + ":" + password))
}