mirror of
https://github.com/drone/drone-kaniko.git
synced 2026-06-04 18:23:50 +08:00
Compare commits
10 Commits
v1.11.4
...
main-patch-1
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c361d5e5e | |||
| 16758bd8cc | |||
| dd3c29c971 | |||
| c06fde824e | |||
| 5bbe6ba026 | |||
| 9491e6b36f | |||
| 594f1e2f23 | |||
| b6428af23d | |||
| f83970e37a | |||
| a1d07a3262 |
@@ -37,7 +37,7 @@ pipeline:
|
||||
identifier: Build
|
||||
spec:
|
||||
connectorRef: Plugins_Docker_Hub_Connector
|
||||
image: golang:1.23.0
|
||||
image: golang:1.25.7
|
||||
shell: Sh
|
||||
command: |-
|
||||
go test ./...
|
||||
@@ -322,7 +322,7 @@ pipeline:
|
||||
identifier: Build_and_Test
|
||||
spec:
|
||||
connectorRef: Plugins_Docker_Hub_Connector
|
||||
image: golang:1.23.0
|
||||
image: golang:1.25.7
|
||||
shell: Sh
|
||||
command: |-
|
||||
go test ./...
|
||||
|
||||
@@ -53,6 +53,45 @@ docker build \
|
||||
--file docker/ecr/Dockerfile.linux.amd64 --tag plugins/kaniko-ecr .
|
||||
```
|
||||
|
||||
### Enhanced Build Arguments Support
|
||||
|
||||
The drone-kaniko plugin now supports an improved build arguments system with the `CustomStringSliceFlag` implementation. This feature provides a more flexible way to pass multiple build arguments to your Docker builds.
|
||||
|
||||
#### Multiple Build Arguments with Semicolon Delimiter
|
||||
|
||||
A new custom CLI flag type that allows passing multiple build arguments using semicolon (`;`) as a delimiter. This flag is available across all registry implementations:
|
||||
|
||||
- `kaniko-docker`
|
||||
- `kaniko-gcr` (Google Container Registry)
|
||||
- `kaniko-ecr` (Amazon Elastic Container Registry)
|
||||
- `kaniko-acr` (Azure Container Registry)
|
||||
- `kaniko-gar` (Google Artifact Registry)
|
||||
|
||||
**Usage:**
|
||||
|
||||
```console
|
||||
docker run --rm \
|
||||
-e PLUGIN_BUILD_ARGS_NEW="ARG1=value1;ARG2=value2;ARG3=value3" \
|
||||
-e PLUGIN_REPO=foo/bar \
|
||||
-v $(pwd):/drone \
|
||||
-w /drone \
|
||||
plugins/kaniko:linux-amd64
|
||||
```
|
||||
|
||||
#### For build args containing commas
|
||||
|
||||
When your build arguments contain commas, enable the `PLUGIN_MULTIPLE_BUILD_ARGS` flag:
|
||||
|
||||
```console
|
||||
docker run --rm \
|
||||
-e PLUGIN_MULTIPLE_BUILD_ARGS=true \
|
||||
-e PLUGIN_BUILD_ARGS_NEW="KEY1=value,with,comma;KEY2=another,value" \
|
||||
-e PLUGIN_REPO=foo/bar \
|
||||
-v $(pwd):/drone \
|
||||
-w /drone \
|
||||
plugins/kaniko:linux-amd64
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Operation Modes
|
||||
|
||||
+147
-43
@@ -20,8 +20,10 @@ import (
|
||||
"github.com/urfave/cli"
|
||||
|
||||
kaniko "github.com/drone/drone-kaniko"
|
||||
azureutil "github.com/drone/drone-kaniko/internal/azure"
|
||||
"github.com/drone/drone-kaniko/pkg/artifact"
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -98,6 +100,17 @@ func main() {
|
||||
Usage: "build args",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS",
|
||||
},
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "plugin-multiple-build-agrs",
|
||||
Usage: "plugin multiple build agrs",
|
||||
EnvVar: "PLUGIN_MULTIPLE_BUILD_ARGS",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "target",
|
||||
Usage: "build target",
|
||||
@@ -156,7 +169,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "tenant-id",
|
||||
Usage: "Azure Tenant Id",
|
||||
EnvVar: "TENANT_ID",
|
||||
EnvVar: "TENANT_ID,AZURE_TENANT_ID,PLUGIN_TENANT_ID",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "subscription-id",
|
||||
@@ -165,8 +178,18 @@ func main() {
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "client-id",
|
||||
Usage: "Azure Client Id",
|
||||
EnvVar: "CLIENT_ID",
|
||||
Usage: "Azure Client ID (also called App ID)",
|
||||
EnvVar: "CLIENT_ID,AZURE_CLIENT_ID,PLUGIN_CLIENT_ID,AZURE_APP_ID",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "oidc-token-id",
|
||||
Usage: "OIDC ID token to exchange for Azure AD access token (federated credentials)",
|
||||
EnvVar: "PLUGIN_OIDC_TOKEN_ID",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "azure-authority-host",
|
||||
Usage: "Azure authority host base URL (e.g., https://login.microsoftonline.com, https://login.microsoftonline.us)",
|
||||
EnvVar: "AZURE_AUTHORITY_HOST",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "snapshot-mode",
|
||||
@@ -231,7 +254,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
|
||||
EnvVar: "PLUGIN_PLATFORM",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "skip-unused-stages",
|
||||
@@ -269,11 +292,6 @@ func main() {
|
||||
Usage: "Sub-path within the context to build.",
|
||||
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "custom-platform",
|
||||
Usage: "Platform to use for building.",
|
||||
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force building the image even if it already exists.",
|
||||
@@ -405,9 +423,17 @@ func run(c *cli.Context) error {
|
||||
registry := c.String("registry")
|
||||
noPush := c.Bool("no-push")
|
||||
|
||||
publicUrl, err := setupAuth(
|
||||
c.String("tenant-id"),
|
||||
c.String("client-id"),
|
||||
clientID := c.String("client-id")
|
||||
tenantID := c.String("tenant-id")
|
||||
oidcIdToken := c.String("oidc-token-id")
|
||||
authorityHost := c.String("azure-authority-host")
|
||||
|
||||
var publicUrl string
|
||||
var err error
|
||||
publicUrl, err = setupAuth(
|
||||
tenantID,
|
||||
clientID,
|
||||
oidcIdToken,
|
||||
c.String("client-cert"),
|
||||
c.String("client-secret"),
|
||||
c.String("subscription-id"),
|
||||
@@ -415,6 +441,7 @@ func run(c *cli.Context) error {
|
||||
c.String("base-image-username"),
|
||||
c.String("base-image-password"),
|
||||
c.String("base-image-registry"),
|
||||
authorityHost,
|
||||
noPush,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -432,6 +459,8 @@ func run(c *cli.Context) error {
|
||||
AutoTagSuffix: c.String("auto-tag-suffix"),
|
||||
ExpandTag: c.Bool("expand-tag"),
|
||||
Args: c.StringSlice("args"),
|
||||
ArgsNew: c.Generic("args-new").(*utils.CustomStringSliceFlag).GetValue(),
|
||||
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
|
||||
Target: c.String("target"),
|
||||
Repo: c.String("repo"),
|
||||
Mirrors: c.StringSlice("registry-mirrors"),
|
||||
@@ -443,14 +472,13 @@ func run(c *cli.Context) error {
|
||||
DigestFile: defaultDigestFile,
|
||||
NoPush: noPush,
|
||||
Verbosity: c.String("verbosity"),
|
||||
Platform: c.String("platform"),
|
||||
CustomPlatform: c.String("platform"),
|
||||
SkipUnusedStages: c.Bool("skip-unused-stages"),
|
||||
CacheDir: c.String("cache-dir"),
|
||||
CacheCopyLayers: c.Bool("cache-copy-layers"),
|
||||
CacheRunLayers: c.Bool("cache-run-layers"),
|
||||
Cleanup: c.Bool("cleanup"),
|
||||
ContextSubPath: c.String("context-sub-path"),
|
||||
CustomPlatform: c.String("custom-platform"),
|
||||
Force: c.Bool("force"),
|
||||
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
|
||||
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
|
||||
@@ -502,47 +530,114 @@ func run(c *cli.Context) error {
|
||||
return plugin.Exec()
|
||||
}
|
||||
|
||||
func setupAuth(tenantId, clientId, cert,
|
||||
clientSecret, subscriptionId, registry, dockerUsername, dockerPassword, dockerRegistry string, noPush bool) (string, error) {
|
||||
func setupAuth(tenantId, clientId, oidcIdToken, cert,
|
||||
clientSecret, subscriptionId, registry, dockerUsername, dockerPassword, dockerRegistry, authorityHost string, noPush bool) (string, error) {
|
||||
if registry == "" {
|
||||
return "", fmt.Errorf("registry must be specified")
|
||||
}
|
||||
|
||||
// case of client secret or cert based auth
|
||||
if clientId != "" {
|
||||
// only setup auth when pushing or credentials are defined
|
||||
var aadAccessToken string
|
||||
var acrToken string
|
||||
var publicUrl string
|
||||
var err error
|
||||
|
||||
token, publicUrl, err := getACRToken(subscriptionId, tenantId, clientId, clientSecret, cert, registry)
|
||||
if oidcIdToken != "" {
|
||||
// OIDC authentication flow requires tenantId and clientId
|
||||
if tenantId == "" || clientId == "" {
|
||||
if noPush {
|
||||
logrus.Warnf("NO_PUSH mode: tenantId or clientId not provided for OIDC")
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("tenantId and clientId must be provided for OIDC authentication")
|
||||
}
|
||||
logrus.Debug("Using OIDC authentication flow")
|
||||
// Exchange OIDC ID token for AAD access token via client_assertion
|
||||
aadAccessToken, err = azureutil.GetAADAccessTokenViaClientAssertion(context.Background(), tenantId, clientId, oidcIdToken, authorityHost)
|
||||
if err != nil {
|
||||
if noPush {
|
||||
logrus.Warnf("NO_PUSH mode: failed to fetch ACR Token: %v", err)
|
||||
return "", nil
|
||||
}
|
||||
return "", errors.Wrap(err, "failed to fetch ACR Token")
|
||||
return handleError(noPush, err, "failed to get AAD token via OIDC")
|
||||
}
|
||||
|
||||
// setup docker config for azure registry and base image docker registry
|
||||
if err := setDockerAuth(username, token, registry, dockerUsername, dockerPassword, dockerRegistry); err != nil {
|
||||
if noPush {
|
||||
logrus.Warnf("NO_PUSH mode: failed to create docker config: %v", err)
|
||||
return "", nil
|
||||
}
|
||||
return "", errors.Wrap(err, "failed to create docker config")
|
||||
publicUrl, err = getPublicUrl(aadAccessToken, registry, subscriptionId)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to get public url with error: %s\n", err)
|
||||
}
|
||||
// Exchange AAD access token to ACR refresh token
|
||||
acrToken, err = fetchACRToken(tenantId, aadAccessToken, registry)
|
||||
if err != nil {
|
||||
return handleError(noPush, err, "failed to fetch ACR token")
|
||||
}
|
||||
return publicUrl, nil
|
||||
} else {
|
||||
if noPush {
|
||||
return "", nil
|
||||
logrus.Debug("Using traditional Azure AD authentication flow")
|
||||
// Validate that if tenantId is provided, clientId must also be provided
|
||||
// (unless using managed identity with no explicit tenantId)
|
||||
if tenantId != "" && clientId == "" && clientSecret == "" && cert == "" {
|
||||
if noPush {
|
||||
logrus.Warnf("NO_PUSH mode: tenantId provided but clientId is missing")
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("tenantId and clientId must be provided")
|
||||
}
|
||||
acrToken, publicUrl, err = getACRToken(subscriptionId, tenantId, clientId, clientSecret, cert, registry)
|
||||
if err != nil {
|
||||
return handleError(noPush, err, "failed to fetch ACR Token")
|
||||
}
|
||||
return "", fmt.Errorf("managed authentication is not supported")
|
||||
}
|
||||
|
||||
if err := setDockerAuth(username, acrToken, registry, dockerUsername, dockerPassword, dockerRegistry); err != nil {
|
||||
return handleError(noPush, err, "failed to create docker config")
|
||||
}
|
||||
return publicUrl, nil
|
||||
}
|
||||
|
||||
// Error handling
|
||||
func handleError(noPush bool, err error, msg string) (string, error) {
|
||||
if noPush {
|
||||
logrus.Warnf("NO_PUSH mode: %s: %v", msg, err)
|
||||
return "", nil
|
||||
}
|
||||
return "", errors.Wrap(err, msg)
|
||||
}
|
||||
|
||||
func getACRToken(subscriptionId, tenantId, clientId, clientSecret, cert, registry string) (string, string, error) {
|
||||
// Handle managed identity (when no clientSecret or cert provided)
|
||||
if clientSecret == "" && cert == "" {
|
||||
if tenantId == "" {
|
||||
tenantId = os.Getenv("AZURE_TENANT_ID")
|
||||
if tenantId == "" {
|
||||
tenantId = os.Getenv("TENANT_ID")
|
||||
}
|
||||
}
|
||||
opts := &azidentity.DefaultAzureCredentialOptions{}
|
||||
if tenantId != "" {
|
||||
opts.TenantID = tenantId
|
||||
}
|
||||
cred, err := azidentity.NewDefaultAzureCredential(opts)
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, "failed to get credentials")
|
||||
}
|
||||
policy := policy.TokenRequestOptions{
|
||||
Scopes: []string{"https://management.azure.com/.default"},
|
||||
}
|
||||
azToken, err := cred.GetToken(context.Background(), policy)
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, "failed to fetch access token")
|
||||
}
|
||||
publicUrl, err := getPublicUrl(azToken.Token, registry, subscriptionId)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to get public url with error: %s\n", err)
|
||||
}
|
||||
if tenantId == "" {
|
||||
return "", "", fmt.Errorf("tenantId cannot be empty for ACR token exchange")
|
||||
}
|
||||
ACRToken, err := fetchACRToken(tenantId, azToken.Token, registry)
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, "failed to fetch ACR token")
|
||||
}
|
||||
return ACRToken, publicUrl, nil
|
||||
}
|
||||
|
||||
if tenantId == "" {
|
||||
return "", "", fmt.Errorf("tenantId can't be empty for AAD authentication")
|
||||
}
|
||||
|
||||
if clientId == "" {
|
||||
return "", "", fmt.Errorf("clientId can't be empty for AAD authentication")
|
||||
}
|
||||
@@ -748,10 +843,18 @@ func handlePushOnly(c *cli.Context) error {
|
||||
return fmt.Errorf("repository and registry must be specified for push-only operation")
|
||||
}
|
||||
|
||||
// Setup ACR authentication
|
||||
publicUrl, err := setupAuth(
|
||||
c.String("tenant-id"),
|
||||
c.String("client-id"),
|
||||
// Resolve Azure client/tenant and OIDC via CLI flags
|
||||
clientID := c.String("client-id")
|
||||
tenantID := c.String("tenant-id")
|
||||
oidcIdToken := c.String("oidc-token-id")
|
||||
authorityHost := c.String("azure-authority-host")
|
||||
|
||||
var publicUrl string
|
||||
var err error
|
||||
publicUrl, err = setupAuth(
|
||||
tenantID,
|
||||
clientID,
|
||||
oidcIdToken,
|
||||
c.String("client-cert"),
|
||||
c.String("client-secret"),
|
||||
c.String("subscription-id"),
|
||||
@@ -759,7 +862,8 @@ func handlePushOnly(c *cli.Context) error {
|
||||
c.String("base-image-username"),
|
||||
c.String("base-image-password"),
|
||||
c.String("base-image-registry"),
|
||||
false, // We want to push in push-only mode
|
||||
authorityHost,
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -154,3 +156,283 @@ func TestCreateDockerConfigWithoutBaseRegistry(t *testing.T) {
|
||||
_, exists := config.Auths[""]
|
||||
assert.False(t, exists)
|
||||
}
|
||||
|
||||
func TestCustomStringSliceFlagIntegration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "single build arg",
|
||||
input: "ARG1=value1",
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "multiple build args with semicolon",
|
||||
input: "ARG1=value1;ARG2=value2;ARG3=value3",
|
||||
expected: []string{"ARG1=value1", "ARG2=value2", "ARG3=value3"},
|
||||
},
|
||||
{
|
||||
name: "build args with spaces",
|
||||
input: "ARG1=value with spaces;ARG2=another value",
|
||||
expected: []string{"ARG1=value with spaces", "ARG2=another value"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test the CustomStringSliceFlag directly
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
result := flag.GetValue()
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if result[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, result[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIIntegrationWithCustomFlag(t *testing.T) {
|
||||
// Test CLI integration with proper flag setup
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "CLI with single arg",
|
||||
args: []string{"acr-test", "--args-new", "ARG1=value1"},
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "CLI with multiple args",
|
||||
args: []string{"acr-test", "--args-new", "ARG1=value1;ARG2=value2"},
|
||||
expected: []string{"ARG1=value1", "ARG2=value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
app.Name = "acr-test"
|
||||
|
||||
var capturedArgs []string
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if genericFlag := c.Generic("args-new"); genericFlag != nil {
|
||||
if customFlag, ok := genericFlag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run(tt.args)
|
||||
if err != nil {
|
||||
t.Errorf("CLI run error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(capturedArgs) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(capturedArgs), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if capturedArgs[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, capturedArgs[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestACRBuildArgsProcessing(t *testing.T) {
|
||||
// Test that build args are correctly processed in the context of ACR plugin
|
||||
tests := []struct {
|
||||
name string
|
||||
argsNew string
|
||||
expectedCount int
|
||||
expectedFirst string
|
||||
}{
|
||||
{
|
||||
name: "docker build args format",
|
||||
argsNew: "GOOS=linux;GOARCH=amd64;CGO_ENABLED=0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "GOOS=linux",
|
||||
},
|
||||
{
|
||||
name: "azure specific args",
|
||||
argsNew: "AZURE_TENANT_ID=tenant123;AZURE_CLIENT_ID=client456",
|
||||
expectedCount: 2,
|
||||
expectedFirst: "AZURE_TENANT_ID=tenant123",
|
||||
},
|
||||
{
|
||||
name: "single complex arg with special characters",
|
||||
argsNew: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
expectedCount: 1,
|
||||
expectedFirst: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.argsNew)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
args := flag.GetValue()
|
||||
if len(args) != tt.expectedCount {
|
||||
t.Errorf("Got %d args, want %d", len(args), tt.expectedCount)
|
||||
return
|
||||
}
|
||||
|
||||
if len(args) > 0 && args[0] != tt.expectedFirst {
|
||||
t.Errorf("Got first arg = %v, want %v", args[0], tt.expectedFirst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestACRAuthenticationFlow(t *testing.T) {
|
||||
// Test that ACR authentication works with build args
|
||||
tests := []struct {
|
||||
name string
|
||||
tenantId string
|
||||
clientId string
|
||||
clientSecret string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "missing tenant id",
|
||||
tenantId: "",
|
||||
clientId: "client123",
|
||||
clientSecret: "secret456",
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
name: "missing client id",
|
||||
tenantId: "tenant123",
|
||||
clientId: "",
|
||||
clientSecret: "secret456",
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
name: "missing client secret",
|
||||
tenantId: "tenant123",
|
||||
clientId: "client456",
|
||||
clientSecret: "",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This test validates the parameter validation logic
|
||||
// without actually making network calls
|
||||
if tt.tenantId == "" && !tt.expectError {
|
||||
t.Error("Expected error for missing tenant ID")
|
||||
}
|
||||
if tt.clientId == "" && !tt.expectError {
|
||||
t.Error("Expected error for missing client ID")
|
||||
}
|
||||
if tt.clientSecret == "" && !tt.expectError {
|
||||
t.Error("Expected error for missing client secret")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupAuth_RegistryMustBeSpecified(t *testing.T) {
|
||||
pub, err := setupAuth("tenant", "client", "", "", "", "sub", "", "", "", "", "", false)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "registry must be specified")
|
||||
assert.Equal(t, "", pub)
|
||||
}
|
||||
|
||||
func TestSetupAuth_MissingTenantOrClient(t *testing.T) {
|
||||
pub, err := setupAuth("tenant", "", "", "", "", "sub", "myregistry.azurecr.io", "", "", "", "", false)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "tenantId and clientId must be provided")
|
||||
assert.Equal(t, "", pub)
|
||||
}
|
||||
|
||||
func TestSetupAuth_NoCreds_NoPushTrue(t *testing.T) {
|
||||
pub, err := setupAuth("tenant", "client", "", "", "", "sub", "myregistry.azurecr.io", "", "", "", "", true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "", pub)
|
||||
}
|
||||
|
||||
// Test cases for managed identity support
|
||||
|
||||
func TestSetupAuth_ManagedIdentity_NoPush_Positive(t *testing.T) {
|
||||
// Positive test: Managed identity flow with noPush=true should succeed
|
||||
// This tests the new managed identity support when no credentials are provided
|
||||
pub, err := setupAuth("tenant123", "", "", "", "", "sub", "myregistry.azurecr.io", "", "", "", "", true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "", pub)
|
||||
}
|
||||
|
||||
func TestSetupAuth_TenantIdButNoClientId_ManagedIdentity(t *testing.T) {
|
||||
// Negative test: When tenantId is provided but clientId is missing for managed identity,
|
||||
// it should fail (unless noPush is true)
|
||||
pub, err := setupAuth("tenant123", "", "", "", "", "sub", "myregistry.azurecr.io", "", "", "", "", false)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "tenantId and clientId must be provided")
|
||||
assert.Equal(t, "", pub)
|
||||
}
|
||||
|
||||
func TestGetACRToken_ManagedIdentity_NoTenantId(t *testing.T) {
|
||||
// Negative test: Managed identity requires tenantId for ACR token exchange
|
||||
// Clear environment variables to ensure tenantId is not available
|
||||
originalTenantId := os.Getenv("AZURE_TENANT_ID")
|
||||
originalTenantId2 := os.Getenv("TENANT_ID")
|
||||
defer func() {
|
||||
if originalTenantId != "" {
|
||||
os.Setenv("AZURE_TENANT_ID", originalTenantId)
|
||||
} else {
|
||||
os.Unsetenv("AZURE_TENANT_ID")
|
||||
}
|
||||
if originalTenantId2 != "" {
|
||||
os.Setenv("TENANT_ID", originalTenantId2)
|
||||
} else {
|
||||
os.Unsetenv("TENANT_ID")
|
||||
}
|
||||
}()
|
||||
os.Unsetenv("AZURE_TENANT_ID")
|
||||
os.Unsetenv("TENANT_ID")
|
||||
|
||||
// Managed identity path without tenantId should fail
|
||||
// The failure occurs when DefaultAzureCredential tries to acquire a token
|
||||
// since tenantId is required for ACR token exchange but not available
|
||||
_, _, err := getACRToken("sub", "", "", "", "", "myregistry.azurecr.io")
|
||||
assert.Error(t, err)
|
||||
// The error will be from DefaultAzureCredential failing to acquire a token
|
||||
// because tenantId is missing and no credentials are available
|
||||
assert.Contains(t, err.Error(), "failed to fetch access token")
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
kaniko "github.com/drone/drone-kaniko"
|
||||
"github.com/drone/drone-kaniko/pkg/artifact"
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -102,6 +103,17 @@ func main() {
|
||||
Usage: "build args",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS",
|
||||
},
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "plugin-multiple-build-agrs",
|
||||
Usage: "plugin multiple build agrs",
|
||||
EnvVar: "PLUGIN_MULTIPLE_BUILD_ARGS",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "target",
|
||||
Usage: "build target",
|
||||
@@ -201,7 +213,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
|
||||
EnvVar: "PLUGIN_PLATFORM",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "skip-unused-stages",
|
||||
@@ -239,16 +251,12 @@ func main() {
|
||||
Usage: "Enable or disable compressed caching.",
|
||||
EnvVar: "PLUGIN_COMPRESSED_CACHING",
|
||||
},
|
||||
|
||||
cli.StringFlag{
|
||||
Name: "context-sub-path",
|
||||
Usage: "Sub-path within the context to build.",
|
||||
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "custom-platform",
|
||||
Usage: "Platform to use for building.",
|
||||
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force building the image even if it already exists.",
|
||||
@@ -421,6 +429,8 @@ func run(c *cli.Context) error {
|
||||
AutoTagSuffix: c.String("auto-tag-suffix"),
|
||||
ExpandTag: c.Bool("expand-tag"),
|
||||
Args: c.StringSlice("args"),
|
||||
ArgsNew: c.Generic("args-new").(*utils.CustomStringSliceFlag).GetValue(),
|
||||
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
|
||||
Target: c.String("target"),
|
||||
Repo: buildRepo(c.String("registry"), c.String("repo"), c.Bool("expand-repo")),
|
||||
Mirrors: c.StringSlice("registry-mirrors"),
|
||||
@@ -434,7 +444,7 @@ func run(c *cli.Context) error {
|
||||
NoPush: noPush,
|
||||
TarPath: c.String("tar-path"),
|
||||
Verbosity: c.String("verbosity"),
|
||||
Platform: c.String("platform"),
|
||||
CustomPlatform: c.String("platform"),
|
||||
PushOnly: c.Bool("push-only"),
|
||||
SkipUnusedStages: c.Bool("skip-unused-stages"),
|
||||
CacheDir: c.String("cache-dir"),
|
||||
@@ -442,7 +452,6 @@ func run(c *cli.Context) error {
|
||||
CacheRunLayers: c.Bool("cache-run-layers"),
|
||||
Cleanup: c.Bool("cleanup"),
|
||||
ContextSubPath: c.String("context-sub-path"),
|
||||
CustomPlatform: c.String("custom-platform"),
|
||||
Force: c.Bool("force"),
|
||||
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
|
||||
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
func Test_buildRepo(t *testing.T) {
|
||||
@@ -42,6 +44,226 @@ func Test_buildRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomStringSliceFlagIntegration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "single build arg",
|
||||
input: "ARG1=value1",
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "multiple build args with semicolon",
|
||||
input: "ARG1=value1;ARG2=value2;ARG3=value3",
|
||||
expected: []string{"ARG1=value1", "ARG2=value2", "ARG3=value3"},
|
||||
},
|
||||
{
|
||||
name: "build args with spaces",
|
||||
input: "ARG1=value with spaces;ARG2=another value",
|
||||
expected: []string{"ARG1=value with spaces", "ARG2=another value"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test the CustomStringSliceFlag directly
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
result := flag.GetValue()
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if result[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, result[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIIntegrationWithCustomFlag(t *testing.T) {
|
||||
// Test CLI integration with proper flag setup
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "CLI with single arg",
|
||||
args: []string{"docker-test", "--args-new", "ARG1=value1"},
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "CLI with multiple args",
|
||||
args: []string{"docker-test", "--args-new", "ARG1=value1;ARG2=value2"},
|
||||
expected: []string{"ARG1=value1", "ARG2=value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
app.Name = "docker-test"
|
||||
|
||||
var capturedArgs []string
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if genericFlag := c.Generic("args-new"); genericFlag != nil {
|
||||
if customFlag, ok := genericFlag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run(tt.args)
|
||||
if err != nil {
|
||||
t.Errorf("CLI run error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(capturedArgs) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(capturedArgs), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if capturedArgs[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, capturedArgs[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerBuildArgsProcessing(t *testing.T) {
|
||||
// Test that build args are correctly processed in the context of Docker plugin
|
||||
tests := []struct {
|
||||
name string
|
||||
argsNew string
|
||||
expectedCount int
|
||||
expectedFirst string
|
||||
}{
|
||||
{
|
||||
name: "docker build args format",
|
||||
argsNew: "GOOS=linux;GOARCH=amd64;CGO_ENABLED=0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "GOOS=linux",
|
||||
},
|
||||
{
|
||||
name: "single complex arg with special characters",
|
||||
argsNew: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
expectedCount: 1,
|
||||
expectedFirst: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
},
|
||||
{
|
||||
name: "args with equals and semicolons",
|
||||
argsNew: "API_URL=https://api.example.com;DEBUG=true;VERSION=1.0.0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "API_URL=https://api.example.com",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.argsNew)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
args := flag.GetValue()
|
||||
if len(args) != tt.expectedCount {
|
||||
t.Errorf("Got %d args, want %d", len(args), tt.expectedCount)
|
||||
return
|
||||
}
|
||||
|
||||
if len(args) > 0 && args[0] != tt.expectedFirst {
|
||||
t.Errorf("Got first arg = %v, want %v", args[0], tt.expectedFirst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformEnvVarMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envVar string
|
||||
envValue string
|
||||
expectedValue string
|
||||
}{
|
||||
{
|
||||
name: "PLUGIN_PLATFORM env var",
|
||||
envVar: "PLUGIN_PLATFORM",
|
||||
envValue: "linux/amd64",
|
||||
expectedValue: "linux/amd64",
|
||||
},
|
||||
{
|
||||
name: "PLUGIN_CUSTOM_PLATFORM env var",
|
||||
envVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
envValue: "linux/arm64",
|
||||
expectedValue: "linux/arm64",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Set the environment variable
|
||||
os.Setenv(tt.envVar, tt.envValue)
|
||||
defer os.Unsetenv(tt.envVar)
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Name = "kaniko-docker-test"
|
||||
|
||||
var capturedPlatform string
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
}
|
||||
|
||||
app.Action = func(c *cli.Context) error {
|
||||
capturedPlatform = c.String("platform")
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run([]string{"kaniko-docker-test"})
|
||||
if err != nil {
|
||||
t.Errorf("CLI run error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
if capturedPlatform != tt.expectedValue {
|
||||
t.Errorf("Got platform = %v, want %v", capturedPlatform, tt.expectedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDockerConfig(t *testing.T) {
|
||||
config := docker.NewConfig()
|
||||
tempDir, err := ioutil.TempDir("", "docker-config-test")
|
||||
|
||||
+5
-10
@@ -30,6 +30,7 @@ import (
|
||||
kaniko "github.com/drone/drone-kaniko"
|
||||
"github.com/drone/drone-kaniko/pkg/artifact"
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/google/go-containerregistry/pkg/authn"
|
||||
"github.com/google/go-containerregistry/pkg/crane"
|
||||
)
|
||||
@@ -132,7 +133,7 @@ func main() {
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(CustomStringSliceFlag),
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "plugin-multiple-build-agrs",
|
||||
@@ -243,7 +244,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
|
||||
EnvVar: "PLUGIN_PLATFORM",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "skip-unused-stages",
|
||||
@@ -281,11 +282,6 @@ func main() {
|
||||
Usage: "Sub-path within the context to build.",
|
||||
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "custom-platform",
|
||||
Usage: "Platform to use for building.",
|
||||
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force building the image even if it already exists.",
|
||||
@@ -504,7 +500,7 @@ func run(c *cli.Context) error {
|
||||
AutoTagSuffix: c.String("auto-tag-suffix"),
|
||||
ExpandTag: c.Bool("expand-tag"),
|
||||
Args: c.StringSlice("args"),
|
||||
ArgsNew: c.Generic("args-new").(*CustomStringSliceFlag).GetValue(),
|
||||
ArgsNew: c.Generic("args-new").(*utils.CustomStringSliceFlag).GetValue(),
|
||||
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
|
||||
Target: c.String("target"),
|
||||
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
|
||||
@@ -517,14 +513,13 @@ func run(c *cli.Context) error {
|
||||
DigestFile: defaultDigestFile,
|
||||
NoPush: noPush,
|
||||
Verbosity: c.String("verbosity"),
|
||||
Platform: c.String("platform"),
|
||||
CustomPlatform: c.String("platform"),
|
||||
SkipUnusedStages: c.Bool("skip-unused-stages"),
|
||||
CacheDir: c.String("cache-dir"),
|
||||
CacheCopyLayers: c.Bool("cache-copy-layers"),
|
||||
CacheRunLayers: c.Bool("cache-run-layers"),
|
||||
Cleanup: c.Bool("cleanup"),
|
||||
ContextSubPath: c.String("context-sub-path"),
|
||||
CustomPlatform: c.String("custom-platform"),
|
||||
Force: c.Bool("force"),
|
||||
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
|
||||
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
func TestCreateDockerConfigForECRWithBaseRegistry(t *testing.T) {
|
||||
@@ -43,3 +45,165 @@ func TestCreateDockerConfigForECRWithBaseRegistry(t *testing.T) {
|
||||
expectedDockerAuth := docker.Auth{Auth: base64.StdEncoding.EncodeToString([]byte(dockerUsername + ":" + dockerPassword))}
|
||||
assert.Equal(t, expectedDockerAuth, config.Auths[dockerRegistry])
|
||||
}
|
||||
|
||||
func TestCustomStringSliceFlagIntegration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "single build arg",
|
||||
input: "ARG1=value1",
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "multiple build args with semicolon",
|
||||
input: "ARG1=value1;ARG2=value2;ARG3=value3",
|
||||
expected: []string{"ARG1=value1", "ARG2=value2", "ARG3=value3"},
|
||||
},
|
||||
{
|
||||
name: "build args with spaces",
|
||||
input: "ARG1=value with spaces;ARG2=another value",
|
||||
expected: []string{"ARG1=value with spaces", "ARG2=another value"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test the CustomStringSliceFlag directly
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
result := flag.GetValue()
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if result[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, result[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIIntegrationWithCustomFlag(t *testing.T) {
|
||||
// Test CLI integration with proper flag setup
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "CLI with single arg",
|
||||
args: []string{"ecr-test", "--args-new", "ARG1=value1"},
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "CLI with multiple args",
|
||||
args: []string{"ecr-test", "--args-new", "ARG1=value1;ARG2=value2"},
|
||||
expected: []string{"ARG1=value1", "ARG2=value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
app.Name = "ecr-test"
|
||||
|
||||
var capturedArgs []string
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if genericFlag := c.Generic("args-new"); genericFlag != nil {
|
||||
if customFlag, ok := genericFlag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run(tt.args)
|
||||
if err != nil {
|
||||
t.Errorf("CLI run error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(capturedArgs) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(capturedArgs), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if capturedArgs[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, capturedArgs[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestECRBuildArgsProcessing(t *testing.T) {
|
||||
// Test that build args are correctly processed in the context of ECR plugin
|
||||
tests := []struct {
|
||||
name string
|
||||
argsNew string
|
||||
expectedCount int
|
||||
expectedFirst string
|
||||
}{
|
||||
{
|
||||
name: "docker build args format",
|
||||
argsNew: "GOOS=linux;GOARCH=amd64;CGO_ENABLED=0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "GOOS=linux",
|
||||
},
|
||||
{
|
||||
name: "aws specific args",
|
||||
argsNew: "AWS_REGION=us-west-2;AWS_ACCOUNT_ID=123456789012",
|
||||
expectedCount: 2,
|
||||
expectedFirst: "AWS_REGION=us-west-2",
|
||||
},
|
||||
{
|
||||
name: "single complex arg with special characters",
|
||||
argsNew: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
expectedCount: 1,
|
||||
expectedFirst: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.argsNew)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
args := flag.GetValue()
|
||||
if len(args) != tt.expectedCount {
|
||||
t.Errorf("Got %d args, want %d", len(args), tt.expectedCount)
|
||||
return
|
||||
}
|
||||
|
||||
if len(args) > 0 && args[0] != tt.expectedFirst {
|
||||
t.Errorf("Got first arg = %v, want %v", args[0], tt.expectedFirst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+17
-8
@@ -18,6 +18,8 @@ import (
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/google/go-containerregistry/pkg/authn"
|
||||
"github.com/google/go-containerregistry/pkg/crane"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -96,6 +98,17 @@ func main() {
|
||||
Usage: "build args",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS",
|
||||
},
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "plugin-multiple-build-agrs",
|
||||
Usage: "plugin multiple build agrs",
|
||||
EnvVar: "PLUGIN_MULTIPLE_BUILD_ARGS",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "target",
|
||||
Usage: "build target",
|
||||
@@ -194,7 +207,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
|
||||
EnvVar: "PLUGIN_PLATFORM",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "skip-unused-stages",
|
||||
@@ -232,11 +245,6 @@ func main() {
|
||||
Usage: "Sub-path within the context to build.",
|
||||
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "custom-platform",
|
||||
Usage: "Platform to use for building.",
|
||||
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force building the image even if it already exists.",
|
||||
@@ -401,6 +409,8 @@ func run(c *cli.Context) error {
|
||||
AutoTagSuffix: c.String("auto-tag-suffix"),
|
||||
ExpandTag: c.Bool("expand-tag"),
|
||||
Args: c.StringSlice("args"),
|
||||
ArgsNew: c.Generic("args-new").(*utils.CustomStringSliceFlag).GetValue(),
|
||||
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
|
||||
Target: c.String("target"),
|
||||
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
|
||||
Mirrors: c.StringSlice("registry-mirrors"),
|
||||
@@ -415,14 +425,13 @@ func run(c *cli.Context) error {
|
||||
SourceTarPath: c.String("source-tar-path"),
|
||||
TarPath: c.String("tar-path"),
|
||||
Verbosity: c.String("verbosity"),
|
||||
Platform: c.String("platform"),
|
||||
CustomPlatform: c.String("platform"),
|
||||
SkipUnusedStages: c.Bool("skip-unused-stages"),
|
||||
CacheDir: c.String("cache-dir"),
|
||||
CacheCopyLayers: c.Bool("cache-copy-layers"),
|
||||
CacheRunLayers: c.Bool("cache-run-layers"),
|
||||
Cleanup: c.Bool("cleanup"),
|
||||
ContextSubPath: c.String("context-sub-path"),
|
||||
CustomPlatform: c.String("custom-platform"),
|
||||
Force: c.Bool("force"),
|
||||
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
|
||||
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
func TestCustomStringSliceFlagIntegration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "single build arg",
|
||||
input: "ARG1=value1",
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "multiple build args with semicolon",
|
||||
input: "ARG1=value1;ARG2=value2;ARG3=value3",
|
||||
expected: []string{"ARG1=value1", "ARG2=value2", "ARG3=value3"},
|
||||
},
|
||||
{
|
||||
name: "build args with spaces",
|
||||
input: "ARG1=value with spaces;ARG2=another value",
|
||||
expected: []string{"ARG1=value with spaces", "ARG2=another value"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test the CustomStringSliceFlag directly
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
result := flag.GetValue()
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if result[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, result[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIIntegrationWithCustomFlag(t *testing.T) {
|
||||
// Test CLI integration with proper flag setup
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "CLI with single arg",
|
||||
args: []string{"gar-test", "--args-new", "ARG1=value1"},
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "CLI with multiple args",
|
||||
args: []string{"gar-test", "--args-new", "ARG1=value1;ARG2=value2"},
|
||||
expected: []string{"ARG1=value1", "ARG2=value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := cli.NewApp()
|
||||
app.Name = "gar-test"
|
||||
|
||||
var capturedArgs []string
|
||||
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if genericFlag := c.Generic("args-new"); genericFlag != nil {
|
||||
if customFlag, ok := genericFlag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run(tt.args)
|
||||
if err != nil {
|
||||
t.Errorf("CLI run error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(capturedArgs) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(capturedArgs), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if capturedArgs[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, capturedArgs[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvironmentVariableIntegration(t *testing.T) {
|
||||
// Test that environment variables work with CustomStringSliceFlag
|
||||
originalEnv := os.Getenv("PLUGIN_BUILD_ARGS_NEW")
|
||||
defer func() {
|
||||
if originalEnv != "" {
|
||||
os.Setenv("PLUGIN_BUILD_ARGS_NEW", originalEnv)
|
||||
} else {
|
||||
os.Unsetenv("PLUGIN_BUILD_ARGS_NEW")
|
||||
}
|
||||
}()
|
||||
|
||||
os.Setenv("PLUGIN_BUILD_ARGS_NEW", "ENV_ARG1=env_value1;ENV_ARG2=env_value2")
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
var capturedArgs []string
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if flag := c.Generic("args-new"); flag != nil {
|
||||
if customFlag, ok := flag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run([]string{"test"})
|
||||
if err != nil {
|
||||
t.Errorf("App.Run() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
expected := []string{"ENV_ARG1=env_value1", "ENV_ARG2=env_value2"}
|
||||
if len(capturedArgs) != len(expected) {
|
||||
t.Errorf("Environment variable test: got %d args, want %d", len(capturedArgs), len(expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, exp := range expected {
|
||||
if capturedArgs[i] != exp {
|
||||
t.Errorf("Environment variable test: got arg[%d] = %v, want %v", i, capturedArgs[i], exp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGARBuildArgsProcessing(t *testing.T) {
|
||||
// Test that build args are correctly processed in the context of GAR plugin
|
||||
tests := []struct {
|
||||
name string
|
||||
argsNew string
|
||||
expectedCount int
|
||||
expectedFirst string
|
||||
}{
|
||||
{
|
||||
name: "docker build args format",
|
||||
argsNew: "GOOS=linux;GOARCH=amd64;CGO_ENABLED=0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "GOOS=linux",
|
||||
},
|
||||
{
|
||||
name: "google cloud specific args",
|
||||
argsNew: "GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json;PROJECT_ID=my-project",
|
||||
expectedCount: 2,
|
||||
expectedFirst: "GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json",
|
||||
},
|
||||
{
|
||||
name: "single complex arg with special characters",
|
||||
argsNew: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
expectedCount: 1,
|
||||
expectedFirst: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.argsNew)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
args := flag.GetValue()
|
||||
if len(args) != tt.expectedCount {
|
||||
t.Errorf("Got %d args, want %d", len(args), tt.expectedCount)
|
||||
return
|
||||
}
|
||||
|
||||
if len(args) > 0 && args[0] != tt.expectedFirst {
|
||||
t.Errorf("Got first arg = %v, want %v", args[0], tt.expectedFirst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGARRegistryFormatting(t *testing.T) {
|
||||
// Test GAR-specific registry formatting
|
||||
tests := []struct {
|
||||
name string
|
||||
registry string
|
||||
repo string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "standard GAR format",
|
||||
registry: "us-central1-docker.pkg.dev",
|
||||
repo: "my-project/my-repo/my-image",
|
||||
expected: "us-central1-docker.pkg.dev/my-project/my-repo/my-image",
|
||||
},
|
||||
{
|
||||
name: "different region",
|
||||
registry: "europe-west1-docker.pkg.dev",
|
||||
repo: "project123/repo456/image789",
|
||||
expected: "europe-west1-docker.pkg.dev/project123/repo456/image789",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This would be the format used in the GAR plugin
|
||||
result := tt.registry + "/" + tt.repo
|
||||
if result != tt.expected {
|
||||
t.Errorf("GAR formatting: got %v, want %v", result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGARAuthSetup(t *testing.T) {
|
||||
// Test GAR authentication setup
|
||||
tests := []struct {
|
||||
name string
|
||||
jsonKey string
|
||||
expectAuthFile bool
|
||||
}{
|
||||
{
|
||||
name: "with json key",
|
||||
jsonKey: `{"type":"service_account","project_id":"test"}`,
|
||||
expectAuthFile: true,
|
||||
},
|
||||
{
|
||||
name: "without json key (workload identity)",
|
||||
jsonKey: "",
|
||||
expectAuthFile: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This simulates the auth setup logic
|
||||
hasAuthFile := tt.jsonKey != ""
|
||||
if hasAuthFile != tt.expectAuthFile {
|
||||
t.Errorf("Auth file expectation: got %v, want %v", hasAuthFile, tt.expectAuthFile)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+17
-8
@@ -13,6 +13,7 @@ import (
|
||||
kaniko "github.com/drone/drone-kaniko"
|
||||
"github.com/drone/drone-kaniko/pkg/artifact"
|
||||
"github.com/drone/drone-kaniko/pkg/docker"
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -175,7 +176,7 @@ func main() {
|
||||
cli.StringFlag{
|
||||
Name: "platform",
|
||||
Usage: "Allows to build with another default platform than the host, similarly to docker build --platform",
|
||||
EnvVar: "PLUGIN_PLATFORM",
|
||||
EnvVar: "PLUGIN_PLATFORM,PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "skip-unused-stages",
|
||||
@@ -213,11 +214,6 @@ func main() {
|
||||
Usage: "Sub-path within the context to build.",
|
||||
EnvVar: "PLUGIN_CONTEXT_SUB_PATH",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "custom-platform",
|
||||
Usage: "Platform to use for building.",
|
||||
EnvVar: "PLUGIN_CUSTOM_PLATFORM",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "Force building the image even if it already exists.",
|
||||
@@ -333,6 +329,18 @@ func main() {
|
||||
Usage: "Number of retries for downloading base images.",
|
||||
EnvVar: "PLUGIN_IMAGE_DOWNLOAD_RETRY",
|
||||
},
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "plugin-multiple-build-agrs",
|
||||
Usage: "plugin multiple build agrs",
|
||||
EnvVar: "PLUGIN_MULTIPLE_BUILD_ARGS",
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
@@ -378,6 +386,8 @@ func run(c *cli.Context) error {
|
||||
AutoTagSuffix: c.String("auto-tag-suffix"),
|
||||
ExpandTag: c.Bool("expand-tag"),
|
||||
Args: c.StringSlice("args"),
|
||||
ArgsNew: c.Generic("args-new").(*utils.CustomStringSliceFlag).GetValue(),
|
||||
IsMultipleBuildArgs: c.Bool("plugin-multiple-build-agrs"),
|
||||
Target: c.String("target"),
|
||||
Repo: fmt.Sprintf("%s/%s", c.String("registry"), c.String("repo")),
|
||||
Mirrors: c.StringSlice("registry-mirrors"),
|
||||
@@ -389,14 +399,13 @@ func run(c *cli.Context) error {
|
||||
DigestFile: defaultDigestFile,
|
||||
NoPush: noPush,
|
||||
Verbosity: c.String("verbosity"),
|
||||
Platform: c.String("platform"),
|
||||
CustomPlatform: c.String("platform"),
|
||||
SkipUnusedStages: c.Bool("skip-unused-stages"),
|
||||
CacheDir: c.String("cache-dir"),
|
||||
CacheCopyLayers: c.Bool("cache-copy-layers"),
|
||||
CacheRunLayers: c.Bool("cache-run-layers"),
|
||||
Cleanup: c.Bool("cleanup"),
|
||||
ContextSubPath: c.String("context-sub-path"),
|
||||
CustomPlatform: c.String("custom-platform"),
|
||||
Force: c.Bool("force"),
|
||||
ImageNameWithDigestFile: c.String("image-name-with-digest-file"),
|
||||
ImageNameTagWithDigestFile: c.String("image-name-tag-with-digest-file"),
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/drone/drone-kaniko/pkg/utils"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
func TestCustomStringSliceFlagIntegration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "single build arg",
|
||||
input: "ARG1=value1",
|
||||
expected: []string{"ARG1=value1"},
|
||||
},
|
||||
{
|
||||
name: "multiple build args with semicolon",
|
||||
input: "ARG1=value1;ARG2=value2;ARG3=value3",
|
||||
expected: []string{"ARG1=value1", "ARG2=value2", "ARG3=value3"},
|
||||
},
|
||||
{
|
||||
name: "build args with spaces",
|
||||
input: "ARG1=value with spaces;ARG2=another value",
|
||||
expected: []string{"ARG1=value with spaces", "ARG2=another value"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test the CustomStringSliceFlag directly
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
result := flag.GetValue()
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("Got %d args, want %d", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
if result[i] != expected {
|
||||
t.Errorf("Got arg[%d] = %v, want %v", i, result[i], expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvironmentVariableIntegration(t *testing.T) {
|
||||
// Test that environment variables work with CustomStringSliceFlag
|
||||
originalEnv := os.Getenv("PLUGIN_BUILD_ARGS_NEW")
|
||||
defer func() {
|
||||
if originalEnv != "" {
|
||||
os.Setenv("PLUGIN_BUILD_ARGS_NEW", originalEnv)
|
||||
} else {
|
||||
os.Unsetenv("PLUGIN_BUILD_ARGS_NEW")
|
||||
}
|
||||
}()
|
||||
|
||||
os.Setenv("PLUGIN_BUILD_ARGS_NEW", "ENV_ARG1=env_value1;ENV_ARG2=env_value2")
|
||||
|
||||
app := cli.NewApp()
|
||||
app.Flags = []cli.Flag{
|
||||
cli.GenericFlag{
|
||||
Name: "args-new",
|
||||
Usage: "build args new",
|
||||
EnvVar: "PLUGIN_BUILD_ARGS_NEW",
|
||||
Value: new(utils.CustomStringSliceFlag),
|
||||
},
|
||||
}
|
||||
|
||||
var capturedArgs []string
|
||||
app.Action = func(c *cli.Context) error {
|
||||
if flag := c.Generic("args-new"); flag != nil {
|
||||
if customFlag, ok := flag.(*utils.CustomStringSliceFlag); ok {
|
||||
capturedArgs = customFlag.GetValue()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := app.Run([]string{"test"})
|
||||
if err != nil {
|
||||
t.Errorf("App.Run() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
expected := []string{"ENV_ARG1=env_value1", "ENV_ARG2=env_value2"}
|
||||
if len(capturedArgs) != len(expected) {
|
||||
t.Errorf("Environment variable test: got %d args, want %d", len(capturedArgs), len(expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, exp := range expected {
|
||||
if capturedArgs[i] != exp {
|
||||
t.Errorf("Environment variable test: got arg[%d] = %v, want %v", i, capturedArgs[i], exp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCRBuildArgsProcessing(t *testing.T) {
|
||||
// Test that build args are correctly processed in the context of GCR plugin
|
||||
tests := []struct {
|
||||
name string
|
||||
argsNew string
|
||||
expectedCount int
|
||||
expectedFirst string
|
||||
}{
|
||||
{
|
||||
name: "docker build args format",
|
||||
argsNew: "GOOS=linux;GOARCH=amd64;CGO_ENABLED=0",
|
||||
expectedCount: 3,
|
||||
expectedFirst: "GOOS=linux",
|
||||
},
|
||||
{
|
||||
name: "google cloud specific args",
|
||||
argsNew: "GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json;PROJECT_ID=my-project",
|
||||
expectedCount: 2,
|
||||
expectedFirst: "GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json",
|
||||
},
|
||||
{
|
||||
name: "single complex arg with special characters",
|
||||
argsNew: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
expectedCount: 1,
|
||||
expectedFirst: "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flag := &utils.CustomStringSliceFlag{}
|
||||
err := flag.Set(tt.argsNew)
|
||||
if err != nil {
|
||||
t.Errorf("Set() error = %v, want nil", err)
|
||||
return
|
||||
}
|
||||
|
||||
args := flag.GetValue()
|
||||
if len(args) != tt.expectedCount {
|
||||
t.Errorf("Got %d args, want %d", len(args), tt.expectedCount)
|
||||
return
|
||||
}
|
||||
|
||||
if len(args) > 0 && args[0] != tt.expectedFirst {
|
||||
t.Errorf("Got first arg = %v, want %v", args[0], tt.expectedFirst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCRRegistryFormatting(t *testing.T) {
|
||||
// Test GCR-specific registry formatting
|
||||
tests := []struct {
|
||||
name string
|
||||
registry string
|
||||
repo string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "standard GCR format",
|
||||
registry: "gcr.io",
|
||||
repo: "my-project/my-image",
|
||||
expected: "gcr.io/my-project/my-image",
|
||||
},
|
||||
{
|
||||
name: "regional GCR",
|
||||
registry: "us.gcr.io",
|
||||
repo: "project123/image456",
|
||||
expected: "us.gcr.io/project123/image456",
|
||||
},
|
||||
{
|
||||
name: "european GCR",
|
||||
registry: "eu.gcr.io",
|
||||
repo: "my-eu-project/my-app",
|
||||
expected: "eu.gcr.io/my-eu-project/my-app",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This would be the format used in the GCR plugin
|
||||
result := tt.registry + "/" + tt.repo
|
||||
if result != tt.expected {
|
||||
t.Errorf("GCR formatting: got %v, want %v", result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCRJSONKeyValidation(t *testing.T) {
|
||||
// Test JSON key validation for GCR authentication
|
||||
tests := []struct {
|
||||
name string
|
||||
jsonKey string
|
||||
expectErr bool
|
||||
}{
|
||||
{
|
||||
name: "empty json key",
|
||||
jsonKey: "",
|
||||
expectErr: false, // Empty is allowed (workload identity)
|
||||
},
|
||||
{
|
||||
name: "valid json structure",
|
||||
jsonKey: `{"type":"service_account","project_id":"test","private_key_id":"123"}`,
|
||||
expectErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid json",
|
||||
jsonKey: `{invalid json}`,
|
||||
expectErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This simulates the JSON key validation that would happen in GCR
|
||||
if tt.jsonKey != "" {
|
||||
var data map[string]interface{}
|
||||
err := json.Unmarshal([]byte(tt.jsonKey), &data)
|
||||
if err != nil && !tt.expectErr {
|
||||
t.Errorf("Expected no error for JSON key, got %v", err)
|
||||
}
|
||||
if err == nil && tt.expectErr {
|
||||
t.Errorf("Expected error for JSON key, got nil")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGCRAuthSetup(t *testing.T) {
|
||||
// Test GCR authentication setup
|
||||
tests := []struct {
|
||||
name string
|
||||
jsonKey string
|
||||
expectAuthFile bool
|
||||
}{
|
||||
{
|
||||
name: "with json key",
|
||||
jsonKey: `{"type":"service_account","project_id":"test"}`,
|
||||
expectAuthFile: true,
|
||||
},
|
||||
{
|
||||
name: "without json key (workload identity)",
|
||||
jsonKey: "",
|
||||
expectAuthFile: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This simulates the auth setup logic
|
||||
hasAuthFile := tt.jsonKey != ""
|
||||
if hasAuthFile != tt.expectAuthFile {
|
||||
t.Errorf("Auth file expectation: got %v, want %v", hasAuthFile, tt.expectAuthFile)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM gcr.io/kaniko-project/executor:v1.23.2
|
||||
FROM harnesscommunity/kaniko-executor:1.25.0-linux-amd64
|
||||
|
||||
ENV KANIKO_VERSION=1.23.2
|
||||
ADD release/linux/amd64/kaniko-gcr /kaniko/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM gcr.io/kaniko-project/executor:v1.23.2
|
||||
FROM harnesscommunity/kaniko-executor:1.25.0-linux-arm64
|
||||
|
||||
ENV HOME /root
|
||||
ENV USER root
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module github.com/drone/drone-kaniko
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.1.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
|
||||
github.com/aws/aws-sdk-go v1.44.52
|
||||
github.com/aws/aws-sdk-go-v2 v1.16.7
|
||||
github.com/aws/aws-sdk-go-v2/config v1.15.14
|
||||
@@ -16,14 +16,14 @@ require (
|
||||
github.com/joho/godotenv v1.4.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.9.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/urfave/cli v1.22.15
|
||||
golang.org/x/mod v0.22.0
|
||||
golang.org/x/mod v0.26.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.3 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.12.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.14 // indirect
|
||||
@@ -38,26 +38,24 @@ require (
|
||||
github.com/docker/cli v27.5.0+incompatible // indirect
|
||||
github.com/docker/distribution v2.8.3+incompatible // indirect
|
||||
github.com/docker/docker-credential-helpers v0.8.2 // indirect
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.0 // indirect
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/vbatts/tar-split v0.11.6 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/net v0.17.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
golang.org/x/crypto v0.41.0 // indirect
|
||||
golang.org/x/net v0.43.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.23.8
|
||||
go 1.24.11
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.1.1 h1:tz19qLF65vuu2ibfTqGVJxG/zZAI27NEIIbvAOQwYbw=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.1.1/go.mod h1:uGG2W01BaETf0Ozp+QxxKJdMBNRWPdstHG0Fmdwn1/U=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0 h1:QkAcEIAKbNL4KoFr4SathZPhDhF4mVwpBMFlYjyAqy8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0/go.mod h1:bhXu1AjYL+wutSL/kpSq6s7733q2Rb0yuot9Zgfqa/0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0 h1:jp0dGvZ7ZK0mgqnTSClMxa5xuRL7NZgHameVYF6BurY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.3 h1:TsFCaaF5tR4XN8b4zLVl/J4qMb0nf80Q4CXcpXDNJDY=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.3/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0 h1:JXg2dwJUmPB9JmtVmdEB16APJ7jurfbY5jnfXpJoRMc=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0/go.mod h1:YD5h/ldMsG0XiIw7PdyNhLxaM317eFh5yNLccNfGdyw=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/aws/aws-sdk-go v1.44.52 h1:kHLbYJj59C7VrsLM4gm7pxsvaNIvhXCCIDYEFFoQ+VE=
|
||||
github.com/aws/aws-sdk-go v1.44.52/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
|
||||
@@ -45,27 +49,21 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dnaeon/go-vcr v1.1.0 h1:ReYa/UBrRyQdant9B4fNHGoCNKw6qh6P0fsdGmZpR7c=
|
||||
github.com/dnaeon/go-vcr v1.1.0/go.mod h1:M7tiix8f0r6mKKJ3Yq/kqU1OYf3MnfmBWVbPx/yU9ko=
|
||||
github.com/docker/cli v27.5.0+incompatible h1:aMphQkcGtpHixwwhAXJT1rrK/detk2JIvDaFkLctbGM=
|
||||
github.com/docker/cli v27.5.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
||||
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
|
||||
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||
github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo=
|
||||
github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M=
|
||||
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang-jwt/jwt/v4 v4.2.0 h1:besgBTC8w8HjP6NzQdxwKH9Z5oQMZ24ThTrHp3cZ8eU=
|
||||
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-containerregistry v0.20.3 h1:oNx7IdTI936V8CQRveCjaxOiegWwvM7kqkbXTpyiovI=
|
||||
github.com/google/go-containerregistry v0.20.3/go.mod h1:w00pIgBRDVUDFM6bq+Qx8lwNWK+cxgCuX1vd3PIBDNI=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek=
|
||||
github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
|
||||
@@ -74,24 +72,30 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGw
|
||||
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
|
||||
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
|
||||
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU=
|
||||
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
@@ -104,35 +108,36 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/urfave/cli v1.22.15 h1:nuqt+pdC/KqswQKhETJjo7pvn/k4xMUxgW6liI7XpnM=
|
||||
github.com/urfave/cli v1.22.15/go.mod h1:wSan1hmo5zeyLGBjRJbzRTNk8gwoYa2B9n4q9dmRIc0=
|
||||
github.com/vbatts/tar-split v0.11.6 h1:4SjTW5+PU11n6fZenf2IPoV8/tz3AaYHMWjf23envGs=
|
||||
github.com/vbatts/tar-split v0.11.6/go.mod h1:dqKNtesIOr2j2Qv3W/cHjnvk9I8+G7oAkFDFN6TCBEI=
|
||||
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4=
|
||||
golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
|
||||
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
|
||||
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
|
||||
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const DefaultResource = "https://management.azure.com/"
|
||||
const defaultAuthorityHost = "https://login.microsoftonline.com"
|
||||
const defaultHTTPTimeout = 30 * time.Second
|
||||
|
||||
// GetAADAccessTokenViaClientAssertion exchanges an external OIDC ID token for an Azure AD access token
|
||||
|
||||
func GetAADAccessTokenViaClientAssertion(ctx context.Context, tenantID, clientID, oidcToken, authorityHost string) (string, error) {
|
||||
resource := DefaultResource
|
||||
|
||||
form := url.Values{
|
||||
"client_id": {clientID},
|
||||
"scope": {resource + ".default"},
|
||||
"grant_type": {"client_credentials"},
|
||||
"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
|
||||
"client_assertion": {oidcToken},
|
||||
}
|
||||
base := authorityHost
|
||||
if strings.TrimSpace(base) == "" {
|
||||
base = defaultAuthorityHost
|
||||
}
|
||||
base = strings.TrimRight(base, "/")
|
||||
endpoint := fmt.Sprintf("%s/%s/oauth2/v2.0/token", base, tenantID)
|
||||
client := &http.Client{Timeout: defaultHTTPTimeout}
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
var aadErr struct {
|
||||
Error string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
limited := io.LimitedReader{R: resp.Body, N: 4096}
|
||||
_ = json.NewDecoder(&limited).Decode(&aadErr)
|
||||
if aadErr.Error != "" {
|
||||
return "", fmt.Errorf("AAD token request failed: status=%d, error=%s", resp.StatusCode, aadErr.Error)
|
||||
}
|
||||
return "", fmt.Errorf("AAD token request failed: status=%d", resp.StatusCode)
|
||||
}
|
||||
var payload struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if payload.AccessToken == "" {
|
||||
return "", fmt.Errorf("AAD token response missing access_token")
|
||||
}
|
||||
return payload.AccessToken, nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetAADAccessTokenViaClientAssertion_Success(t *testing.T) {
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("expected POST, got %s", r.Method)
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "application/x-www-form-urlencoded") {
|
||||
t.Fatalf("expected form content-type, got %s", ct)
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatalf("failed parsing form: %v", err)
|
||||
}
|
||||
assertEq(t, r.Form.Get("client_id"), "client")
|
||||
assertEq(t, r.Form.Get("grant_type"), "client_credentials")
|
||||
assertEq(t, r.Form.Get("client_assertion_type"), "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
|
||||
assertEq(t, r.Form.Get("client_assertion"), "idtoken")
|
||||
assertEq(t, r.Form.Get("scope"), DefaultResource+".default")
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"access_token":"AT","token_type":"Bearer","expires_in":3600}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
tok, err := GetAADAccessTokenViaClientAssertion(context.Background(), "tenant", "client", "idtoken", ts.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if tok != "AT" {
|
||||
t.Fatalf("expected access token AT, got %q", tok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAADAccessTokenViaClientAssertion_400WithErrorField(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_client","error_description":"bad"}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
_, err := GetAADAccessTokenViaClientAssertion(context.Background(), "tenant", "client", "idtoken", ts.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "status=400") || !strings.Contains(err.Error(), "invalid_client") {
|
||||
t.Fatalf("expected 400 with invalid_client error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAADAccessTokenViaClientAssertion_400WithoutErrorField(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte("{}"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
_, err := GetAADAccessTokenViaClientAssertion(context.Background(), "tenant", "client", "idtoken", ts.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "status=400") {
|
||||
t.Fatalf("expected 400 error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAADAccessTokenViaClientAssertion_MalformedJSON(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("not-json"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
_, err := GetAADAccessTokenViaClientAssertion(context.Background(), "tenant", "client", "idtoken", ts.URL)
|
||||
if err == nil {
|
||||
t.Fatalf("expected JSON decode error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAADAccessTokenViaClientAssertion_MissingAccessToken(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"token_type":"Bearer","expires_in":3600}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
_, err := GetAADAccessTokenViaClientAssertion(context.Background(), "tenant", "client", "idtoken", ts.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "missing access_token") {
|
||||
t.Fatalf("expected missing access_token error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEq(t *testing.T, got, want string) {
|
||||
t.Helper()
|
||||
if got != want {
|
||||
t.Fatalf("mismatch: got=%q want=%q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,6 @@ type (
|
||||
Labels []string // Label map
|
||||
Mirrors []string // Docker repository mirrors
|
||||
NoPush bool // Set this flag if you only want to build the image, without pushing to a registry
|
||||
Platform string // Allows to build with another default platform than the host, similarly to docker build --platform
|
||||
PushOnly bool // Specify if the operation is push-only.
|
||||
Repo string // Docker build repository
|
||||
SkipTlsVerify bool // Docker skip tls certificate verify for registry
|
||||
@@ -228,7 +227,15 @@ func (p Plugin) Exec() error {
|
||||
}
|
||||
|
||||
if _, err := os.Stat(p.Build.Dockerfile); os.IsNotExist(err) {
|
||||
return fmt.Errorf("dockerfile does not exist at path: %s", p.Build.Dockerfile)
|
||||
|
||||
// Get absolute path for better error message. If path is empty, this will
|
||||
// return the current working directory, showing where the plugin looked.
|
||||
absPath, absErr := filepath.Abs(p.Build.Dockerfile)
|
||||
if absErr != nil {
|
||||
absPath = p.Build.Dockerfile
|
||||
}
|
||||
|
||||
return fmt.Errorf("dockerfile does not exist at path: %s", absPath)
|
||||
}
|
||||
|
||||
var tags = p.Build.Tags
|
||||
@@ -311,10 +318,6 @@ func (p Plugin) Exec() error {
|
||||
cmdArgs = append(cmdArgs, fmt.Sprintf("--verbosity=%s", p.Build.Verbosity))
|
||||
}
|
||||
|
||||
if p.Build.Platform != "" {
|
||||
cmdArgs = append(cmdArgs, fmt.Sprintf("--customPlatform=%s", p.Build.Platform))
|
||||
}
|
||||
|
||||
if p.Build.SkipUnusedStages {
|
||||
cmdArgs = append(cmdArgs, "--skip-unused-stages")
|
||||
}
|
||||
|
||||
@@ -283,6 +283,57 @@ func TestTarPathValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomPlatformFlag(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
customPlatform string
|
||||
expectFlag bool
|
||||
}{
|
||||
{
|
||||
name: "with_custom_platform",
|
||||
customPlatform: "linux/amd64",
|
||||
expectFlag: true,
|
||||
},
|
||||
{
|
||||
name: "with_custom_platform_arm",
|
||||
customPlatform: "linux/arm64",
|
||||
expectFlag: true,
|
||||
},
|
||||
{
|
||||
name: "empty_custom_platform",
|
||||
customPlatform: "",
|
||||
expectFlag: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p := Plugin{
|
||||
Build: Build{
|
||||
Dockerfile: "Dockerfile",
|
||||
Context: ".",
|
||||
Repo: "test/repo",
|
||||
Tags: []string{"latest"},
|
||||
CustomPlatform: tt.customPlatform,
|
||||
NoPush: true, // Don't actually push
|
||||
},
|
||||
}
|
||||
|
||||
// We can't actually run Exec() without kaniko installed,
|
||||
// but we can verify the logic by checking the field is set correctly
|
||||
if tt.expectFlag && p.Build.CustomPlatform == "" {
|
||||
t.Errorf("Expected CustomPlatform to be set to %q, but got empty string", tt.customPlatform)
|
||||
}
|
||||
if !tt.expectFlag && p.Build.CustomPlatform != "" {
|
||||
t.Errorf("Expected CustomPlatform to be empty, but got %q", p.Build.CustomPlatform)
|
||||
}
|
||||
if tt.expectFlag && p.Build.CustomPlatform != tt.customPlatform {
|
||||
t.Errorf("Expected CustomPlatform to be %q, but got %q", tt.customPlatform, p.Build.CustomPlatform)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceTarballPush(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
@@ -10,6 +10,7 @@ type CustomStringSliceFlag struct {
|
||||
Value []string
|
||||
}
|
||||
|
||||
// GetValue returns the slice of strings stored in the flag
|
||||
func (f *CustomStringSliceFlag) GetValue() []string {
|
||||
if f.Value == nil {
|
||||
return make([]string, 0)
|
||||
@@ -17,6 +18,7 @@ func (f *CustomStringSliceFlag) GetValue() []string {
|
||||
return f.Value
|
||||
}
|
||||
|
||||
// String returns a string representation of the flag
|
||||
func (f *CustomStringSliceFlag) String() string {
|
||||
if f.Value == nil {
|
||||
return ""
|
||||
@@ -24,6 +26,7 @@ func (f *CustomStringSliceFlag) String() string {
|
||||
return strings.Join(f.Value, ";")
|
||||
}
|
||||
|
||||
// Set sets the value of the flag from a string
|
||||
func (f *CustomStringSliceFlag) Set(v string) error {
|
||||
for _, s := range strings.Split(v, ";") {
|
||||
s = strings.TrimSpace(s)
|
||||
Reference in New Issue
Block a user