Skip to content

Commit

Permalink
feat: merge package credentials back from oras-credentials-go (#589)
Browse files Browse the repository at this point in the history
1. Add package `credentials` (migrated from
[`oras-credentials-go`](https://github.com/oras-project/oras-credentials-go))
and its corresponding description
2. Add new type `auth.CredentialFunc`
3. Migrate the credentials example from
[oras.land](https://oras.land/docs/client_libraries/go/#pull-an-image-using-the-docker-credential-store)
4. Change `auth.DefaultCache` to `auth.NewCache()` in examples

Resolves: #584
Signed-off-by: Lixia (Sylvia) Lei <[email protected]>
  • Loading branch information
Wwwsylvia authored Sep 8, 2023
1 parent 4a52cfd commit c130949
Show file tree
Hide file tree
Showing 30 changed files with 5,528 additions and 10 deletions.
49 changes: 45 additions & 4 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"oras.land/oras-go/v2/content/oci"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials"
"oras.land/oras-go/v2/registry/remote/retry"
)

Expand All @@ -48,7 +49,7 @@ func Example_pullFilesFromRemoteRepository() {
// Note: The below code can be omitted if authentication is not required
repo.Client = &auth.Client{
Client: retry.DefaultClient,
Cache: auth.DefaultCache,
Cache: auth.NewCache(),
Credential: auth.StaticCredential(reg, auth.Credential{
Username: "username",
Password: "password",
Expand Down Expand Up @@ -83,7 +84,7 @@ func Example_pullImageFromRemoteRepository() {
// Note: The below code can be omitted if authentication is not required
repo.Client = &auth.Client{
Client: retry.DefaultClient,
Cache: auth.DefaultCache,
Cache: auth.NewCache(),
Credential: auth.StaticCredential(reg, auth.Credential{
Username: "username",
Password: "password",
Expand All @@ -99,6 +100,46 @@ func Example_pullImageFromRemoteRepository() {
fmt.Println("manifest descriptor:", manifestDescriptor)
}

// ExamplePullImageUsingDockerCredentials gives an example of pulling an image
// from a remote repository to an OCI Image layout folder using Docker
// credentials.
func Example_pullImageUsingDockerCredentials() {
// 0. Create an OCI layout store
store, err := oci.New("/tmp/oci-layout-root")
if err != nil {
panic(err)
}

// 1. Connect to a remote repository
ctx := context.Background()
reg := "docker.io"
repo, err := remote.NewRepository(reg + "/user/my-repo")
if err != nil {
panic(err)
}

// prepare authentication using Docker credentials
storeOpts := credentials.StoreOptions{}
credStore, err := credentials.NewStoreFromDocker(storeOpts)
if err != nil {
panic(err)
}
repo.Client = &auth.Client{
Client: retry.DefaultClient,
Cache: auth.NewCache(),
Credential: credentials.Credential(credStore), // Use the credentials store
}

// 2. Copy from the remote repository to the OCI layout store
tag := "latest"
manifestDescriptor, err := oras.Copy(ctx, repo, tag, store, tag, oras.DefaultCopyOptions)
if err != nil {
panic(err)
}

fmt.Println("manifest pulled:", manifestDescriptor.Digest, manifestDescriptor.MediaType)
}

// ExamplePushFilesToRemoteRepository gives an example of pushing local files
// to a remote repository.
func Example_pushFilesToRemoteRepository() {
Expand Down Expand Up @@ -148,14 +189,14 @@ func Example_pushFilesToRemoteRepository() {
// Note: The below code can be omitted if authentication is not required
repo.Client = &auth.Client{
Client: retry.DefaultClient,
Cache: auth.DefaultCache,
Cache: auth.NewCache(),
Credential: auth.StaticCredential(reg, auth.Credential{
Username: "username",
Password: "password",
}),
}

// 3. Copy from the file store to the remote repository
// 4. Copy from the file store to the remote repository
_, err = oras.Copy(ctx, fs, tag, repo, tag, oras.DefaultCopyOptions)
if err != nil {
panic(err)
Expand Down
19 changes: 13 additions & 6 deletions registry/remote/auth/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,23 @@ var maxResponseBytes int64 = 128 * 1024 // 128 KiB
// See also ClientID.
var defaultClientID = "oras-go"

// CredentialFunc represents a function that resolves the credential for the
// given registry (i.e. host:port).
//
// [EmptyCredential] is a valid return value and should not be considered as
// an error.
type CredentialFunc func(ctx context.Context, hostport string) (Credential, error)

// StaticCredential specifies static credentials for the given host.
func StaticCredential(registry string, cred Credential) func(context.Context, string) (Credential, error) {
func StaticCredential(registry string, cred Credential) CredentialFunc {
if registry == "docker.io" {
// it is expected that traffic targeting "docker.io" will be redirected
// to "registry-1.docker.io"
// reference: https://github.com/moby/moby/blob/v24.0.0-beta.2/registry/config.go#L25-L48
registry = "registry-1.docker.io"
}
return func(_ context.Context, target string) (Credential, error) {
if target == registry {
return func(_ context.Context, hostport string) (Credential, error) {
if hostport == registry {
return cred, nil
}
return EmptyCredential, nil
Expand All @@ -88,10 +95,10 @@ type Client struct {

// Credential specifies the function for resolving the credential for the
// given registry (i.e. host:port).
// `EmptyCredential` is a valid return value and should not be considered as
// EmptyCredential is a valid return value and should not be considered as
// an error.
// If nil, the credential is always resolved to `EmptyCredential`.
Credential func(context.Context, string) (Credential, error)
// If nil, the credential is always resolved to EmptyCredential.
Credential CredentialFunc

// Cache caches credentials for direct accessing the remote registry.
// If nil, no cache is used.
Expand Down
239 changes: 239 additions & 0 deletions registry/remote/credentials/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/*
Copyright The ORAS Authors.
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.
*/

package credentials_test

import (
"context"
"fmt"
"net/http"

"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
credentials "oras.land/oras-go/v2/registry/remote/credentials"
)

func ExampleNewNativeStore() {
ns := credentials.NewNativeStore("pass")

ctx := context.Background()
// save credentials into the store
err := ns.Put(ctx, "localhost:5000", auth.Credential{
Username: "username-example",
Password: "password-example",
})
if err != nil {
panic(err)
}

// get credentials from the store
cred, err := ns.Get(ctx, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println(cred)

// delete the credentials from the store
err = ns.Delete(ctx, "localhost:5000")
if err != nil {
panic(err)
}
}

func ExampleNewFileStore() {
fs, err := credentials.NewFileStore("example/path/config.json")
if err != nil {
panic(err)
}

ctx := context.Background()
// save credentials into the store
err = fs.Put(ctx, "localhost:5000", auth.Credential{
Username: "username-example",
Password: "password-example",
})
if err != nil {
panic(err)
}

// get credentials from the store
cred, err := fs.Get(ctx, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println(cred)

// delete the credentials from the store
err = fs.Delete(ctx, "localhost:5000")
if err != nil {
panic(err)
}
}

func ExampleNewStore() {
// NewStore returns a Store based on the given configuration file. It will
// automatically determine which Store (file store or native store) to use.
// If the native store is not available, you can save your credentials in
// the configuration file by specifying AllowPlaintextPut: true, but keep
// in mind that this is an unsafe workaround.
// See the documentation for details.
store, err := credentials.NewStore("example/path/config.json", credentials.StoreOptions{
AllowPlaintextPut: true,
})
if err != nil {
panic(err)
}

ctx := context.Background()
// save credentials into the store
err = store.Put(ctx, "localhost:5000", auth.Credential{
Username: "username-example",
Password: "password-example",
})
if err != nil {
panic(err)
}

// get credentials from the store
cred, err := store.Get(ctx, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println(cred)

// delete the credentials from the store
err = store.Delete(ctx, "localhost:5000")
if err != nil {
panic(err)
}
}

func ExampleNewStoreFromDocker() {
ds, err := credentials.NewStoreFromDocker(credentials.StoreOptions{
AllowPlaintextPut: true,
})
if err != nil {
panic(err)
}

ctx := context.Background()
// save credentials into the store
err = ds.Put(ctx, "localhost:5000", auth.Credential{
Username: "username-example",
Password: "password-example",
})
if err != nil {
panic(err)
}

// get credentials from the store
cred, err := ds.Get(ctx, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println(cred)

// delete the credentials from the store
err = ds.Delete(ctx, "localhost:5000")
if err != nil {
panic(err)
}
}

func ExampleNewStoreWithFallbacks_configAsPrimaryStoreDockerAsFallback() {
primaryStore, err := credentials.NewStore("example/path/config.json", credentials.StoreOptions{
AllowPlaintextPut: true,
})
if err != nil {
panic(err)
}
fallbackStore, err := credentials.NewStoreFromDocker(credentials.StoreOptions{})
sf := credentials.NewStoreWithFallbacks(primaryStore, fallbackStore)

ctx := context.Background()
// save credentials into the store
err = sf.Put(ctx, "localhost:5000", auth.Credential{
Username: "username-example",
Password: "password-example",
})
if err != nil {
panic(err)
}

// get credentials from the store
cred, err := sf.Get(ctx, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println(cred)

// delete the credentials from the store
err = sf.Delete(ctx, "localhost:5000")
if err != nil {
panic(err)
}
}

func ExampleLogin() {
store, err := credentials.NewStore("example/path/config.json", credentials.StoreOptions{
AllowPlaintextPut: true,
})
if err != nil {
panic(err)
}
registry, err := remote.NewRegistry("localhost:5000")
if err != nil {
panic(err)
}
cred := auth.Credential{
Username: "username-example",
Password: "password-example",
}
err = credentials.Login(context.Background(), store, registry, cred)
if err != nil {
panic(err)
}
fmt.Println("Login succeeded")
}

func ExampleLogout() {
store, err := credentials.NewStore("example/path/config.json", credentials.StoreOptions{})
if err != nil {
panic(err)
}
err = credentials.Logout(context.Background(), store, "localhost:5000")
if err != nil {
panic(err)
}
fmt.Println("Logout succeeded")
}

func ExampleCredential() {
store, err := credentials.NewStore("example/path/config.json", credentials.StoreOptions{})
if err != nil {
panic(err)
}

client := auth.DefaultClient
client.Credential = credentials.Credential(store)

request, err := http.NewRequest(http.MethodGet, "localhost:5000", nil)
if err != nil {
panic(err)
}

_, err = client.Do(request)
if err != nil {
panic(err)
}
}
Loading

0 comments on commit c130949

Please sign in to comment.