mirror of https://github.com/knative/func.git
Basic auth (#2242)
* feat: host builder basic auth * update tests * mark oci basic auth flags hidden * cleanup - Remove debug statements - Fix test race - Update licenses * spelling and linting errors
This commit is contained in:
parent
9daaea37be
commit
9beea04064
62
cmd/build.go
62
cmd/build.go
|
@ -1,6 +1,7 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
@ -26,9 +27,10 @@ NAME
|
|||
{{rootCmdUse}} build - Build a function container locally without deploying
|
||||
|
||||
SYNOPSIS
|
||||
{{rootCmdUse}} build [-r|--registry] [--builder] [--builder-image] [--push]
|
||||
{{rootCmdUse}} build [-r|--registry] [--builder] [--builder-image]
|
||||
[--push] [--username] [--password] [--token]
|
||||
[--platform] [-p|--path] [-c|--confirm] [-v|--verbose]
|
||||
[--build-timestamp] [--registry-insecure]
|
||||
[--build-timestamp] [--registry-insecure]
|
||||
|
||||
DESCRIPTION
|
||||
|
||||
|
@ -66,7 +68,9 @@ EXAMPLES
|
|||
|
||||
`,
|
||||
SuggestFor: []string{"biuld", "buidl", "built"},
|
||||
PreRunE: bindEnv("image", "path", "builder", "registry", "confirm", "push", "builder-image", "platform", "verbose", "build-timestamp", "registry-insecure"),
|
||||
PreRunE: bindEnv("image", "path", "builder", "registry", "confirm",
|
||||
"push", "builder-image", "platform", "verbose", "build-timestamp",
|
||||
"registry-insecure", "username", "password", "token"),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runBuild(cmd, args, newClient)
|
||||
},
|
||||
|
@ -108,15 +112,31 @@ EXAMPLES
|
|||
"Specify a custom builder image for use by the builder other than its default. ($FUNC_BUILDER_IMAGE)")
|
||||
cmd.Flags().StringP("image", "i", f.Image,
|
||||
"Full image name in the form [registry]/[namespace]/[name]:[tag] (optional). This option takes precedence over --registry ($FUNC_IMAGE)")
|
||||
cmd.Flags().BoolP("build-timestamp", "", false, "Use the actual time as the created time for the docker image. This is only useful for buildpacks builder.")
|
||||
|
||||
// Static Flags:
|
||||
// Options which have static defaults only (not globally configurable nor
|
||||
// persisted with the function)
|
||||
// Options which are either empty or have static defaults only (not
|
||||
// globally configurable nor persisted with the function)
|
||||
cmd.Flags().BoolP("push", "u", false,
|
||||
"Attempt to push the function image to the configured registry after being successfully built")
|
||||
cmd.Flags().StringP("platform", "", "",
|
||||
"Optionally specify a target platform, for example \"linux/amd64\" when using the s2i build strategy")
|
||||
cmd.Flags().StringP("username", "", "",
|
||||
"Username to use when pushing to the registry.")
|
||||
cmd.Flags().StringP("password", "", "",
|
||||
"Password to use when pushing to the registry.")
|
||||
cmd.Flags().StringP("token", "", "",
|
||||
"Token to use when pushing to the registry.")
|
||||
cmd.Flags().BoolP("build-timestamp", "", false, "Use the actual time as the created time for the docker image. This is only useful for buildpacks builder.")
|
||||
|
||||
// Temporarily Hidden Basic Auth Flags
|
||||
// Username, Password and Token flags, which plumb through basic auth, are
|
||||
// currently only available on the experimental "host" builder, which is
|
||||
// itself behind a feature flag FUNC_ENABLE_HOST_BUILDER. So set these
|
||||
// flags to hidden until it's out of preview and they are plumbed through
|
||||
// the docker pusher as well.
|
||||
_ = cmd.Flags().MarkHidden("username")
|
||||
_ = cmd.Flags().MarkHidden("password")
|
||||
_ = cmd.Flags().MarkHidden("token")
|
||||
|
||||
// Oft-shared flags:
|
||||
addConfirmFlag(cmd, cfg.Confirm)
|
||||
|
@ -142,10 +162,10 @@ func runBuild(cmd *cobra.Command, _ []string, newClient ClientFactory) (err erro
|
|||
if err = config.CreatePaths(); err != nil { // for possible auth.json usage
|
||||
return
|
||||
}
|
||||
if cfg, err = newBuildConfig().Prompt(); err != nil {
|
||||
if cfg, err = newBuildConfig().Prompt(); err != nil { // gather values into a single instruction set
|
||||
return
|
||||
}
|
||||
if err = cfg.Validate(); err != nil {
|
||||
if err = cfg.Validate(); err != nil { // Perform any pre-validation
|
||||
return
|
||||
}
|
||||
if f, err = fn.NewFunction(cfg.Path); err != nil {
|
||||
|
@ -156,6 +176,8 @@ func runBuild(cmd *cobra.Command, _ []string, newClient ClientFactory) (err erro
|
|||
}
|
||||
f = cfg.Configure(f) // Updates f at path to include build request values
|
||||
|
||||
cmd.SetContext(cfg.WithValues(cmd.Context())) // Some optional settings are passed via context
|
||||
|
||||
// Client
|
||||
clientOptions, err := cfg.clientOptions()
|
||||
if err != nil {
|
||||
|
@ -185,6 +207,16 @@ func runBuild(cmd *cobra.Command, _ []string, newClient ClientFactory) (err erro
|
|||
return f.Stamp()
|
||||
}
|
||||
|
||||
// WithValues returns a context populated with values from the build config
|
||||
// which are provided to the system via the context.
|
||||
func (c buildConfig) WithValues(ctx context.Context) context.Context {
|
||||
// Push
|
||||
ctx = context.WithValue(ctx, fn.PushUsernameKey{}, c.Username)
|
||||
ctx = context.WithValue(ctx, fn.PushPasswordKey{}, c.Password)
|
||||
ctx = context.WithValue(ctx, fn.PushTokenKey{}, c.Token)
|
||||
return ctx
|
||||
}
|
||||
|
||||
type buildConfig struct {
|
||||
// Globals (builder, confirm, registry, verbose)
|
||||
config.Global
|
||||
|
@ -207,6 +239,17 @@ type buildConfig struct {
|
|||
// Push the resulting image to the registry after building.
|
||||
Push bool
|
||||
|
||||
// Username when specifying optional basic auth.
|
||||
Username string
|
||||
|
||||
// Password when using optional basic auth. Should be provided along
|
||||
// with Username.
|
||||
Password string
|
||||
|
||||
// Token when performing basic auth using a bearer token. Should be
|
||||
// exclusive with Username and Password.
|
||||
Token string
|
||||
|
||||
// Build with the current timestamp as the created time for docker image.
|
||||
// This is only useful for buildpacks builder.
|
||||
WithTimestamp bool
|
||||
|
@ -227,6 +270,9 @@ func newBuildConfig() buildConfig {
|
|||
Path: viper.GetString("path"),
|
||||
Platform: viper.GetString("platform"),
|
||||
Push: viper.GetBool("push"),
|
||||
Username: viper.GetString("username"),
|
||||
Password: viper.GetString("password"),
|
||||
Token: viper.GetString("token"),
|
||||
WithTimestamp: viper.GetBool("build-timestamp"),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -88,6 +88,12 @@ func TestBuild_RegistryOrImageRequired(t *testing.T) {
|
|||
testRegistryOrImageRequired(NewBuildCmd, t)
|
||||
}
|
||||
|
||||
// TestBuild_Authentication ensures that Token and Username/Password auth
|
||||
// propagate to pushers which support them.
|
||||
func TestBuild_Authentication(t *testing.T) {
|
||||
testAuthentication(NewBuildCmd, t)
|
||||
}
|
||||
|
||||
// TestBuild_Push ensures that the build command properly pushes and respects
|
||||
// the --push flag.
|
||||
// - Push triggered after a successful build
|
||||
|
|
|
@ -125,7 +125,7 @@ EXAMPLES
|
|||
|
||||
`,
|
||||
SuggestFor: []string{"delpoy", "deplyo"},
|
||||
PreRunE: bindEnv("build", "build-timestamp", "builder", "builder-image", "confirm", "domain", "env", "git-branch", "git-dir", "git-url", "image", "namespace", "path", "platform", "push", "pvc-size", "service-account", "registry", "registry-insecure", "remote", "verbose"),
|
||||
PreRunE: bindEnv("build", "build-timestamp", "builder", "builder-image", "confirm", "domain", "env", "git-branch", "git-dir", "git-url", "image", "namespace", "path", "platform", "push", "pvc-size", "service-account", "registry", "registry-insecure", "remote", "username", "password", "token", "verbose"),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runDeploy(cmd, newClient)
|
||||
},
|
||||
|
@ -193,8 +193,24 @@ EXAMPLES
|
|||
"Push the function image to registry before deploying. ($FUNC_PUSH)")
|
||||
cmd.Flags().String("platform", "",
|
||||
"Optionally specify a specific platform to build for (e.g. linux/amd64). ($FUNC_PLATFORM)")
|
||||
cmd.Flags().StringP("username", "", "",
|
||||
"Username to use when pushing to the registry.")
|
||||
cmd.Flags().StringP("password", "", "",
|
||||
"Password to use when pushing to the registry.")
|
||||
cmd.Flags().StringP("token", "", "",
|
||||
"Token to use when pushing to the registry.")
|
||||
cmd.Flags().BoolP("build-timestamp", "", false, "Use the actual time as the created time for the docker image. This is only useful for buildpacks builder.")
|
||||
|
||||
// Temporarily Hidden Basic Auth Flags
|
||||
// Username, Password and Token flags, which plumb through basic auth, are
|
||||
// currently only available on the experimental "host" builder, which is
|
||||
// itself behind a feature flag FUNC_ENABLE_HOST_BUILDER. So set these
|
||||
// flags to hidden until it's out of preview and they are plumbed through
|
||||
// the docker pusher as well.
|
||||
_ = cmd.Flags().MarkHidden("username")
|
||||
_ = cmd.Flags().MarkHidden("password")
|
||||
_ = cmd.Flags().MarkHidden("token")
|
||||
|
||||
// Oft-shared flags:
|
||||
addConfirmFlag(cmd, cfg.Confirm)
|
||||
addPathFlag(cmd)
|
||||
|
@ -235,6 +251,7 @@ func runDeploy(cmd *cobra.Command, newClient ClientFactory) (err error) {
|
|||
if f, err = cfg.Configure(f); err != nil { // Updates f with deploy cfg
|
||||
return
|
||||
}
|
||||
cmd.SetContext(cfg.WithValues(cmd.Context())) // Some optional settings are passed via context
|
||||
|
||||
// If using Openshift registry AND redeploying Function, update image registry
|
||||
if f.Namespace != "" && f.Namespace != f.Deploy.Namespace && f.Deploy.Namespace != "" {
|
||||
|
|
|
@ -1400,6 +1400,75 @@ func testRegistryOrImageRequired(cmdFn commandConstructor, t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDeploy_Authentication ensures that Token and Username/Password auth
|
||||
// propagate their values to pushers which support them.
|
||||
func TestDeploy_Authentication(t *testing.T) {
|
||||
testAuthentication(NewDeployCmd, t)
|
||||
}
|
||||
|
||||
func testAuthentication(cmdFn commandConstructor, t *testing.T) {
|
||||
// This test is currently focused on ensuring the flags for
|
||||
// explicit credentials (bearer token and username/password) are respected
|
||||
// and propagated to pushers which support this authentication method.
|
||||
// Integration tests must be used to ensure correct integration between
|
||||
// the system and credential helpers (Docker, ecs, acs)
|
||||
t.Helper()
|
||||
|
||||
root := fromTempDirectory(t)
|
||||
_, err := fn.New().Init(fn.Function{Runtime: "go", Root: root, Registry: TestRegistry})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var (
|
||||
testUser = "alice"
|
||||
testPass = "123"
|
||||
testToken = "example.jwt.token"
|
||||
)
|
||||
|
||||
// Basic Auth: username/password
|
||||
// -----------------------------
|
||||
pusher := mock.NewPusher()
|
||||
pusher.PushFn = func(ctx context.Context, _ fn.Function) (string, error) {
|
||||
username, _ := ctx.Value(fn.PushUsernameKey{}).(string)
|
||||
password, _ := ctx.Value(fn.PushPasswordKey{}).(string)
|
||||
|
||||
if username != testUser || password != testPass {
|
||||
t.Fatalf("expected username %q, password %q. Got %q, %q", testUser, testPass, username, password)
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
cmd := cmdFn(NewTestClient(fn.WithPusher(pusher)))
|
||||
t.Setenv("FUNC_ENABLE_HOST_BUILDER", "true") // host builder is currently behind this feature flag
|
||||
cmd.SetArgs([]string{"--builder", "host", "--username", testUser, "--password", testPass})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Basic Auth: token
|
||||
// -----------------------------
|
||||
pusher = mock.NewPusher()
|
||||
pusher.PushFn = func(ctx context.Context, _ fn.Function) (string, error) {
|
||||
token, _ := ctx.Value(fn.PushTokenKey{}).(string)
|
||||
|
||||
if token != testToken {
|
||||
t.Fatalf("expected token %q, got %q", testToken, token)
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
cmd = cmdFn(NewTestClient(fn.WithPusher(pusher)))
|
||||
|
||||
cmd.SetArgs([]string{"--builder", "host", "--token", testToken})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// TestDeploy_RemoteBuildURLPermutations ensures that the remote, build and git-url flags
|
||||
// are properly respected for all permutations, including empty.
|
||||
func TestDeploy_RemoteBuildURLPermutations(t *testing.T) {
|
||||
|
|
2
go.mod
2
go.mod
|
@ -64,6 +64,8 @@ require (
|
|||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute v1.24.0 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||
contrib.go.opencensus.io/exporter/ocagent v0.7.1-0.20200907061046-05415f1de66d // indirect
|
||||
contrib.go.opencensus.io/exporter/prometheus v0.4.2 // indirect
|
||||
dario.cat/mergo v1.0.0 // indirect
|
||||
|
|
8
go.sum
8
go.sum
|
@ -20,6 +20,10 @@ cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvf
|
|||
cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg=
|
||||
cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc=
|
||||
cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ=
|
||||
cloud.google.com/go/compute v1.24.0 h1:phWcR2eWzRJaL/kOiJwfFsPs4BaKq1j6vnpZrc1YlVg=
|
||||
cloud.google.com/go/compute v1.24.0/go.mod h1:kw1/T+h/+tK2LJK0wiPPx1intgdAM3j/g3hFDlscY40=
|
||||
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
|
||||
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
|
||||
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
|
||||
cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=
|
||||
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
|
||||
|
@ -1008,8 +1012,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMey
|
|||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
|
||||
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
|
||||
go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco=
|
||||
go.opentelemetry.io/otel/sdk v1.19.0 h1:6USY6zH+L8uMH8L3t1enZPR3WFEmSTADlqldyHtJi3o=
|
||||
go.opentelemetry.io/otel/sdk v1.19.0/go.mod h1:NedEbbS4w3C6zElbLdPJKOpJQOrGUJ+GfzpjUvI0v1A=
|
||||
go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZXQ8=
|
||||
go.opentelemetry.io/otel/sdk v1.21.0/go.mod h1:Nna6Yv7PWTdgJHVRD9hIYywQBRx7pbox6nwBnZIxl/E=
|
||||
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
|
||||
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
|
||||
go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I=
|
||||
|
|
|
@ -94,6 +94,18 @@ type Pusher interface {
|
|||
Push(ctx context.Context, f Function) (string, error)
|
||||
}
|
||||
|
||||
// PushUsernameKey is a type available for use to communicate a basic
|
||||
// authentication username to pushers which support this method.
|
||||
type PushUsernameKey struct{}
|
||||
|
||||
// PushPasswordKey is a type available for use as a context key for
|
||||
// providing a basic auth password to pushers which support this method.
|
||||
type PushPasswordKey struct{}
|
||||
|
||||
// PushTokenKey is a type available for use as a context key for providing a
|
||||
// token (for example a jwt bearer token) to pushers which support this method.
|
||||
type PushTokenKey struct{}
|
||||
|
||||
// Deployer of function source to running status.
|
||||
type Deployer interface {
|
||||
// Deploy a function of given name, using given backing image.
|
||||
|
|
|
@ -565,7 +565,7 @@ func TestClient_New_Delegation(t *testing.T) {
|
|||
return nil
|
||||
}
|
||||
|
||||
pusher.PushFn = func(f fn.Function) (string, error) {
|
||||
pusher.PushFn = func(_ context.Context, f fn.Function) (string, error) {
|
||||
if f.Build.Image != expectedImage {
|
||||
t.Fatalf("pusher expected image '%v', got '%v'", expectedImage, f.Build.Image)
|
||||
}
|
||||
|
@ -843,7 +843,7 @@ func TestClient_Update(t *testing.T) {
|
|||
}
|
||||
|
||||
// Pusher whose implementaiton verifies the expected image
|
||||
pusher.PushFn = func(f fn.Function) (string, error) {
|
||||
pusher.PushFn = func(_ context.Context, f fn.Function) (string, error) {
|
||||
if f.Build.Image != expectedImage {
|
||||
t.Fatalf("pusher expected image '%v', got '%v'", expectedImage, f.Build.Image)
|
||||
}
|
||||
|
|
|
@ -8,16 +8,16 @@ import (
|
|||
|
||||
type Pusher struct {
|
||||
PushInvoked bool
|
||||
PushFn func(fn.Function) (string, error)
|
||||
PushFn func(context.Context, fn.Function) (string, error)
|
||||
}
|
||||
|
||||
func NewPusher() *Pusher {
|
||||
return &Pusher{
|
||||
PushFn: func(fn.Function) (string, error) { return "", nil },
|
||||
PushFn: func(context.Context, fn.Function) (string, error) { return "", nil },
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Pusher) Push(ctx context.Context, f fn.Function) (string, error) {
|
||||
i.PushInvoked = true
|
||||
return i.PushFn(f)
|
||||
return i.PushFn(ctx, f)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package mock
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
|
||||
impl "github.com/google/go-containerregistry/pkg/registry"
|
||||
)
|
||||
|
||||
type Registry struct {
|
||||
*httptest.Server
|
||||
|
||||
HandlerFunc http.HandlerFunc
|
||||
RegistryImpl http.Handler
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
registryHandler := impl.New(impl.Logger(log.New(os.Stderr, "test registry: ", log.LstdFlags)))
|
||||
r := &Registry{
|
||||
RegistryImpl: registryHandler,
|
||||
}
|
||||
r.Server = httptest.NewServer(r)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *Registry) Addr() net.Addr {
|
||||
return r.Server.Listener.Addr()
|
||||
}
|
||||
|
||||
func (r *Registry) Close() {
|
||||
r.Server.Close()
|
||||
}
|
||||
|
||||
func (r *Registry) ServeHTTP(res http.ResponseWriter, req *http.Request) {
|
||||
if r.HandlerFunc != nil {
|
||||
r.HandlerFunc(res, req)
|
||||
} else {
|
||||
r.RegistryImpl.ServeHTTP(res, req)
|
||||
}
|
||||
}
|
|
@ -2,7 +2,9 @@ package oci
|
|||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
|
@ -11,26 +13,28 @@ import (
|
|||
"github.com/google/go-containerregistry/pkg/authn"
|
||||
"github.com/google/go-containerregistry/pkg/name"
|
||||
v1 "github.com/google/go-containerregistry/pkg/v1"
|
||||
"github.com/google/go-containerregistry/pkg/v1/google"
|
||||
"github.com/google/go-containerregistry/pkg/v1/layout"
|
||||
"github.com/google/go-containerregistry/pkg/v1/remote"
|
||||
"github.com/pkg/errors"
|
||||
progress "github.com/schollz/progressbar/v3"
|
||||
|
||||
fn "knative.dev/func/pkg/functions"
|
||||
)
|
||||
|
||||
// Pusher of OCI multi-arch layout directories.
|
||||
type Pusher struct {
|
||||
Insecure bool
|
||||
Anonymous bool
|
||||
Verbose bool
|
||||
Username string
|
||||
Insecure bool
|
||||
Token string
|
||||
Username string
|
||||
Verbose bool
|
||||
|
||||
updates chan v1.Update
|
||||
done chan bool
|
||||
}
|
||||
|
||||
func NewPusher(insecure, anon, verbose bool) *Pusher {
|
||||
fmt.Println(insecure, anon, verbose)
|
||||
return &Pusher{
|
||||
Insecure: insecure,
|
||||
Anonymous: anon,
|
||||
|
@ -77,43 +81,6 @@ func (p *Pusher) Push(ctx context.Context, f fn.Function) (digest string, err er
|
|||
return
|
||||
}
|
||||
|
||||
// The last build directory is symlinked upon successful build.
|
||||
func getLastBuildDir(f fn.Function) (string, error) {
|
||||
dir := filepath.Join(f.Root, fn.RunDataDir, "builds", "last")
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return dir, fmt.Errorf("last build directory not found '%v'. Has it been built?", dir)
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func (p *Pusher) writeIndex(ctx context.Context, ref name.Reference, ii v1.ImageIndex) error {
|
||||
// If we're set to anonymous, just try as-is and return on failure
|
||||
if p.Anonymous {
|
||||
return remote.WriteIndex(ref, ii,
|
||||
remote.WithContext(ctx),
|
||||
remote.WithProgress(p.updates))
|
||||
}
|
||||
|
||||
// TODO: The below is untested and may only be useful for the test, since
|
||||
// a `docker login` utilizes the keychain for the httpasswd basic auth
|
||||
// credentials as well:
|
||||
if p.Username != "" && p.Token != "" {
|
||||
return remote.WriteIndex(ref, ii,
|
||||
remote.WithContext(ctx),
|
||||
remote.WithProgress(p.updates),
|
||||
remote.WithAuth(&authn.Basic{
|
||||
Username: p.Username,
|
||||
Password: p.Token,
|
||||
}))
|
||||
}
|
||||
|
||||
// Otherwise use the keychain
|
||||
return remote.WriteIndex(ref, ii,
|
||||
remote.WithContext(ctx),
|
||||
remote.WithProgress(p.updates),
|
||||
remote.WithAuthFromKeychain(authn.DefaultKeychain))
|
||||
}
|
||||
|
||||
func (p *Pusher) handleUpdates(ctx context.Context) {
|
||||
var bar *progress.ProgressBar
|
||||
for {
|
||||
|
@ -141,5 +108,72 @@ func (p *Pusher) handleUpdates(ctx context.Context) {
|
|||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// The last build directory is symlinked upon successful build.
|
||||
func getLastBuildDir(f fn.Function) (string, error) {
|
||||
dir := filepath.Join(f.Root, fn.RunDataDir, "builds", "last")
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return dir, fmt.Errorf("last build directory not found '%v'. Has it been built?", dir)
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
// writeIndex to its defined registry.
|
||||
func (p *Pusher) writeIndex(ctx context.Context, ref name.Reference, ii v1.ImageIndex) error {
|
||||
oo := []remote.Option{
|
||||
remote.WithContext(ctx),
|
||||
remote.WithProgress(p.updates),
|
||||
}
|
||||
|
||||
if p.Insecure {
|
||||
t := remote.DefaultTransport.(*http.Transport).Clone()
|
||||
t.TLSClientConfig = &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
oo = append(oo, remote.WithTransport(t))
|
||||
}
|
||||
|
||||
if !p.Anonymous {
|
||||
a, err := p.authOption(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
oo = append(oo, a)
|
||||
}
|
||||
|
||||
return remote.WriteIndex(ref, ii, oo...)
|
||||
}
|
||||
|
||||
// authOption selects an appropriate authentication option.
|
||||
// If user provided = basic auth (secret is password)
|
||||
// If only secret provided = bearer token auth
|
||||
// If neither are provided = Returned is a cascading keychain auth mthod
|
||||
// which performs the following in order:
|
||||
// - Default Keychain (docker and podman config files)
|
||||
// - Google Keychain
|
||||
// - TODO: ECR Amazon
|
||||
// - TODO: ACR Azure
|
||||
func (p *Pusher) authOption(ctx context.Context, ref name.Reference) (remote.Option, error) {
|
||||
|
||||
// Basic Auth if provided
|
||||
username, _ := ctx.Value(fn.PushUsernameKey{}).(string)
|
||||
password, _ := ctx.Value(fn.PushPasswordKey{}).(string)
|
||||
token, _ := ctx.Value(fn.PushTokenKey{}).(string)
|
||||
if username != "" && token != "" {
|
||||
return nil, errors.New("only one of username/password or token authentication allowed. Received both a token and username")
|
||||
} else if token != "" {
|
||||
return remote.WithAuth(&authn.Bearer{Token: token}), nil
|
||||
} else if username != "" {
|
||||
return remote.WithAuth(&authn.Basic{Username: username, Password: password}), nil
|
||||
}
|
||||
|
||||
// Default chain
|
||||
return remote.WithAuthFromKeychain(authn.NewMultiKeychain(
|
||||
authn.DefaultKeychain, // Podman and Docker config files
|
||||
google.Keychain, // Google
|
||||
// TODO: Integrate and test ECR and ACR credential helpers:
|
||||
// authn.NewKeychainFromHelper(ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}}),
|
||||
// authn.NewKeychainFromHelper(acr.ACRCredHelper{}),
|
||||
)), nil
|
||||
}
|
||||
|
|
|
@ -10,18 +10,18 @@ import (
|
|||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-containerregistry/pkg/registry"
|
||||
"time"
|
||||
|
||||
fn "knative.dev/func/pkg/functions"
|
||||
"knative.dev/func/pkg/oci/mock"
|
||||
. "knative.dev/func/pkg/testing"
|
||||
|
||||
"github.com/google/go-containerregistry/pkg/registry"
|
||||
)
|
||||
|
||||
// TestPusher ensures that the pusher contacts the endpoint on request with
|
||||
// the expected content type (see the go-containerregistry library for
|
||||
// tests which confirm it is functioning as expected from there, and the
|
||||
// builder tests which ensure the container being pushed is OCI-compliant.)
|
||||
func TestPusher(t *testing.T) {
|
||||
// TestPusher_Push ensures the base case that the pusher contacts the
|
||||
// registry with a correctly formed request.
|
||||
func TestPusher_Push(t *testing.T) {
|
||||
var (
|
||||
root, done = Mktemp(t)
|
||||
verbose = false
|
||||
|
@ -84,3 +84,81 @@ func TestPusher(t *testing.T) {
|
|||
t.Fatal("did not receive the image index JSON")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPusher_Auth ensures that the pusher authenticates via basic auth when
|
||||
// supplied with a username/password via the context.
|
||||
func TestPusher_BasicAuth(t *testing.T) {
|
||||
var (
|
||||
root, done = Mktemp(t)
|
||||
username = "username"
|
||||
password = "password"
|
||||
verbose = false
|
||||
successCh = make(chan bool, 100) // Many successes are queued on push
|
||||
err error
|
||||
)
|
||||
defer done()
|
||||
|
||||
// A mock registry with middleware which performs basic auth
|
||||
server := mock.NewRegistry()
|
||||
server.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
|
||||
u, p, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
// no header. ask for auth
|
||||
w.Header().Add("www-authenticate", "Basic realm=\"Registry Realm\"")
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
} else if u != "username" || p != "password" {
|
||||
// header exists, but creds are either missing or incorrect
|
||||
t.Fatalf("Unauthorized. Expected user %q pass %q, got user %q pass %q", username, password, u, p)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
} else {
|
||||
// (at least one) request indicates authentication worked.
|
||||
// The channel has a large buffer because many are queued before
|
||||
// the receive instruction.
|
||||
successCh <- true
|
||||
}
|
||||
|
||||
// always delegate to the registry impl which implements the protocol
|
||||
server.RegistryImpl.ServeHTTP(w, r)
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
// Client
|
||||
// initialized with an OCI builder and pusher.
|
||||
client := fn.New(
|
||||
fn.WithBuilder(NewBuilder("", verbose)),
|
||||
fn.WithPusher(NewPusher(false, false, verbose)))
|
||||
|
||||
// Function
|
||||
// Built and tagged to push to the mock registry
|
||||
f := fn.Function{
|
||||
Root: root,
|
||||
Runtime: "go",
|
||||
Name: "f",
|
||||
Registry: server.Addr().String() + "/funcs"}
|
||||
|
||||
if f, err = client.Init(f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, err = client.Build(context.Background(), f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Push
|
||||
// Enables optional basic authentication via the push context to use instead
|
||||
// of the default behavior of using the multi-auth chain of config files
|
||||
// and various known credentials managers.
|
||||
ctx := context.Background()
|
||||
ctx = context.WithValue(ctx, fn.PushUsernameKey{}, username)
|
||||
ctx = context.WithValue(ctx, fn.PushPasswordKey{}, password)
|
||||
|
||||
if _, err = client.Push(ctx, f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-successCh:
|
||||
case <-time.NewTimer(10 * time.Second).C:
|
||||
t.Fatal("timed out waiting for a successful basic auth request")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
Loading…
Reference in New Issue