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 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
e067e69
feat: add blob policy commands
JeyJeyGao Dec 24, 2024
588f3e5
fix: add e2e test cases
JeyJeyGao Dec 24, 2024
1ff8547
fix: improve code
JeyJeyGao Dec 24, 2024
88aee76
fix: improve code
JeyJeyGao Dec 24, 2024
8fe215e
fix: improve code
JeyJeyGao Dec 24, 2024
e67b5fd
fix: improve code
JeyJeyGao Dec 24, 2024
1eb1908
fix: improve code
JeyJeyGao Dec 24, 2024
77d87e5
fix: split blob and OCI policy commands
JeyJeyGao Dec 27, 2024
b1ed2fa
fix: simplify code
JeyJeyGao Dec 27, 2024
91be43c
fix: simplify code
JeyJeyGao Dec 27, 2024
d70dd18
fix: update error message
JeyJeyGao Dec 27, 2024
62c874c
fix: optimize readability
JeyJeyGao Dec 27, 2024
3494909
fix: improve readability
JeyJeyGao Dec 27, 2024
5ab618b
fix: replace os.IsNotExist(err) with errors.Is(err, fs.ErrNotExist)
JeyJeyGao Dec 30, 2024
cf1fc19
fix: update help doc
JeyJeyGao Dec 30, 2024
8ecf320
fix: add E2E test cases
JeyJeyGao Dec 30, 2024
b595f64
fix: resolve comments
JeyJeyGao Dec 30, 2024
43878ed
fix: remove the change of oci policy commands
JeyJeyGao Dec 30, 2024
fad665c
fix: remove unused file
JeyJeyGao Dec 30, 2024
71f522a
fix: E2E test
JeyJeyGao Dec 30, 2024
ec7fe13
fix: resolve comment for Two-Hearts
JeyJeyGao Jan 6, 2025
4d13267
fix: resolve comments for Patrick
JeyJeyGao Jan 7, 2025
b76c4eb
fix: resolve comment
JeyJeyGao Jan 7, 2025
4360cfb
fix: update error message link
JeyJeyGao Jan 7, 2025
15d940e
Merge remote-tracking branch 'upstream/main' into feat/blob_policy_cmd
JeyJeyGao Jan 14, 2025
0cb99f7
fix: bump up
JeyJeyGao Jan 14, 2025
6b9922a
Merge remote-tracking branch 'upstream/main' into feat/blob_policy_cmd
JeyJeyGao Jan 14, 2025
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
32 changes: 32 additions & 0 deletions cmd/notation/blob/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// 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 the command for blob trust policy configuration.
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
package blob

import "github.com/spf13/cobra"

// Cmd returns the command for blob
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
func Cmd() *cobra.Command {
command := &cobra.Command{
Use: "blob [commnad]",
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
Short: "Sign, verify and inspect singatures associated with blobs",
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
Long: "Sign, inspect, and verify signatures and configure trust policies.",
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
}

command.AddCommand(
policyCmd(),
)

return command
}
86 changes: 86 additions & 0 deletions cmd/notation/blob/policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// 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 (
"fmt"

"github.com/notaryproject/notation/cmd/notation/internal/policy"
"github.com/spf13/cobra"
)

func policyCmd() *cobra.Command {
command := &cobra.Command{
Use: "policy [command]",
Short: "manage trust policy configuration for signed blobs",
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
Long: "Manage trust policy configuration for arbitrary blob signature verification.",
}

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

return command
}

type importOpts struct {
filePath string
force bool
}

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

Example - Import trust policy configuration from a file:
notation blob policy import 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 policy.Import(opts.filePath, opts.force, false)
},
}
command.Flags().BoolVar(&opts.force, "force", false, "override the existing trust policy configuration, never prompt")
return command
}

func showCmd() *cobra.Command {
command := &cobra.Command{
Use: "show [flags]",
Short: "show 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 policy.Show(false)
},
}
return command
}
102 changes: 102 additions & 0 deletions cmd/notation/internal/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"
)

type policy interface {
Validate() error
}

// Import imports trust policy configuration from a JSON file.
//
// - If force is true, it will override the existing trust policy configuration
// without prompting.
// - If isOciPolicy is true, it will import OCI trust policy configuration.
// Otherwise, it will import blob trust policy configuration.
func Import(filePath string, force, isOCIPolicy bool) error {
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
// read configuration
policyJSON, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read trust policy file: %w", err)
}

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

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

