Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: add blob policy import and show commands #1126

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions cmd/notation/blob/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package blob provides blob sign, verify, inspect, and policy commands.
package blob

import (
"github.com/notaryproject/notation/cmd/notation/blob/policy"
"github.com/spf13/cobra"
)

// Cmd returns the commands for blob
func Cmd() *cobra.Command {
command := &cobra.Command{
Use: "blob [command]",
Short: "Sign, inspect, verify signatures, and configure trust policies for blob artifacts",
Long: "Sign, inspect, verify signatures, and configure trust policies for blob artifacts.",
}

command.AddCommand(
policy.Cmd(),
)

return command
}
35 changes: 35 additions & 0 deletions cmd/notation/blob/policy/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package policy provides the import and show commands for blob trust policy.
package policy

import (
"github.com/spf13/cobra"
)

// Cmd returns the commands for policy including import and show.
func Cmd() *cobra.Command {
command := &cobra.Command{
Use: "policy [command]",
Short: "Manage trust policy configuration for signed blobs",
Long: "Manage trust policy configuration for arbitrary blob signature verification.",
}

command.AddCommand(
importCmd(),
showCmd(),
)

return command
}
102 changes: 102 additions & 0 deletions cmd/notation/blob/policy/import.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package policy

import (
"encoding/json"
"fmt"
"os"

"github.com/notaryproject/notation-go/dir"
"github.com/notaryproject/notation-go/verifier/trustpolicy"
"github.com/notaryproject/notation/cmd/notation/internal/cmdutil"
"github.com/notaryproject/notation/internal/osutil"
"github.com/spf13/cobra"
)

type importOpts struct {
filePath string
force bool
}

func importCmd() *cobra.Command {
var opts importOpts
command := &cobra.Command{
Use: "import [flags] <file_path>",
Short: "Import blob trust policy configuration from a JSON file",
Long: `Import blob trust policy configuration from a JSON file.

Example - Import blob trust policy configuration from a file:
notation blob policy import my_policy.json

Example - Import blob trust policy and override existing configuration without prompt:
notation blob policy import --force my_policy.json
`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("requires 1 argument but received %d.\nUsage: notation blob policy import <path-to-policy.json>\nPlease specify a trust policy file location as the argument", len(args))
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
opts.filePath = args[0]
return runImport(opts)
},
}
command.Flags().BoolVar(&opts.force, "force", false, "override the existing blob trust policy configuration without prompt")
return command
}

func runImport(opts importOpts) error {
// read configuration
policyJSON, err := os.ReadFile(opts.filePath)
if err != nil {
return fmt.Errorf("failed to read blob trust policy file: %w", err)
}

var doc trustpolicy.BlobDocument
if err = json.Unmarshal(policyJSON, &doc); err != nil {
return fmt.Errorf("failed to parse blob trust policy configuration: %w", err)
}
if err = doc.Validate(); err != nil {
return fmt.Errorf("failed to validate blob trust policy: %w", err)
}

// optional confirmation
if !opts.force {
if _, err = trustpolicy.LoadBlobDocument(); err == nil {
confirmed, err := cmdutil.AskForConfirmation(os.Stdin, "The blob trust policy file already exists, do you want to overwrite it?", opts.force)
if err != nil {
return err
}

Check warning on line 82 in cmd/notation/blob/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/blob/policy/import.go#L81-L82

Added lines #L81 - L82 were not covered by tests
if !confirmed {
return nil
}
}
} else {
fmt.Fprintln(os.Stderr, "Warning: existing blob trust policy file will be overwritten")
}

// write
policyPath, err := dir.ConfigFS().SysPath(dir.PathBlobTrustPolicy)
if err != nil {
return fmt.Errorf("failed to obtain path of blob trust policy file: %w", err)
}

Check warning on line 95 in cmd/notation/blob/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/blob/policy/import.go#L94-L95

Added lines #L94 - L95 were not covered by tests
if err = osutil.WriteFile(policyPath, policyJSON); err != nil {
return fmt.Errorf("failed to write blob trust policy file: %w", err)
}

_, err = fmt.Fprintln(os.Stdout, "Successfully imported blob trust policy file.")
return err
}
81 changes: 81 additions & 0 deletions cmd/notation/blob/policy/show.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package policy

import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"

"github.com/notaryproject/notation-go/dir"
"github.com/notaryproject/notation-go/verifier/trustpolicy"
"github.com/spf13/cobra"
)

