Debian Codegraph @

verifier/trustpolicy/oci.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package trustpolicy
15
16 import (
17 "errors"
18 "fmt"
19 "regexp"
20 "strings"
21
22 "github.com/notaryproject/notation-go/dir"
23 set "github.com/notaryproject/notation-go/internal/container"
24 "github.com/notaryproject/notation-go/internal/slices"
25 "github.com/notaryproject/notation-go/internal/trustpolicy"
26 )
27
28 // Document represents a trustpolicy.json document
29 type Document struct {
30 // Version of the policy document
31 Version string `json:"version"`
32
33 // TrustPolicies include each policy statement
34 TrustPolicies []TrustPolicy `json:"trustPolicies"`
35 }
36
37 // TrustPolicy represents a policy statement in the policy document
38 type TrustPolicy struct {
39 // Name of the policy statement
40 Name string `json:"name"`
41
42 // RegistryScopes that this policy statement affects
43 RegistryScopes []string `json:"registryScopes"`
44
45 // SignatureVerification setting for this policy statement
46 SignatureVerification SignatureVerification `json:"signatureVerification"`
47
48 // TrustStores this policy statement uses
49 TrustStores []string `json:"trustStores"`
50
51 // TrustedIdentities this policy statement pins
52 TrustedIdentities []string `json:"trustedIdentities"`
53 }
54
55 var supportedPolicyVersions = []string{"1.0"}
56
57 // LoadDocument retrieves a trust policy document from the local file system.
58 func LoadDocument() (*Document, error) {
59 var doc Document
60 if err := getDocument(dir.PathTrustPolicy, &doc); err != nil {
61 return nil, err
62 }
63 return &doc, nil
64 }
65
66 // Validate validates a policy document according to its version's rule set.
67 // if any rule is violated, returns an error
68 func (policyDoc *Document) Validate() error {
69 // sanity check
70 if policyDoc == nil {
71 return errors.New("trust policy document cannot be nil")
72 }
73
74 // Validate Version
75 if policyDoc.Version == "" {
76 return errors.New("trust policy document has empty version, version must be specified")
77 }
78 if !slices.Contains(supportedPolicyVersions, policyDoc.Version) {
79 return fmt.Errorf("trust policy document uses unsupported version %q", policyDoc.Version)
80 }
81
82 // Validate the policy according to 1.0 rules
83 if len(policyDoc.TrustPolicies) == 0 {
84 return errors.New("trust policy document can not have zero trust policy statements")
85 }
86
87 policyNames := set.New[string]()
88 for _, statement := range policyDoc.TrustPolicies {
89 // Verify unique policy statement names across the policy document
90 if policyNames.Contains(statement.Name) {
91 return fmt.Errorf("multiple trust policy statements use the same name %q, statement names must be unique", statement.Name)
92 }
93
94 if err := validatePolicyCore(statement.Name, statement.SignatureVerification, statement.TrustStores, statement.TrustedIdentities); err != nil {
95 return fmt.Errorf("trust policy: %w", err)
96 }
97
98 policyNames.Add(statement.Name)
99 }
100
101 // Verify registry scopes are valid
102 if err := validateRegistryScopes(policyDoc); err != nil {
103 return err
104 }
105
106 return nil
107 }
108
109 // GetApplicableTrustPolicy returns a pointer to the deep copied TrustPolicy
110 // statement that applies to the given registry scope. If no applicable trust
111 // policy is found, returns an error
112 // see https://github.com/notaryproject/notaryproject/blob/v1.0.0/specs/trust-store-trust-policy.md#selecting-a-trust-policy-based-on-artifact-uri
113 func (policyDoc *Document) GetApplicableTrustPolicy(artifactReference string) (*TrustPolicy, error) {
114 artifactPath, err := getArtifactPathFromReference(artifactReference)
115 if err != nil {
116 return nil, err
117 }
118
119 var wildcardPolicy *TrustPolicy
120 var applicablePolicy *TrustPolicy
121 for _, policyStatement := range policyDoc.TrustPolicies {
122 if slices.Contains(policyStatement.RegistryScopes, trustpolicy.Wildcard) {
123 // we need to deep copy because we can't use the loop variable
124 // address. see https://stackoverflow.com/a/45967429
125 wildcardPolicy = (&policyStatement).clone()
126 } else if slices.Contains(policyStatement.RegistryScopes, artifactPath) {
127 applicablePolicy = (&policyStatement).clone()
128 }
129 }
130
131 if applicablePolicy != nil {
132 // a policy with exact match for registry scope takes precedence over
133 // a wildcard (*) policy.
134 return applicablePolicy, nil
135 } else if wildcardPolicy != nil {
136 return wildcardPolicy, nil
137 } else {
138 return nil, fmt.Errorf("artifact %q has no applicable trust policy statement. Trust policy applicability for a given artifact is determined by registryScopes. To create a trust policy, see: %s", artifactReference, trustPolicyLink)
139 }
140 }
141
142 // clone returns a pointer to the deeply copied TrustPolicy
143 func (t *TrustPolicy) clone() *TrustPolicy {
144 return &TrustPolicy{
145 Name: t.Name,
146 SignatureVerification: t.SignatureVerification,
147 TrustedIdentities: append([]string(nil), t.TrustedIdentities...),
148 TrustStores: append([]string(nil), t.TrustStores...),
149 RegistryScopes: append([]string(nil), t.RegistryScopes...),
150 }
151 }
152
153 // validateRegistryScopes validates if the policy document is following the
154 // Notary Project spec rules for registry scopes
155 func validateRegistryScopes(policyDoc *Document) error {
156 registryScopeCount := make(map[string]int)
157 for _, statement := range policyDoc.TrustPolicies {
158 // Verify registry scopes are valid
159 if len(statement.RegistryScopes) == 0 {
160 return fmt.Errorf("trust policy statement %q has zero registry scopes, it must specify registry scopes with at least one value", statement.Name)
161 }
162 if len(statement.RegistryScopes) > 1 && slices.Contains(statement.RegistryScopes, trustpolicy.Wildcard) {
163 return fmt.Errorf("trust policy statement %q uses wildcard registry scope '*', a wildcard scope cannot be used in conjunction with other scope values", statement.Name)
164 }
165 for _, scope := range statement.RegistryScopes {
166 if scope != trustpolicy.Wildcard {
167 if err := validateRegistryScopeFormat(scope); err != nil {
168 return err
169 }
170 }
171 registryScopeCount[scope]++
172 }
173 }
174
175 // Verify one policy statement per registry scope
176 for key := range registryScopeCount {
177 if registryScopeCount[key] > 1 {
178 return fmt.Errorf("registry scope %q is present in multiple trust policy statements, one registry scope value can only be associated with one statement", key)
179 }
180 }
181
182 // No error
183 return nil
184 }
185
186 func getArtifactPathFromReference(artifactReference string) (string, error) {
187 // TODO support more types of URI like "domain.com/repository",
188 // "domain.com/repository:tag"
189 i := strings.LastIndex(artifactReference, "@")
190 if i < 0 {
191 return "", fmt.Errorf("artifact URI %q could not be parsed, make sure it is the fully qualified oci artifact URI without the scheme/protocol. e.g domain.com:80/my/repository@sha256:digest", artifactReference)
192 }
193
194 artifactPath := artifactReference[:i]
195 if err := validateRegistryScopeFormat(artifactPath); err != nil {
196 return "", err
197 }
198 return artifactPath, nil
199 }
200
201 // validateRegistryScopeFormat validates if a scope is following the format
202 // defined in distribution spec
203 func validateRegistryScopeFormat(scope string) error {
204 // Domain and Repository regexes are adapted from distribution
205 // implementation
206 // https://github.com/distribution/distribution/blob/main/reference/regexp.go#L31
207 domainRegexp := regexp.MustCompile(`^(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])(?:(?:\.(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]))+)?(?::[0-9]+)?$`)
208 repositoryRegexp := regexp.MustCompile(`^[a-z0-9]+(?:(?:(?:[._]|__|[-]*)[a-z0-9]+)+)?(?:(?:/[a-z0-9]+(?:(?:(?:[._]|__|[-]*)[a-z0-9]+)+)?)+)?$`)
209 ensureMessage := "make sure it is a fully qualified repository without the scheme, protocol or tag. For example domain.com/my/repository or a local scope like local/myOCILayout"
210 errorMessage := "registry scope %q is not valid, " + ensureMessage
211 errorWildCardMessage := "registry scope %q with wild card(s) is not valid, " + ensureMessage
212
213 // Check for presence of * in scope
214 if len(scope) > 1 && strings.Contains(scope, "*") {
215 return fmt.Errorf(errorWildCardMessage, scope)
216 }
217
218 domain, repository, found := strings.Cut(scope, "/")
219 if !found {
220 return fmt.Errorf(errorMessage, scope)
221 }
222
223 if domain == "" || repository == "" || !domainRegexp.MatchString(domain) || !repositoryRegexp.MatchString(repository) {
224 return fmt.Errorf(errorMessage, scope)
225 }
226
227 // No errors
228 return nil
229 }