0
Fork 0
mirror of https://github.com/project-zot/zot.git synced 2025-01-27 23:01:43 -05:00

refactor(cli): Move cmdflags package under pkg/cli/client (#1840)

Signed-off-by: Alexei Dodon <adodon@cisco.com>
This commit is contained in:
Alexei Dodon 2023-09-22 16:33:18 +03:00 committed by GitHub
parent 8c559441e6
commit 4e04be420e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 447 additions and 450 deletions

View file

@ -5,8 +5,6 @@ package client
import (
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
func NewCVECommand(searchService SearchService) *cobra.Command {
@ -19,15 +17,15 @@ func NewCVECommand(searchService SearchService) *cobra.Command {
cvesCmd.SetUsageTemplate(cvesCmd.UsageTemplate() + usageFooter)
cvesCmd.PersistentFlags().String(cmdflags.URLFlag, "",
cvesCmd.PersistentFlags().String(URLFlag, "",
"Specify zot server URL if config-name is not mentioned")
cvesCmd.PersistentFlags().String(cmdflags.ConfigFlag, "",
cvesCmd.PersistentFlags().String(ConfigFlag, "",
"Specify the registry configuration to use for connection")
cvesCmd.PersistentFlags().StringP(cmdflags.UserFlag, "u", "",
cvesCmd.PersistentFlags().StringP(UserFlag, "u", "",
`User Credentials of zot server in "username:password" format`)
cvesCmd.PersistentFlags().StringP(cmdflags.OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
cvesCmd.PersistentFlags().Bool(cmdflags.VerboseFlag, false, "Show verbose output")
cvesCmd.PersistentFlags().Bool(cmdflags.DebugFlag, false, "Show debug output")
cvesCmd.PersistentFlags().StringP(OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
cvesCmd.PersistentFlags().Bool(VerboseFlag, false, "Show verbose output")
cvesCmd.PersistentFlags().Bool(DebugFlag, false, "Show debug output")
cvesCmd.AddCommand(NewCveForImageCommand(searchService))
cvesCmd.AddCommand(NewImagesByCVEIDCommand(searchService))

View file

@ -10,7 +10,6 @@ import (
"github.com/spf13/cobra"
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/cli/cmdflags"
zcommon "zotregistry.io/zot/pkg/common"
)
@ -21,7 +20,7 @@ const (
func NewCveForImageCommand(searchService SearchService) *cobra.Command {
var (
searchedCVEID string
cveListSortFlag = cmdflags.CVEListSortFlag(cmdflags.SortBySeverity)
cveListSortFlag = CVEListSortFlag(SortBySeverity)
)
cveForImageCmd := &cobra.Command{
@ -46,9 +45,9 @@ func NewCveForImageCommand(searchService SearchService) *cobra.Command {
},
}
cveForImageCmd.Flags().StringVar(&searchedCVEID, cmdflags.SearchedCVEID, "", "Search for a specific CVE by name/id")
cveForImageCmd.Flags().Var(&cveListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.CVEListSortOptionsStr()))
cveForImageCmd.Flags().StringVar(&searchedCVEID, SearchedCVEID, "", "Search for a specific CVE by name/id")
cveForImageCmd.Flags().Var(&cveListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", CVEListSortOptionsStr()))
return cveForImageCmd
}
@ -56,7 +55,7 @@ func NewCveForImageCommand(searchService SearchService) *cobra.Command {
func NewImagesByCVEIDCommand(searchService SearchService) *cobra.Command {
var (
repo string
imageListSortFlag = cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag = ImageListSortFlag(SortByAlphabeticAsc)
)
imagesByCVEIDCmd := &cobra.Command{
@ -92,14 +91,14 @@ func NewImagesByCVEIDCommand(searchService SearchService) *cobra.Command {
}
imagesByCVEIDCmd.Flags().StringVar(&repo, "repo", "", "Search for a specific CVE by name/id")
imagesByCVEIDCmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
imagesByCVEIDCmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return imagesByCVEIDCmd
}
func NewFixedTagsCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
fixedTagsCmd := &cobra.Command{
Use: "fixed [repo] [cveId]",
@ -136,8 +135,8 @@ func NewFixedTagsCommand(searchService SearchService) *cobra.Command {
},
}
fixedTagsCmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
fixedTagsCmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return fixedTagsCmd
}

View file

@ -1,4 +1,7 @@
package cmdflags
//go:build search
// +build search
package client
import (
"fmt"

View file

@ -1,11 +1,14 @@
package cmdflags_test
//go:build search
// +build search
package client_test
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
. "zotregistry.io/zot/pkg/cli/cmdflags"
. "zotregistry.io/zot/pkg/cli/client"
gql_gen "zotregistry.io/zot/pkg/extensions/search/gql_generated"
)

View file

@ -8,8 +8,6 @@ import (
"time"
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
const (
@ -29,15 +27,15 @@ func NewImageCommand(searchService SearchService) *cobra.Command {
imageCmd.SetUsageTemplate(imageCmd.UsageTemplate() + usageFooter)
imageCmd.PersistentFlags().String(cmdflags.URLFlag, "",
imageCmd.PersistentFlags().String(URLFlag, "",
"Specify zot server URL if config-name is not mentioned")
imageCmd.PersistentFlags().String(cmdflags.ConfigFlag, "",
imageCmd.PersistentFlags().String(ConfigFlag, "",
"Specify the registry configuration to use for connection")
imageCmd.PersistentFlags().StringP(cmdflags.UserFlag, "u", "",
imageCmd.PersistentFlags().StringP(UserFlag, "u", "",
`User Credentials of zot server in "username:password" format`)
imageCmd.PersistentFlags().StringP(cmdflags.OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
imageCmd.PersistentFlags().Bool(cmdflags.VerboseFlag, false, "Show verbose output")
imageCmd.PersistentFlags().Bool(cmdflags.DebugFlag, false, "Show debug output")
imageCmd.PersistentFlags().StringP(OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
imageCmd.PersistentFlags().Bool(VerboseFlag, false, "Show verbose output")
imageCmd.PersistentFlags().Bool(DebugFlag, false, "Show debug output")
imageCmd.AddCommand(NewImageListCommand(searchService))
imageCmd.AddCommand(NewImageCVEListCommand(searchService))

View file

@ -9,12 +9,11 @@ import (
"github.com/spf13/cobra"
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/cli/cmdflags"
zcommon "zotregistry.io/zot/pkg/common"
)
func NewImageListCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "list",
@ -35,8 +34,8 @@ func NewImageListCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}
@ -44,7 +43,7 @@ func NewImageListCommand(searchService SearchService) *cobra.Command {
func NewImageCVEListCommand(searchService SearchService) *cobra.Command {
var (
searchedCVEID string
cveListSortFlag = cmdflags.CVEListSortFlag(cmdflags.SortBySeverity)
cveListSortFlag = CVEListSortFlag(SortBySeverity)
)
cmd := &cobra.Command{
@ -68,15 +67,15 @@ func NewImageCVEListCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().StringVar(&searchedCVEID, cmdflags.SearchedCVEID, "", "Search for a specific CVE by name/id")
cmd.Flags().Var(&cveListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.CVEListSortOptionsStr()))
cmd.Flags().StringVar(&searchedCVEID, SearchedCVEID, "", "Search for a specific CVE by name/id")
cmd.Flags().Var(&cveListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", CVEListSortOptionsStr()))
return cmd
}
func NewImageDerivedCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "derived [repo-name:tag]|[repo-name@digest]",
@ -97,14 +96,14 @@ func NewImageDerivedCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}
func NewImageBaseCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "base [repo-name:tag]|[repo-name@digest]",
@ -125,14 +124,14 @@ func NewImageBaseCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}
func NewImageDigestCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "digest [digest]",
@ -155,14 +154,14 @@ zli image digest sha256:8a1930f0...`,
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}
func NewImageNameCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "name [repo:tag]",
@ -195,8 +194,8 @@ func NewImageNameCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}

View file

@ -5,8 +5,6 @@ package client
import (
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
const prefix = "Searching... "
@ -21,13 +19,13 @@ func NewRepoCommand(searchService SearchService) *cobra.Command {
repoCmd.SetUsageTemplate(repoCmd.UsageTemplate() + usageFooter)
repoCmd.PersistentFlags().String(cmdflags.URLFlag, "",
repoCmd.PersistentFlags().String(URLFlag, "",
"Specify zot server URL if config-name is not mentioned")
repoCmd.PersistentFlags().String(cmdflags.ConfigFlag, "",
repoCmd.PersistentFlags().String(ConfigFlag, "",
"Specify the registry configuration to use for connection")
repoCmd.PersistentFlags().StringP(cmdflags.UserFlag, "u", "",
repoCmd.PersistentFlags().StringP(UserFlag, "u", "",
`User Credentials of zot server in "username:password" format`)
repoCmd.PersistentFlags().Bool(cmdflags.DebugFlag, false, "Show debug output")
repoCmd.PersistentFlags().Bool(DebugFlag, false, "Show debug output")
repoCmd.AddCommand(NewListReposCommand(searchService))

View file

@ -7,12 +7,10 @@ import (
"fmt"
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
func NewListReposCommand(searchService SearchService) *cobra.Command {
repoListSortFlag := cmdflags.RepoListSortFlag(cmdflags.SortByAlphabeticAsc)
repoListSortFlag := RepoListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "list",
@ -29,8 +27,8 @@ func NewListReposCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&repoListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.RepoListSortOptionsStr()))
cmd.Flags().Var(&repoListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", RepoListSortOptionsStr()))
return cmd
}

View file

@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/api/config"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
// "zli" - client-side cli.
@ -36,7 +35,7 @@ func NewCliRootCmd() *cobra.Command {
// additional cmds
enableCli(rootCmd)
// "version"
rootCmd.Flags().BoolVarP(&showVersion, cmdflags.VersionFlag, "v", false, "show the version and exit")
rootCmd.Flags().BoolVarP(&showVersion, VersionFlag, "v", false, "show the version and exit")
return rootCmd
}

View file

@ -5,8 +5,6 @@ package client
import (
"github.com/spf13/cobra"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
func NewSearchCommand(searchService SearchService) *cobra.Command {
@ -19,15 +17,15 @@ func NewSearchCommand(searchService SearchService) *cobra.Command {
searchCmd.SetUsageTemplate(searchCmd.UsageTemplate() + usageFooter)
searchCmd.PersistentFlags().String(cmdflags.URLFlag, "",
searchCmd.PersistentFlags().String(URLFlag, "",
"Specify zot server URL if config-name is not mentioned")
searchCmd.PersistentFlags().String(cmdflags.ConfigFlag, "",
searchCmd.PersistentFlags().String(ConfigFlag, "",
"Specify the registry configuration to use for connection")
searchCmd.PersistentFlags().StringP(cmdflags.UserFlag, "u", "",
searchCmd.PersistentFlags().StringP(UserFlag, "u", "",
`User Credentials of zot server in "username:password" format`)
searchCmd.PersistentFlags().StringP(cmdflags.OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
searchCmd.PersistentFlags().Bool(cmdflags.VerboseFlag, false, "Show verbose output")
searchCmd.PersistentFlags().Bool(cmdflags.DebugFlag, false, "Show debug output")
searchCmd.PersistentFlags().StringP(OutputFormatFlag, "f", "", "Specify output format [text/json/yaml]")
searchCmd.PersistentFlags().Bool(VerboseFlag, false, "Show verbose output")
searchCmd.PersistentFlags().Bool(DebugFlag, false, "Show debug output")
searchCmd.AddCommand(NewSearchQueryCommand(searchService))
searchCmd.AddCommand(NewSearchSubjectCommand(searchService))

View file

@ -22,7 +22,6 @@ import (
"github.com/spf13/cobra"
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/cli/cmdflags"
"zotregistry.io/zot/pkg/common"
)
@ -693,7 +692,7 @@ func TestUtils(t *testing.T) {
// bad showspinner
configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":"bad", "verify-tls": false}]}`)
cmd = &cobra.Command{}
cmd.Flags().String(cmdflags.ConfigFlag, "imagetest", "")
cmd.Flags().String(ConfigFlag, "imagetest", "")
isSpinner, verifyTLS, err = GetCliConfigOptions(cmd)
So(err, ShouldNotBeNil)
So(isSpinner, ShouldBeFalse)
@ -703,7 +702,7 @@ func TestUtils(t *testing.T) {
// bad verify-tls
configPath = makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false, "verify-tls": "bad"}]}`)
cmd = &cobra.Command{}
cmd.Flags().String(cmdflags.ConfigFlag, "imagetest", "")
cmd.Flags().String(ConfigFlag, "imagetest", "")
isSpinner, verifyTLS, err = GetCliConfigOptions(cmd)
So(err, ShouldNotBeNil)
So(isSpinner, ShouldBeFalse)
@ -713,7 +712,7 @@ func TestUtils(t *testing.T) {
Convey("GetServerURLFromFlags", t, func() {
cmd := &cobra.Command{}
cmd.Flags().String(cmdflags.URLFlag, "url", "")
cmd.Flags().String(URLFlag, "url", "")
url, err := GetServerURLFromFlags(cmd)
So(url, ShouldResemble, "url")
So(err, ShouldBeNil)
@ -727,7 +726,7 @@ func TestUtils(t *testing.T) {
// err ulr from config is empty
configPath := makeConfigFile(`{"configs":[{"_name":"imagetest"}]}`)
cmd = &cobra.Command{}
cmd.Flags().String(cmdflags.ConfigFlag, "imagetest", "")
cmd.Flags().String(ConfigFlag, "imagetest", "")
url, err = GetServerURLFromFlags(cmd)
So(url, ShouldResemble, "")
So(err, ShouldNotBeNil)
@ -736,7 +735,7 @@ func TestUtils(t *testing.T) {
// err reading the server url from config
configPath = makeConfigFile("{}")
cmd = &cobra.Command{}
cmd.Flags().String(cmdflags.ConfigFlag, "imagetest", "")
cmd.Flags().String(ConfigFlag, "imagetest", "")
url, err = GetServerURLFromFlags(cmd)
So(url, ShouldResemble, "")
So(err, ShouldNotBeNil)

View file

@ -9,12 +9,11 @@ import (
"github.com/spf13/cobra"
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/cli/cmdflags"
zcommon "zotregistry.io/zot/pkg/common"
)
func NewSearchSubjectCommand(searchService SearchService) *cobra.Command {
imageListSortFlag := cmdflags.ImageListSortFlag(cmdflags.SortByAlphabeticAsc)
imageListSortFlag := ImageListSortFlag(SortByAlphabeticAsc)
cmd := &cobra.Command{
Use: "subject [repo:tag]|[repo@digest]",
@ -39,14 +38,14 @@ func NewSearchSubjectCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageListSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageListSortOptionsStr()))
cmd.Flags().Var(&imageListSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageListSortOptionsStr()))
return cmd
}
func NewSearchQueryCommand(searchService SearchService) *cobra.Command {
imageSearchSortFlag := cmdflags.ImageSearchSortFlag(cmdflags.SortByRelevance)
imageSearchSortFlag := ImageSearchSortFlag(SortByRelevance)
cmd := &cobra.Command{
Use: "query [repo]|[repo:tag]",
@ -54,7 +53,7 @@ func NewSearchQueryCommand(searchService SearchService) *cobra.Command {
Long: "Fuzzy search for repos and their tags.",
Example: `# For repo search specify a substring of the repo name without the tag
zli search query "test/repo"
# For image search specify the full repo name followed by the tag or a prefix of the tag.
zli search query "test/repo:2.1."`,
Args: cobra.ExactArgs(1),
@ -82,8 +81,8 @@ func NewSearchQueryCommand(searchService SearchService) *cobra.Command {
},
}
cmd.Flags().Var(&imageSearchSortFlag, cmdflags.SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", cmdflags.ImageSearchSortOptionsStr()))
cmd.Flags().Var(&imageSearchSortFlag, SortByFlag,
fmt.Sprintf("Options for sorting the output: [%s]", ImageSearchSortOptionsStr()))
return cmd
}

View file

@ -22,7 +22,6 @@ import (
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/api/constants"
"zotregistry.io/zot/pkg/cli/cmdflags"
"zotregistry.io/zot/pkg/common"
)
@ -108,7 +107,7 @@ func (service searchService) getDerivedImageListGQL(ctx context.Context, config
IsSigned
}
}
}`, derivedImage, cmdflags.Flag2SortCriteria(config.sortBy))
}`, derivedImage, Flag2SortCriteria(config.sortBy))
result := &common.DerivedImageListResponse{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -180,7 +179,7 @@ func (service searchService) globalSearchGQL(ctx context.Context, config searchC
StarCount
}
}
}`, query, cmdflags.Flag2SortCriteria(config.sortBy))
}`, query, Flag2SortCriteria(config.sortBy))
result := &common.GlobalSearchResultResp{}
@ -216,7 +215,7 @@ func (service searchService) getBaseImageListGQL(ctx context.Context, config sea
IsSigned
}
}
}`, baseImage, cmdflags.Flag2SortCriteria(config.sortBy))
}`, baseImage, Flag2SortCriteria(config.sortBy))
result := &common.BaseImageListResponse{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -252,7 +251,7 @@ func (service searchService) getImagesGQL(ctx context.Context, config searchConf
IsSigned
}
}
}`, imageName, cmdflags.Flag2SortCriteria(config.sortBy))
}`, imageName, Flag2SortCriteria(config.sortBy))
result := &common.ImageListResponse{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -288,7 +287,7 @@ func (service searchService) getImagesForDigestGQL(ctx context.Context, config s
IsSigned
}
}
}`, digest, cmdflags.Flag2SortCriteria(config.sortBy))
}`, digest, Flag2SortCriteria(config.sortBy))
result := &common.ImagesForDigest{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -304,14 +303,14 @@ func (service searchService) getCveByImageGQL(ctx context.Context, config search
imageName, searchedCVE string,
) (*cveResult, error) {
query := fmt.Sprintf(`
{
CVEListForImage (image:"%s", searchedCVE:"%s", requestedPage: {sortBy: %s}) {
Tag CVEList {
Id Title Severity Description
{
CVEListForImage (image:"%s", searchedCVE:"%s", requestedPage: {sortBy: %s}) {
Tag CVEList {
Id Title Severity Description
PackageList {Name InstalledVersion FixedVersion}
}
}
}`, imageName, searchedCVE, cmdflags.Flag2SortCriteria(config.sortBy))
}`, imageName, searchedCVE, Flag2SortCriteria(config.sortBy))
result := &cveResult{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -348,7 +347,7 @@ func (service searchService) getTagsForCVEGQL(ctx context.Context, config search
}
}
}`,
cveID, cmdflags.Flag2SortCriteria(config.sortBy))
cveID, Flag2SortCriteria(config.sortBy))
result := &common.ImagesForCve{}
err := service.makeGraphQLQuery(ctx, config, username, password, query, result)
@ -1337,7 +1336,7 @@ func (service searchService) getRepos(ctx context.Context, config searchConfig,
fmt.Fprintln(config.resultWriter, "\nREPOSITORY NAME")
if config.sortBy == cmdflags.SortByAlphabeticAsc {
if config.sortBy == SortByAlphabeticAsc {
for i := 0; i < len(catalog.Repositories); i++ {
fmt.Fprintln(config.resultWriter, catalog.Repositories[i])
}

View file

@ -18,7 +18,6 @@ import (
zerr "zotregistry.io/zot/errors"
"zotregistry.io/zot/pkg/api/constants"
"zotregistry.io/zot/pkg/cli/cmdflags"
)
const (
@ -370,12 +369,12 @@ func GetSearchConfigFromFlags(cmd *cobra.Command, searchService SearchService) (
}
flags := cmd.Flags()
user := defaultIfError(flags.GetString(cmdflags.UserFlag))
fixed := defaultIfError(flags.GetBool(cmdflags.FixedFlag))
debug := defaultIfError(flags.GetBool(cmdflags.DebugFlag))
verbose := defaultIfError(flags.GetBool(cmdflags.VerboseFlag))
outputFormat := defaultIfError(flags.GetString(cmdflags.OutputFormatFlag))
sortBy := defaultIfError(flags.GetString(cmdflags.SortByFlag))
user := defaultIfError(flags.GetString(UserFlag))
fixed := defaultIfError(flags.GetBool(FixedFlag))
debug := defaultIfError(flags.GetBool(DebugFlag))
verbose := defaultIfError(flags.GetBool(VerboseFlag))
outputFormat := defaultIfError(flags.GetString(OutputFormatFlag))
sortBy := defaultIfError(flags.GetString(SortByFlag))
spin := spinner.New(spinner.CharSets[39], spinnerDuration, spinner.WithWriter(cmd.ErrOrStderr()))
spin.Prefix = prefix
@ -406,7 +405,7 @@ func defaultIfError[T any](out T, err error) T {
}
func GetCliConfigOptions(cmd *cobra.Command) (bool, bool, error) {
configName, err := cmd.Flags().GetString(cmdflags.ConfigFlag)
configName, err := cmd.Flags().GetString(ConfigFlag)
if err != nil {
return false, false, err
}
@ -436,19 +435,18 @@ func GetCliConfigOptions(cmd *cobra.Command) (bool, bool, error) {
}
func GetServerURLFromFlags(cmd *cobra.Command) (string, error) {
serverURL, err := cmd.Flags().GetString(cmdflags.URLFlag)
serverURL, err := cmd.Flags().GetString(URLFlag)
if err == nil && serverURL != "" {
return serverURL, nil
}
configName, err := cmd.Flags().GetString(cmdflags.ConfigFlag)
configName, err := cmd.Flags().GetString(ConfigFlag)
if err != nil {
return "", err
}
if configName == "" {
return "", fmt.Errorf("%w: specify either '--%s' or '--%s' flags", zerr.ErrNoURLProvided, cmdflags.URLFlag,
cmdflags.ConfigFlag)
return "", fmt.Errorf("%w: specify either '--%s' or '--%s' flags", zerr.ErrNoURLProvided, URLFlag, ConfigFlag)
}
serverURL, err = ReadServerURLFromConfig(configName)

View file

@ -13,12 +13,356 @@ import (
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/resty.v1"
"zotregistry.io/zot/pkg/api/config"
cli "zotregistry.io/zot/pkg/cli/server"
. "zotregistry.io/zot/pkg/test"
)
const readLogFileTimeout = 5 * time.Second
func TestVerifyExtensionsConfig(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
Convey("Test verify CVE warn for remote storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{
"storage":{
"rootDirectory":"/tmp/zot",
"dedupe":true,
"remoteCache":false,
"storageDriver":{
"name":"s3",
"rootdirectory":"/zot",
"region":"us-east-2",
"bucket":"zot-storage",
"secure":true,
"skipverify":false
}
},
"http":{
"address":"127.0.0.1",
"port":"8080"
},
"extensions":{
"search": {
"enable": true,
"cve": {
"updateInterval": "24h"
}
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
content = []byte(`{
"storage":{
"rootDirectory":"/tmp/zot",
"dedupe":true,
"remoteCache":false,
"subPaths":{
"/a": {
"rootDirectory": "/tmp/zot1",
"dedupe": false,
"storageDriver":{
"name":"s3",
"rootdirectory":"/zot-a",
"region":"us-east-2",
"bucket":"zot-storage",
"secure":true,
"skipverify":false
}
}
}
},
"http":{
"address":"127.0.0.1",
"port":"8080"
},
"extensions":{
"search": {
"enable": true,
"cve": {
"updateInterval": "24h"
}
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify w/ sync and w/o filesystem storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s"}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify w/ sync and w/ filesystem storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s"}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldNotPanic)
})
Convey("Test verify with bad sync prefixes", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"[repo%^&"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify with bad sync content config", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"zot-repo","stripPrefix":true,"destination":"/"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify with good sync content config", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"zot-repo/*","stripPrefix":true,"destination":"/"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
err = cli.NewServerRootCmd().Execute()
So(err, ShouldBeNil)
})
Convey("Test verify sync config default tls value", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"repo**"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
err = cli.NewServerRootCmd().Execute()
So(err, ShouldBeNil)
})
Convey("Test verify sync without retry options", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 10, "content": [{"prefix":"repo**"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
}
func TestValidateExtensionsConfig(t *testing.T) {
Convey("Legacy extensions should not error", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"mgmt": {
"enable": "true"
},
"apikey": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
})
Convey("Test missing extensions for UI to work", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldNotBeNil)
})
Convey("Test enabling UI extension with all prerequisites", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {
"enable": "true"
},
"search": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
})
Convey("Test extension are implicitly enabled", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {},
"search": {},
"metrics": {},
"trust": {},
"scrub": {}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
So(config.Extensions.UI, ShouldNotBeNil)
So(*config.Extensions.UI.Enable, ShouldBeTrue)
So(config.Extensions.Search, ShouldNotBeNil)
So(*config.Extensions.Search.Enable, ShouldBeTrue)
So(config.Extensions.Trust, ShouldNotBeNil)
So(*config.Extensions.Trust.Enable, ShouldBeTrue)
So(*config.Extensions.Metrics, ShouldNotBeNil)
So(*config.Extensions.Metrics.Enable, ShouldBeTrue)
So(config.Extensions.Scrub, ShouldNotBeNil)
So(*config.Extensions.Scrub.Enable, ShouldBeTrue)
})
}
func TestServeExtensions(t *testing.T) {
oldArgs := os.Args

View file

@ -303,7 +303,7 @@ func validateExtensionsConfig(cfg *config.Config, log zlog.Logger) error {
// it would make sense to also check for mgmt and user prefs to be enabled,
// but those are both enabled by having the search and ui extensions enabled
if cfg.Extensions.Search == nil || !*cfg.Extensions.Search.Enable {
log.Warn().Err(zerr.ErrBadConfig).Msg("UI functionality can't be used without search extension.")
log.Error().Err(zerr.ErrBadConfig).Msg("UI functionality can't be used without search extension.")
return zerr.ErrBadConfig
}
@ -312,7 +312,7 @@ func validateExtensionsConfig(cfg *config.Config, log zlog.Logger) error {
//nolint:lll
if cfg.Storage.StorageDriver != nil && cfg.Extensions != nil && cfg.Extensions.Search != nil &&
cfg.Extensions.Search.Enable != nil && *cfg.Extensions.Search.Enable && cfg.Extensions.Search.CVE != nil {
log.Warn().Err(zerr.ErrBadConfig).Msg("CVE functionality can't be used with remote storage. Please disable CVE")
log.Error().Err(zerr.ErrBadConfig).Msg("CVE functionality can't be used with remote storage. Please disable CVE")
return zerr.ErrBadConfig
}
@ -321,7 +321,7 @@ func validateExtensionsConfig(cfg *config.Config, log zlog.Logger) error {
//nolint:lll
if subPath.StorageDriver != nil && cfg.Extensions != nil && cfg.Extensions.Search != nil &&
cfg.Extensions.Search.Enable != nil && *cfg.Extensions.Search.Enable && cfg.Extensions.Search.CVE != nil {
log.Warn().Err(zerr.ErrBadConfig).Msg("CVE functionality can't be used with remote storage. Please disable CVE")
log.Error().Err(zerr.ErrBadConfig).Msg("CVE functionality can't be used with remote storage. Please disable CVE")
return zerr.ErrBadConfig
}

View file

@ -115,84 +115,6 @@ func TestVerify(t *testing.T) {
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify CVE warn for remote storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{
"storage":{
"rootDirectory":"/tmp/zot",
"dedupe":true,
"remoteCache":false,
"storageDriver":{
"name":"s3",
"rootdirectory":"/zot",
"region":"us-east-2",
"bucket":"zot-storage",
"secure":true,
"skipverify":false
}
},
"http":{
"address":"127.0.0.1",
"port":"8080"
},
"extensions":{
"search": {
"enable": true,
"cve": {
"updateInterval": "24h"
}
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
content = []byte(`{
"storage":{
"rootDirectory":"/tmp/zot",
"dedupe":true,
"remoteCache":false,
"subPaths":{
"/a": {
"rootDirectory": "/tmp/zot1",
"dedupe": false,
"storageDriver":{
"name":"s3",
"rootdirectory":"/zot-a",
"region":"us-east-2",
"bucket":"zot-storage",
"secure":true,
"skipverify":false
}
}
}
},
"http":{
"address":"127.0.0.1",
"port":"8080"
},
"extensions":{
"search": {
"enable": true,
"cve": {
"updateInterval": "24h"
}
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test cached db config", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
@ -777,95 +699,6 @@ func TestVerify(t *testing.T) {
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify w/ sync and w/o filesystem storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s"}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify w/ sync and w/ filesystem storage", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s"}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldNotPanic)
})
Convey("Test verify with bad sync prefixes", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"[repo%^&"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify with bad sync content config", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"zot-repo","stripPrefix":true,"destination":"/"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify with good sync content config", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"zot-repo/*","stripPrefix":true,"destination":"/"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
err = cli.NewServerRootCmd().Execute()
So(err, ShouldBeNil)
})
Convey("Test verify with bad authorization repo patterns", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
@ -882,42 +715,6 @@ func TestVerify(t *testing.T) {
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify sync config default tls value", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 1, "retryDelay": "10s",
"content": [{"prefix":"repo**"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
err = cli.NewServerRootCmd().Execute()
So(err, ShouldBeNil)
})
Convey("Test verify sync without retry options", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name()) // clean up
content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"},
"http":{"address":"127.0.0.1","port":"8080","realm":"zot",
"auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}},
"extensions":{"sync": {"registries": [{"urls":["localhost:9999"],
"maxRetries": 10, "content": [{"prefix":"repo**"}]}]}}}`)
_, err = tmpfile.Write(content)
So(err, ShouldBeNil)
err = tmpfile.Close()
So(err, ShouldBeNil)
os.Args = []string{"cli_test", "verify", tmpfile.Name()}
So(func() { _ = cli.NewServerRootCmd().Execute() }, ShouldPanic)
})
Convey("Test verify config with unknown keys", t, func(c C) {
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
@ -1063,140 +860,6 @@ func TestVerify(t *testing.T) {
})
}
func TestValidateExtensionsConfig(t *testing.T) {
Convey("Legacy extensions should not error", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"mgmt": {
"enable": "true"
},
"apikey": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
})
Convey("Test missing extensions for UI to work", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldNotBeNil)
})
Convey("Test enabling UI extension with all prerequisites", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {
"enable": "true"
},
"search": {
"enable": "true"
}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
})
Convey("Test extension are implicitly enabled", t, func(c C) {
config := config.New()
tmpfile, err := os.CreateTemp("", "zot-test*.json")
So(err, ShouldBeNil)
defer os.Remove(tmpfile.Name())
content := []byte(`{
"storage": {
"rootDirectory": "%/tmp/zot"
},
"http": {
"address": "127.0.0.1",
"port": "8080"
},
"log": {
"level": "debug"
},
"extensions": {
"ui": {},
"search": {},
"metrics": {},
"trust": {},
"scrub": {}
}
}`)
err = os.WriteFile(tmpfile.Name(), content, 0o0600)
So(err, ShouldBeNil)
err = cli.LoadConfiguration(config, tmpfile.Name())
So(err, ShouldBeNil)
So(config.Extensions.UI, ShouldNotBeNil)
So(*config.Extensions.UI.Enable, ShouldBeTrue)
So(config.Extensions.Search, ShouldNotBeNil)
So(*config.Extensions.Search.Enable, ShouldBeTrue)
So(config.Extensions.Trust, ShouldNotBeNil)
So(*config.Extensions.Trust.Enable, ShouldBeTrue)
So(*config.Extensions.Metrics, ShouldNotBeNil)
So(*config.Extensions.Metrics.Enable, ShouldBeTrue)
So(config.Extensions.Scrub, ShouldNotBeNil)
So(*config.Extensions.Scrub.Enable, ShouldBeTrue)
})
}
func TestApiKeyConfig(t *testing.T) {
Convey("Test API Keys are enabled if OpenID is enabled", t, func(c C) {
config := config.New()

View file

@ -245,6 +245,7 @@ func TestScheduler(t *testing.T) {
func TestGetNumWorkers(t *testing.T) {
Convey("Test setting the number of workers - default value", t, func() {
sch := scheduler.NewScheduler(config.New(), log.NewLogger("debug", "logFile"))
defer os.Remove("logFile")
So(sch.NumWorkers, ShouldEqual, runtime.NumCPU()*4)
})
@ -252,6 +253,7 @@ func TestGetNumWorkers(t *testing.T) {
cfg := config.New()
cfg.Scheduler = &config.SchedulerConfig{NumWorkers: 3}
sch := scheduler.NewScheduler(cfg, log.NewLogger("debug", "logFile"))
defer os.Remove("logFile")
So(sch.NumWorkers, ShouldEqual, 3)
})
}