Skip to content
Merged
Show file tree
Hide file tree
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
16 changes: 14 additions & 2 deletions cmd/crossplane/dependency/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/crossplane/cli/v2/apis/dev/v1alpha1"
"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/dependency"
"github.com/crossplane/cli/v2/internal/git"
"github.com/crossplane/cli/v2/internal/project/projectfile"
"github.com/crossplane/cli/v2/internal/schemas/generator"
"github.com/crossplane/cli/v2/internal/terminal"
Expand All @@ -47,6 +48,8 @@ type addCmd struct {
Package string `arg:"" help:"Package to add (xpkg OCI reference, k8s:<version>, git repository URL, or HTTP(S) URL)."`
ProjectFile string `default:"${project_file}" help:"Path to project definition file." short:"f"`
CacheDir string `env:"CROSSPLANE_XPKG_CACHE" help:"Directory for cached xpkg package contents." name:"cache-dir"`
GitToken string `env:"CROSSPLANE_GIT_TOKEN" help:"Token for git HTTPS authentication."`
GitUsername string `default:"x-access-token" env:"CROSSPLANE_GIT_USERNAME" help:"Username for git HTTPS authentication."`

// Flags for specific dependency types.
APIOnly bool `help:"Mark an xpkg dependency as API-only (not a runtime dependency)." name:"api-only"`
Expand Down Expand Up @@ -79,7 +82,7 @@ func (c *addCmd) Run(logger logging.Logger, sp terminal.SpinnerPrinter, cfg *con
return errors.Wrap(err, "cannot create xpkg client")
}

m := dependency.NewManager(proj, projFS,
opts := []dependency.ManagerOption{
dependency.WithProjectFile(c.ProjectFile),
dependency.WithSchemaGenerators(generator.Filter(
generator.AllLanguages(
Expand All @@ -89,7 +92,16 @@ func (c *addCmd) Run(logger logging.Logger, sp terminal.SpinnerPrinter, cfg *con
proj.Spec.Schemas.GetLanguages(),
)),
dependency.WithXpkgClient(client),
)
}

if c.GitToken != "" {
opts = append(opts, dependency.WithGitAuthProvider(&git.HTTPSAuthProvider{
Username: c.GitUsername,
Password: c.GitToken,
}))
}

m := dependency.NewManager(proj, projFS, opts...)

dep, err := c.buildDependency()
if err != nil {
Expand Down
37 changes: 0 additions & 37 deletions cmd/crossplane/dependency/auth.go

This file was deleted.

7 changes: 4 additions & 3 deletions cmd/crossplane/dependency/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/crossplane/cli/v2/internal/async"
"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/dependency"
"github.com/crossplane/cli/v2/internal/git"
"github.com/crossplane/cli/v2/internal/project/projectfile"
"github.com/crossplane/cli/v2/internal/schemas/generator"
"github.com/crossplane/cli/v2/internal/terminal"
Expand Down Expand Up @@ -88,9 +89,9 @@ func (c *updateCacheCmd) Run(logger logging.Logger, sp terminal.SpinnerPrinter,
}

if c.GitToken != "" {
opts = append(opts, dependency.WithGitAuthProvider(&gitAuthProvider{
username: c.GitUsername,
token: c.GitToken,
opts = append(opts, dependency.WithGitAuthProvider(&git.HTTPSAuthProvider{
Username: c.GitUsername,
Password: c.GitToken,
}))
}

Expand Down
104 changes: 104 additions & 0 deletions cmd/crossplane/dependency/dependency_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
Copyright 2026 The Crossplane 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 dependency

import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"

gitclient "github.com/go-git/go-git/v5/plumbing/transport/client"
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/crossplane/crossplane-runtime/v2/pkg/logging"

"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/terminal"
)

func TestAddGitAuth(t *testing.T) {
testDependencyGitAuth(t, func(serverURL, projectFile, cacheDir, token string) error {
c := &addCmd{Package: serverURL + "/repo.git", GitRef: "main", ProjectFile: projectFile, CacheDir: cacheDir, GitToken: token, GitUsername: "test-user"}
return c.Run(logging.NewNopLogger(), terminal.NewSpinnerPrinter(io.Discard, false), &config.Config{})
})
}

func TestUpdateCacheGitAuth(t *testing.T) {
testDependencyGitAuth(t, func(_, projectFile, cacheDir, token string) error {
c := &updateCacheCmd{ProjectFile: projectFile, CacheDir: cacheDir, GitToken: token, GitUsername: "test-user"}
return c.Run(logging.NewNopLogger(), terminal.NewSpinnerPrinter(io.Discard, false), &config.Config{})
})
}

// testDependencyGitAuth verifies that a command passes its token to a Git
// clone. It replaces the global HTTPS transport, so callers must run serially.
func testDependencyGitAuth(t *testing.T, run func(serverURL, projectFile, cacheDir, token string) error) {
t.Helper()
const token = "test-token"
credentials := make(chan string, 10)
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, password, _ := r.BasicAuth()
credentials <- user + ":" + password
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
original := gitclient.Protocols["https"]
gitclient.InstallProtocol("https", githttp.NewClient(server.Client()))
t.Cleanup(func() { gitclient.InstallProtocol("https", original) })
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "apis"), 0o700); err != nil {
t.Fatal(err)
}
projectFile := filepath.Join(dir, "crossplane-project.yaml")
project := fmt.Sprintf(`apiVersion: dev.crossplane.io/v1alpha1
kind: Project
metadata:
name: test
spec:
repository: example.com/test
dependencies:
- type: crd
git:
repository: %s/repo.git
ref: main
`, server.URL)
if err := os.WriteFile(projectFile, []byte(project), 0o600); err != nil {
t.Fatal(err)
}

err := run(server.URL, projectFile, filepath.Join(dir, "cache"), token)

if err == nil {
t.Fatal("expected unauthorized clone to fail")
}
if strings.Contains(err.Error(), token) {
t.Fatal("clone error exposes token")
}
select {
case got := <-credentials:
if got != "test-user:"+token {
t.Fatal("clone received unexpected credentials")
}
default:
t.Fatalf("command did not reach git server: %v", err)
}
}
6 changes: 6 additions & 0 deletions cmd/crossplane/dependency/help/add.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ dependencies. Use the `--api-only` flag to add a build-time xpkg dependency.

Non-xpkg dependencies are always build-time dependencies.

Git dependencies fetched over HTTPS can authenticate using `--git-token` and
`--git-username`. Prefer the `CROSSPLANE_GIT_TOKEN` and
`CROSSPLANE_GIT_USERNAME` environment variables to avoid exposing credentials
in shell history. The username defaults to `x-access-token`. Credentials aren't
saved in the project file.

## Examples

Retrieve the latest available semantic version of `provider-aws-eks`, generate
Expand Down
16 changes: 14 additions & 2 deletions cmd/crossplane/project/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/crossplane/cli/v2/internal/async"
"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/dependency"
"github.com/crossplane/cli/v2/internal/git"
"github.com/crossplane/cli/v2/internal/project"
"github.com/crossplane/cli/v2/internal/project/functions"
"github.com/crossplane/cli/v2/internal/project/projectfile"
Expand All @@ -56,6 +57,8 @@ type buildCmd struct {
OutputDir string `default:"_output" help:"Output directory for packages." short:"o"`
MaxConcurrency uint `default:"8" help:"Max concurrent function builds."`
CacheDir string `env:"CROSSPLANE_XPKG_CACHE" help:"Directory for cached xpkg package contents." name:"cache-dir"`
GitToken string `env:"CROSSPLANE_GIT_TOKEN" help:"Token for git HTTPS authentication."`
GitUsername string `default:"x-access-token" env:"CROSSPLANE_GIT_USERNAME" help:"Username for git HTTPS authentication."`

proj *devv1alpha1.Project
projFS afero.Fs
Expand Down Expand Up @@ -111,13 +114,22 @@ func (c *buildCmd) Run(logger logging.Logger, sp terminal.SpinnerPrinter, cfg *c
return errors.Wrap(err, "cannot create xpkg client")
}

depMgr := dependency.NewManager(c.proj, c.projFS,
opts := []dependency.ManagerOption{
dependency.WithProjectFile(c.ProjectFile),
dependency.WithSchemaFS(schemasFS),
dependency.WithSchemaGenerators(generators),
dependency.WithSchemaRunner(schemaRunner),
dependency.WithXpkgClient(client),
)
}

if c.GitToken != "" {
opts = append(opts, dependency.WithGitAuthProvider(&git.HTTPSAuthProvider{
Username: c.GitUsername,
Password: c.GitToken,
}))
}

depMgr := dependency.NewManager(c.proj, c.projFS, opts...)

// The builder may decompress function runtime tarballs into this directory;
// the built images read from it lazily, so we remove it only after the
Expand Down
97 changes: 97 additions & 0 deletions cmd/crossplane/project/build_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
Copyright 2026 The Crossplane 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 project

import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"

gitclient "github.com/go-git/go-git/v5/plumbing/transport/client"
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/crossplane/crossplane-runtime/v2/pkg/logging"

"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/terminal"
)

// TestBuildGitAuth verifies that build passes its token to a Git clone.
// It runs serially because it temporarily replaces the HTTPS transport.
func TestBuildGitAuth(t *testing.T) {
const token = "test-token"
credentials := make(chan string, 10)
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, password, _ := r.BasicAuth()
credentials <- user + ":" + password
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
original := gitclient.Protocols["https"]
gitclient.InstallProtocol("https", githttp.NewClient(server.Client()))
t.Cleanup(func() { gitclient.InstallProtocol("https", original) })
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "apis"), 0o700); err != nil {
t.Fatal(err)
}
projectFile := filepath.Join(dir, "crossplane-project.yaml")
project := fmt.Sprintf(`apiVersion: dev.crossplane.io/v1alpha1
kind: Project
metadata:
name: test
spec:
repository: example.com/test
dependencies:
- type: crd
git:
repository: %s/repo.git
ref: main
`, server.URL)
if err := os.WriteFile(projectFile, []byte(project), 0o600); err != nil {
t.Fatal(err)
}

logger := logging.NewNopLogger()
sp := terminal.NewSpinnerPrinter(io.Discard, false)
cfg := &config.Config{}

c := &buildCmd{ProjectFile: projectFile, CacheDir: filepath.Join(dir, "cache"), GitToken: token, GitUsername: "test-user", MaxConcurrency: 1}
if err := c.AfterApply(); err != nil {
t.Fatal(err)
}
err := c.Run(logger, sp, cfg)

if err == nil {
t.Fatal("expected unauthorized clone to fail")
}
if strings.Contains(err.Error(), token) {
t.Fatal("clone error exposes token")
}
select {
case got := <-credentials:
if got != "test-user:"+token {
t.Fatal("clone received unexpected credentials")
}
default:
t.Fatalf("command did not reach git server: %v", err)
}
}
6 changes: 6 additions & 0 deletions cmd/crossplane/project/help/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ The build reuses the dependency cache populated by `crossplane dependency add`
and `crossplane dependency update-cache`. Override the cache location with
`--cache-dir` or the `CROSSPLANE_XPKG_CACHE` environment variable.

Git dependencies fetched over HTTPS can authenticate using `--git-token` and
`--git-username`. Prefer the `CROSSPLANE_GIT_TOKEN` and
`CROSSPLANE_GIT_USERNAME` environment variables to avoid exposing credentials
in shell history. The username defaults to `x-access-token`. Credentials aren't
saved in the project file.

The CLI builds embedded functions onto a runtime base image from a registry, and
caches those image layers on disk under `crossplane/base-images` in your user
cache directory. A build that needs a layer already in the cache reads it
Expand Down
Loading