func showCmd() *cobra.Command {
command := &cobra.Command{
Use: "show [flags]",
Short: "Show blob trust policy configuration",
Long: `Show blob trust policy configuration.

Example - Show current blob trust policy configuration:
notation blob policy show

Example - Save current blob trust policy configuration to a file:
notation blob policy show > my_policy.json
`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return runShow()
},
}
return command
}

func runShow() error {
policyJSON, err := loadBlobTrustPolicy()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("failed to show blob trust policy as the trust policy file does not exist.\nYou can import one using `notation blob policy import <path-to-policy.json>`")
}
return fmt.Errorf("failed to show trust policy: %w", err)
}
var doc trustpolicy.BlobDocument
if err = json.Unmarshal(policyJSON, &doc); err == nil {
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
err = doc.Validate()
}
if err != nil {
fmt.Fprintf(os.Stderr, "Existing blob trust policy file is invalid, you may update or create a new one via `notation blob policy import <path-to-policy.json>`. See https://github.com/notaryproject/specifications/blob/8cf800c60b7315a43f0adbcae463d848a353b412/specs/trust-store-trust-policy.md#trust-policy-for-blobs for a blob trust policy example.\n")
os.Stdout.Write(policyJSON)
return err
}

// show policy content
_, err = os.Stdout.Write(policyJSON)
return err
}

// loadBlobTrustPolicy loads the blob trust policy from notation configuration
// directory.
func loadBlobTrustPolicy() ([]byte, error) {
f, err := dir.ConfigFS().Open(dir.PathBlobTrustPolicy)
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
2 changes: 2 additions & 0 deletions cmd/notation/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"os"

"github.com/notaryproject/notation-go/dir"
"github.com/notaryproject/notation/cmd/notation/blob"
"github.com/notaryproject/notation/cmd/notation/cert"
"github.com/notaryproject/notation/cmd/notation/plugin"
"github.com/notaryproject/notation/cmd/notation/policy"
Expand Down Expand Up @@ -51,6 +52,7 @@ func main() {
},
}
cmd.AddCommand(
blob.Cmd(),
signCommand(nil),
verifyCommand(nil),
listCommand(nil),
Expand Down
10 changes: 10 additions & 0 deletions test/e2e/internal/notation/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,16 @@ func AddTrustPolicyOption(trustpolicyName string) utils.HostOption {
}
}

// AddBlobTrustPolicyOption adds a valid trust policy for testing.
func AddBlobTrustPolicyOption(trustpolicyName string) utils.HostOption {
return func(vhost *utils.VirtualHost) error {
return copyFile(
filepath.Join(NotationE2ETrustPolicyDir, trustpolicyName),
vhost.AbsolutePath(NotationDirName, BlobTrustPolicyName),
)
}
}

// AddConfigJsonOption adds a valid config.json for testing.
func AddConfigJsonOption(configJsonName string) utils.HostOption {
return func(vhost *utils.VirtualHost) error {
Expand Down
15 changes: 8 additions & 7 deletions test/e2e/internal/notation/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ import (
)

const (
NotationDirName = "notation"
TrustPolicyName = "trustpolicy.json"
TrustStoreDirName = "truststore"
TrustStoreTypeCA = "ca"
PluginDirName = "plugins"
PluginName = "e2e-plugin"
ConfigJsonName = "config.json"
NotationDirName = "notation"
TrustPolicyName = "trustpolicy.json"
BlobTrustPolicyName = "trustpolicy.blob.json"
TrustStoreDirName = "truststore"
TrustStoreTypeCA = "ca"
PluginDirName = "plugins"
PluginName = "e2e-plugin"
ConfigJsonName = "config.json"
)

const (
Expand Down
4 changes: 3 additions & 1 deletion test/e2e/internal/utils/validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
package validator

import (
"errors"
"io/fs"
"os"

. "github.com/onsi/gomega"
Expand All @@ -29,5 +31,5 @@ func CheckFileExist(f string) {
func CheckFileNotExist(f string) {
_, err := os.Stat(f)
Expect(err).Should(HaveOccurred())
Expect(os.IsNotExist(err)).To(BeTrue())
Expect(errors.Is(err, fs.ErrNotExist)).To(BeTrue())
}
26 changes: 26 additions & 0 deletions test/e2e/suite/command/blob/blob_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package blob

import (
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestCommand(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Blob Command Suite")
}
Loading
Loading