Check warning on line 67 in cmd/notation/internal/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/internal/policy/import.go#L66-L67

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

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

Check warning on line 84 in cmd/notation/internal/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/internal/policy/import.go#L83-L84

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

// clear old trust policy
if isOCIPolicy {
oldPolicyPath, err := dir.ConfigFS().SysPath(dir.PathTrustPolicy)
if err != nil {
return fmt.Errorf("failed to obtain path of trust policy file: %w", err)
}

Check warning on line 94 in cmd/notation/internal/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/internal/policy/import.go#L93-L94

Added lines #L93 - L94 were not covered by tests
if err := osutil.RemoveIfExists(oldPolicyPath); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to clear old trust policy %q: %v\n", oldPolicyPath, err)
}

Check warning on line 97 in cmd/notation/internal/policy/import.go

View check run for this annotation

Codecov / codecov/patch

cmd/notation/internal/policy/import.go#L96-L97

Added lines #L96 - L97 were not covered by tests
}

_, err = fmt.Fprintln(os.Stdout, "Trust policy configuration imported successfully.")
return err
}
88 changes: 88 additions & 0 deletions cmd/notation/internal/policy/show.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// 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"
)

// Show shows trust policy configuration.
//
// - If isOciPolicy is true, it will show OCI trust policy configuration.
// Otherwise, it will show blob trust policy configuration.
func Show(isOCIPolicy bool) error {
var (
doc policy
policyJSON []byte
err error
)
if isOCIPolicy {
doc = &trustpolicy.OCIDocument{}
policyJSON, err = loadOCIDocument()
} else {
doc = &trustpolicy.BlobDocument{}
policyJSON, err = loadBlobDocument()
}
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("failed to show trust policy as the trust policy file does not exist.\nYou can import one using `notation policy import <path-to-policy.json>`")
}
return fmt.Errorf("failed to show trust policy: %w", err)
}

if err = json.Unmarshal(policyJSON, &doc); err == nil {
err = doc.Validate()
}
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
fmt.Fprintf(os.Stderr, "Existing trust policy configuration is invalid, you may update or create a new one via `notation policy import <path-to-policy.json>`\n")
// not returning to show the invalid policy configuration
}

// show policy content
_, err = os.Stdout.Write(policyJSON)
return err
}
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved

func loadOCIDocument() ([]byte, error) {
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
f, err := dir.ConfigFS().Open(dir.PathOCITrustPolicy)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
f, err = dir.ConfigFS().Open(dir.PathTrustPolicy)
if err != nil {
return nil, err
}
}
defer f.Close()
return io.ReadAll(f)
}

func loadBlobDocument() ([]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
52 changes: 2 additions & 50 deletions cmd/notation/policy/import.go
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,9 @@
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/notaryproject/notation/cmd/notation/internal/policy"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -50,52 +45,9 @@ Example - Import trust policy configuration from a file:
},
RunE: func(cmd *cobra.Command, args []string) error {
opts.filePath = args[0]
return runImport(cmd, opts)
return policy.Import(opts.filePath, opts.force, true)
},
}
command.Flags().BoolVar(&opts.force, "force", false, "override the existing trust policy configuration, never prompt")
return command
}

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

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

// optional confirmation
if !opts.force {
if _, err := trustpolicy.LoadDocument(); err == nil {
confirmed, err := cmdutil.AskForConfirmation(os.Stdin, "The trust policy file already exists, do you want to overwrite it?", opts.force)
if err != nil {
return err
}
if !confirmed {
return nil
}
}
} else {
fmt.Fprintln(os.Stderr, "Warning: existing trust policy configuration file will be overwritten")
}

// write
policyPath, err := dir.ConfigFS().SysPath(dir.PathTrustPolicy)
if err != nil {
return fmt.Errorf("failed to obtain path of trust policy file: %w", err)
}
if err = osutil.WriteFile(policyPath, policyJSON); err != nil {
return fmt.Errorf("failed to write trust policy file: %w", err)
}
_, err = fmt.Fprintln(os.Stdout, "Trust policy configuration imported successfully.")
return err
}
Loading
Loading