Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(oci): dont use preparing client for docker authorizer #7196

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 17 additions & 62 deletions download/oci_download.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package download
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
Expand All @@ -26,7 +27,6 @@ import (

"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
"github.com/open-policy-agent/opa/logging"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/plugins"
"github.com/open-policy-agent/opa/plugins/rest"
Expand Down Expand Up @@ -300,7 +300,7 @@ func (d *OCIDownloader) pull(ctx context.Context, ref string) (*ocispec.Descript

d.logger.Debug("OCIDownloader: using auth plugin: %T", plugin)

resolver, err := dockerResolver(plugin, d.client.Config(), d.logger)
resolver, err := dockerResolver(d.client.Config())
if err != nil {
return nil, fmt.Errorf("invalid host url %s: %w", d.client.Config().URL, err)
}
Expand All @@ -318,30 +318,36 @@ func (d *OCIDownloader) pull(ctx context.Context, ref string) (*ocispec.Descript
return &manifestDescriptor, nil
}

func dockerResolver(plugin rest.HTTPAuthPlugin, config *rest.Config, logger logging.Logger) (remotes.Resolver, error) {
client, err := plugin.NewClient(*config)
func dockerResolver(config *rest.Config) (remotes.Resolver, error) {
tc, err := rest.DefaultTLSConfig(*config)
if err != nil {
return nil, fmt.Errorf("failed to create auth client: %w", err)
return nil, fmt.Errorf("failed to create tls config: %w", err)
}

client := rest.DefaultRoundTripperClient(tc, *config.ResponseHeaderTimeoutSeconds)

urlInfo, err := url.Parse(config.URL)
if err != nil {
return nil, fmt.Errorf("failed to parse url: %w", err)
}

authorizer := pluginAuthorizer{
plugin: plugin,
client: client,
logger: logger,
header := make(http.Header)
if b := config.Credentials.Bearer; b != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How many of the auth plugins had been supported before? With this change, we go back to only supporting bearer creds as auth mechanism, don't we?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as far as I understand, this would drop mtls authentication, since azure
managed identity is not supported for OCI. Or is tls even covered
by constructing the tls config? Is this maybe also an issue on redirect?

Personally, I would add another auth type that maps closely to the options
provides by containerd.docker package. Registry protocols are kind of
specific, and I don't think you can cover it with some more simple, generic
auth plugin.

So either we need to make the auth plugins alot more complex for all users,
or we just create a registry specific one, that can deal with the quirky,
protocols.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where @DerGut introduced the feature. It also mentions s3_signing for talking to AWS.

I'd like to avoid throwing the baby out with the bathwater 😉

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this github ui terrible. I don't know understand what all the
buttons are suppossed to do. I keep deleting my comments
by accident, sorry.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi all, as @bluebrown mentioned the registry protocols are quite specific so maybe keeping it simple makes more sense. The addition of the plugins seems to have complicated the behavior of the OCI downloader and is currently causing issues with some registries (AWS and Azure ) because of the underlying redirect mechanism.

Would changing the plugin authorizer used in the OCI downloader to not attach the authorization header on a redirect make sense in this scenario ?

Copy link
Author

@bluebrown bluebrown Dec 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@carabasdaniel, to my understanding, this should solve the problem.

Based on my research, there is nothing in the HTTP spec that says if/when
credentials should be sent during redirect.

However, there is the www-authenticate header, that is used by some
implementations, including containerd.

They maintain a handler map, to know what endpoints should get auth
header. One criterion for adding a URL to the map, is www-authenticate.

You can see this roughly here:
https://github.com/containerd/containerd/blob/88bf19b2105c8b17560993bee28a01ddc2f97182/remotes/docker/authorizer.go#L114

And here: https://github.com/containerd/containerd/blob/2c042ae0de7b9d69df8df8e370e2d802f10f9ee5/core/remotes/docker/auth/parse.go#L98

Copy link
Contributor

@carabasdaniel carabasdaniel Dec 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @bluebrown, @srenatus sorry for the late reply I grabbed this change on top of latest main and I was testing this change with different OCI registries.

Public registries seem to work as expected, however when testing against some private registries I seem to hit the same problem that the CI shows. Basically the client created by rest.DefaultRoundTripperClient(tc, *config.ResponseHeaderTimeoutSeconds) doesn't have the necessary credentials and it fails to get the manifest of a private image returning a 401.

You can use docker to spin up a local private registry to repro this issue or rely on the tests to easily debug. Please let me know if you need more details about this.

In the CNCF policy CLI project used to build and push policy images to different OCI registries we use the oci package from here to solve this issue https://github.com/opcr-io/policy/blob/main/oci/oci.go

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sorry, I meant this as answer to your question:

Would changing the plugin authorizer used in the OCI downloader to not attach the authorization header on a redirect make sense in this scenario ?

We also found some code that would not add the headers on redirect if the hostname changes.

t := base64.StdEncoding.EncodeToString([]byte(config.Credentials.Bearer.Token))
header.Set("Authorization", "Basic "+t)
}

authorizer := docker.NewDockerAuthorizer(
docker.WithAuthClient(client),
docker.WithAuthHeader(header),
)

registryHost := docker.RegistryHost{
Host: urlInfo.Host,
Scheme: urlInfo.Scheme,
Capabilities: docker.HostCapabilityPull | docker.HostCapabilityResolve | docker.HostCapabilityPush,
Client: client,
Path: "/v2",
Authorizer: &authorizer,
Authorizer: authorizer,
}

opts := docker.ResolverOptions{
Expand All @@ -353,57 +359,6 @@ func dockerResolver(plugin rest.HTTPAuthPlugin, config *rest.Config, logger logg
return docker.NewResolver(opts), nil
}

type pluginAuthorizer struct {
plugin rest.HTTPAuthPlugin
client *http.Client

// authorizer will be populated by the first call to pluginAuthorizer.Prepare
// since it requires a first pass through the plugin.Prepare method.
authorizer docker.Authorizer

logger logging.Logger
}

var _ docker.Authorizer = &pluginAuthorizer{}

func (a *pluginAuthorizer) AddResponses(ctx context.Context, responses []*http.Response) error {
return a.authorizer.AddResponses(ctx, responses)
}

// Authorize uses a rest.HTTPAuthPlugin to Prepare a request before passing it on
// to the docker.Authorizer.
func (a *pluginAuthorizer) Authorize(ctx context.Context, req *http.Request) error {
if err := a.plugin.Prepare(req); err != nil {
err = fmt.Errorf("failed to prepare docker request: %w", err)

// Make sure to log this before passing the error back to docker
a.logger.Error(err.Error())

return err
}

if a.authorizer == nil {
// Some registry authentication implementations require a token fetch from
// a separate authenticated token server. This flow is described in the
// docker token auth spec:
// https://docs.docker.com/registry/spec/auth/token/#requesting-a-token
//
// Unfortunately, the containerd implementation does not use the Prepare
// mechanism to authenticate these token requests and we need to add
// auth information in form of a static docker.WithAuthHeader.
//
// Since rest.HTTPAuthPlugins will set the auth header on the request
// passed to HTTPAuthPlugin.Prepare, we can use it afterwards to build
// our docker.Authorizer.
a.authorizer = docker.NewDockerAuthorizer(
docker.WithAuthHeader(req.Header),
docker.WithAuthClient(a.client),
)
}

return a.authorizer.Authorize(ctx, req)
}

func manifestFromDesc(ctx context.Context, target oraslib.Target, desc *ocispec.Descriptor) (*ocispec.Manifest, error) {
var manifest ocispec.Manifest

Expand Down
Loading