blob: 63946a7ed7668fedb71fabd4ca450c53aec37a97 [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "path/filepath"
19 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010020 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080021 "strconv"
22 "strings"
23
24 "github.com/google/blueprint/proptools"
25)
26
27// "neverallow" rules for the build system.
28//
29// This allows things which aren't related to the build system and are enforced
30// for sanity, in progress code refactors, or policy to be expressed in a
31// straightforward away disjoint from implementations and tests which should
32// work regardless of these restrictions.
33//
34// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010035// - it is in one of the "In" paths
36// - it is not in one of the "NotIn" paths
37// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080038// - - values are matched in their entirety
39// - - nil is interpreted as an empty string
40// - - nested properties are separated with a '.'
41// - - if the property is a list, any of the values in the list being matches
42// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010043// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080044
Artur Satayevc5570ac2020-04-09 16:06:36 +010045func RegisterNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080046 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
47}
48
Paul Duffin730f2a52019-06-27 14:08:51 +010049var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080050
Paul Duffin730f2a52019-06-27 14:08:51 +010051func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010052 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010053 AddNeverAllowRules(createTrebleRules()...)
54 AddNeverAllowRules(createLibcoreRules()...)
55 AddNeverAllowRules(createMediaRules()...)
56 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000057 AddNeverAllowRules(createCcSdkVariantRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010058}
Steven Moreland65b3fd92017-12-06 14:18:35 -080059
Paul Duffin730f2a52019-06-27 14:08:51 +010060// Add a NeverAllow rule to the set of rules to apply.
61func AddNeverAllowRules(rules ...Rule) {
62 neverallows = append(neverallows, rules...)
63}
64
Paul Duffinc8111702019-07-22 12:13:55 +010065func createIncludeDirsRules() []Rule {
66 // The list of paths that cannot be referenced using include_dirs
67 paths := []string{
68 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000069 "art/libnativebridge",
70 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010071 "libcore",
72 "libnativehelper",
73 "external/apache-harmony",
74 "external/apache-xml",
75 "external/boringssl",
76 "external/bouncycastle",
77 "external/conscrypt",
78 "external/icu",
79 "external/okhttp",
80 "external/vixl",
81 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010082 }
83
84 // Create a composite matcher that will match if the value starts with any of the restricted
85 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
86 // XY.
87 rules := make([]Rule, 0, len(paths))
88 for _, path := range paths {
89 rule :=
90 NeverAllow().
91 WithMatcher("include_dirs", StartsWith(path+"/")).
92 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
93 " to use alternate mechanisms and so can no longer be used.")
94
95 rules = append(rules, rule)
96 }
97
98 return rules
99}
100
Paul Duffin730f2a52019-06-27 14:08:51 +0100101func createTrebleRules() []Rule {
102 return []Rule{
103 NeverAllow().
104 In("vendor", "device").
105 With("vndk.enabled", "true").
106 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900107 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100108 Because("the VNDK can never contain a library that is device dependent."),
109 NeverAllow().
110 With("vndk.enabled", "true").
111 Without("vendor", "true").
112 Without("owner", "").
113 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800114
Neil Fullerdf5f3562018-10-21 17:19:10 +0100115 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100116 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800117 Without("name", "libhidlbase-combined-impl").
118 Without("name", "libhidlbase").
119 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100120 With("product_variables.enforce_vintf_manifest.cflags", "*").
121 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100122
123 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100124 NeverAllow().
125 Without("name", "libc_bionic_ndk").
126 With("product_variables.treble_linker_namespaces.cflags", "*").
127 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100128
129 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100130 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100131 }
132}
133
Paul Duffin730f2a52019-06-27 14:08:51 +0100134func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100135 var coreLibraryProjects = []string{
136 "libcore",
137 "external/apache-harmony",
138 "external/apache-xml",
139 "external/bouncycastle",
140 "external/conscrypt",
141 "external/icu",
142 "external/okhttp",
143 "external/wycheproof",
Paul Duffine5c3b852020-05-12 15:27:56 +0100144 "prebuilts",
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145 }
146
Paul Duffina3d09862019-06-11 13:40:47 +0100147 // Core library constraints. The sdk_version: "none" can only be used in core library projects.
148 // Access to core library targets is restricted using visibility rules.
Paul Duffin730f2a52019-06-27 14:08:51 +0100149 rules := []Rule{
150 NeverAllow().
151 NotIn(coreLibraryProjects...).
Anton Hansson45376402020-04-09 14:18:21 +0100152 With("sdk_version", "none").
153 WithoutMatcher("name", Regexp("^android_.*stubs_current$")),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100154 }
155
Neil Fullerdf5f3562018-10-21 17:19:10 +0100156 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800157}
158
Paul Duffin730f2a52019-06-27 14:08:51 +0100159func createMediaRules() []Rule {
160 return []Rule{
161 NeverAllow().
162 With("libs", "updatable-media").
163 Because("updatable-media includes private APIs. Use updatable_media_stubs instead."),
Dongwon Kang50a299f2019-02-04 09:00:51 -0800164 }
165}
166
Paul Duffin730f2a52019-06-27 14:08:51 +0100167func createJavaDeviceForHostRules() []Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800168 javaDeviceForHostProjectsWhitelist := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700169 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800170 "external/robolectric-shadows",
171 "framework/layoutlib",
172 }
173
Paul Duffin730f2a52019-06-27 14:08:51 +0100174 return []Rule{
175 NeverAllow().
176 NotIn(javaDeviceForHostProjectsWhitelist...).
177 ModuleType("java_device_for_host", "java_host_for_device").
178 Because("java_device_for_host can only be used in whitelisted projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800179 }
180}
181
Colin Crossc511bc52020-04-07 16:50:32 +0000182func createCcSdkVariantRules() []Rule {
183 sdkVersionOnlyWhitelist := []string{
184 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
185 // This sometimes works because the APEX modules that contain derive_sdk and
186 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
187 // the APEX modules contain the SDK variant and the platform variant still exists.
188 "frameworks/base/apex/sdkextensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700189 // These are for apps and shouldn't be used by non-SDK variant modules.
190 "prebuilts/ndk",
191 "tools/test/graphicsbenchmark/apps/sample_app",
192 "tools/test/graphicsbenchmark/functional_tests/java",
Colin Crossc511bc52020-04-07 16:50:32 +0000193 }
194
195 platformVariantPropertiesWhitelist := []string{
196 // android_native_app_glue and libRSSupport use native_window.h but target old
197 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
198 // so they can't add libnativewindow to shared_libs to get the header directory
199 // for the platform variant. Allow them to use the platform variant
200 // property to set shared_libs.
201 "prebuilts/ndk",
202 "frameworks/rs",
203 }
204
205 return []Rule{
206 NeverAllow().
207 NotIn(sdkVersionOnlyWhitelist...).
208 WithMatcher("sdk_variant_only", isSetMatcherInstance).
209 Because("sdk_variant_only can only be used in whitelisted projects"),
210 NeverAllow().
211 NotIn(platformVariantPropertiesWhitelist...).
212 WithMatcher("platform.shared_libs", isSetMatcherInstance).
213 Because("platform variant properties can only be used in whitelisted projects"),
214 }
215}
216
Steven Moreland65b3fd92017-12-06 14:18:35 -0800217func neverallowMutator(ctx BottomUpMutatorContext) {
218 m, ok := ctx.Module().(Module)
219 if !ok {
220 return
221 }
222
223 dir := ctx.ModuleDir() + "/"
224 properties := m.GetProperties()
225
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100226 osClass := ctx.Module().Target().Os.Class
227
Paul Duffin115445b2019-08-07 15:31:07 +0100228 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100229 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800230 if !n.appliesToPath(dir) {
231 continue
232 }
233
Colin Crossfd4f7432019-03-05 15:06:16 -0800234 if !n.appliesToModuleType(ctx.ModuleType()) {
235 continue
236 }
237
Steven Moreland65b3fd92017-12-06 14:18:35 -0800238 if !n.appliesToProperties(properties) {
239 continue
240 }
241
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100242 if !n.appliesToOsClass(osClass) {
243 continue
244 }
245
Paul Duffin35781882019-07-25 15:41:09 +0100246 if !n.appliesToDirectDeps(ctx) {
247 continue
248 }
249
Steven Moreland65b3fd92017-12-06 14:18:35 -0800250 ctx.ModuleErrorf("violates " + n.String())
251 }
252}
253
Paul Duffin73bf0542019-07-12 14:12:49 +0100254type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100255 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100256 String() string
257}
258
259type equalMatcher struct {
260 expected string
261}
262
Artur Satayevc5570ac2020-04-09 16:06:36 +0100263func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100264 return m.expected == value
265}
266
267func (m *equalMatcher) String() string {
268 return "=" + m.expected
269}
270
271type anyMatcher struct {
272}
273
Artur Satayevc5570ac2020-04-09 16:06:36 +0100274func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100275 return true
276}
277
278func (m *anyMatcher) String() string {
279 return "=*"
280}
281
282var anyMatcherInstance = &anyMatcher{}
283
Paul Duffinc8111702019-07-22 12:13:55 +0100284type startsWithMatcher struct {
285 prefix string
286}
287
Artur Satayevc5570ac2020-04-09 16:06:36 +0100288func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100289 return strings.HasPrefix(value, m.prefix)
290}
291
292func (m *startsWithMatcher) String() string {
293 return ".starts-with(" + m.prefix + ")"
294}
295
Anton Hansson45376402020-04-09 14:18:21 +0100296type regexMatcher struct {
297 re *regexp.Regexp
298}
299
Artur Satayevc5570ac2020-04-09 16:06:36 +0100300func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100301 return m.re.MatchString(value)
302}
303
304func (m *regexMatcher) String() string {
305 return ".regexp(" + m.re.String() + ")"
306}
307
Colin Crossc511bc52020-04-07 16:50:32 +0000308type isSetMatcher struct{}
309
Artur Satayevc5570ac2020-04-09 16:06:36 +0100310func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000311 return value != ""
312}
313
314func (m *isSetMatcher) String() string {
315 return ".is-set"
316}
317
318var isSetMatcherInstance = &isSetMatcher{}
319
Steven Moreland65b3fd92017-12-06 14:18:35 -0800320type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100321 fields []string // e.x.: Vndk.Enabled
322 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800323}
324
Paul Duffin730f2a52019-06-27 14:08:51 +0100325// A NeverAllow rule.
326type Rule interface {
327 In(path ...string) Rule
328
329 NotIn(path ...string) Rule
330
Paul Duffin35781882019-07-25 15:41:09 +0100331 InDirectDeps(deps ...string) Rule
332
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100333 WithOsClass(osClasses ...OsClass) Rule
334
Paul Duffin730f2a52019-06-27 14:08:51 +0100335 ModuleType(types ...string) Rule
336
337 NotModuleType(types ...string) Rule
338
339 With(properties, value string) Rule
340
Paul Duffinc8111702019-07-22 12:13:55 +0100341 WithMatcher(properties string, matcher ValueMatcher) Rule
342
Paul Duffin730f2a52019-06-27 14:08:51 +0100343 Without(properties, value string) Rule
344
Paul Duffinc8111702019-07-22 12:13:55 +0100345 WithoutMatcher(properties string, matcher ValueMatcher) Rule
346
Paul Duffin730f2a52019-06-27 14:08:51 +0100347 Because(reason string) Rule
348}
349
Steven Moreland65b3fd92017-12-06 14:18:35 -0800350type rule struct {
351 // User string for why this is a thing.
352 reason string
353
354 paths []string
355 unlessPaths []string
356
Paul Duffin35781882019-07-25 15:41:09 +0100357 directDeps map[string]bool
358
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100359 osClasses []OsClass
360
Colin Crossfd4f7432019-03-05 15:06:16 -0800361 moduleTypes []string
362 unlessModuleTypes []string
363
Steven Moreland65b3fd92017-12-06 14:18:35 -0800364 props []ruleProperty
365 unlessProps []ruleProperty
366}
367
Paul Duffin730f2a52019-06-27 14:08:51 +0100368// Create a new NeverAllow rule.
369func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100370 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800371}
Colin Crossfd4f7432019-03-05 15:06:16 -0800372
Paul Duffin730f2a52019-06-27 14:08:51 +0100373func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800374 r.paths = append(r.paths, cleanPaths(path)...)
375 return r
376}
Colin Crossfd4f7432019-03-05 15:06:16 -0800377
Paul Duffin730f2a52019-06-27 14:08:51 +0100378func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800379 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
380 return r
381}
Colin Crossfd4f7432019-03-05 15:06:16 -0800382
Paul Duffin35781882019-07-25 15:41:09 +0100383func (r *rule) InDirectDeps(deps ...string) Rule {
384 for _, d := range deps {
385 r.directDeps[d] = true
386 }
387 return r
388}
389
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100390func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
391 r.osClasses = append(r.osClasses, osClasses...)
392 return r
393}
394
Paul Duffin730f2a52019-06-27 14:08:51 +0100395func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800396 r.moduleTypes = append(r.moduleTypes, types...)
397 return r
398}
399
Paul Duffin730f2a52019-06-27 14:08:51 +0100400func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800401 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
402 return r
403}
404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100406 return r.WithMatcher(properties, selectMatcher(value))
407}
408
409func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800410 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100411 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100412 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800413 })
414 return r
415}
Colin Crossfd4f7432019-03-05 15:06:16 -0800416
Paul Duffin730f2a52019-06-27 14:08:51 +0100417func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100418 return r.WithoutMatcher(properties, selectMatcher(value))
419}
420
421func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800422 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100423 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100424 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800425 })
426 return r
427}
Colin Crossfd4f7432019-03-05 15:06:16 -0800428
Paul Duffin73bf0542019-07-12 14:12:49 +0100429func selectMatcher(expected string) ValueMatcher {
430 if expected == "*" {
431 return anyMatcherInstance
432 }
433 return &equalMatcher{expected: expected}
434}
435
Paul Duffin730f2a52019-06-27 14:08:51 +0100436func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800437 r.reason = reason
438 return r
439}
440
441func (r *rule) String() string {
442 s := "neverallow"
443 for _, v := range r.paths {
444 s += " dir:" + v + "*"
445 }
446 for _, v := range r.unlessPaths {
447 s += " -dir:" + v + "*"
448 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800449 for _, v := range r.moduleTypes {
450 s += " type:" + v
451 }
452 for _, v := range r.unlessModuleTypes {
453 s += " -type:" + v
454 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800455 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100456 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457 }
458 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100459 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800460 }
Paul Duffin35781882019-07-25 15:41:09 +0100461 for k := range r.directDeps {
462 s += " deps:" + k
463 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100464 for _, v := range r.osClasses {
465 s += " os:" + v.String()
466 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800467 if len(r.reason) != 0 {
468 s += " which is restricted because " + r.reason
469 }
470 return s
471}
472
473func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800474 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
475 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800476 return includePath && !excludePath
477}
478
Paul Duffin35781882019-07-25 15:41:09 +0100479func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
480 if len(r.directDeps) == 0 {
481 return true
482 }
483
484 matches := false
485 ctx.VisitDirectDeps(func(m Module) {
486 if !matches {
487 name := ctx.OtherModuleName(m)
488 matches = r.directDeps[name]
489 }
490 })
491
492 return matches
493}
494
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100495func (r *rule) appliesToOsClass(osClass OsClass) bool {
496 if len(r.osClasses) == 0 {
497 return true
498 }
499
500 for _, c := range r.osClasses {
501 if c == osClass {
502 return true
503 }
504 }
505
506 return false
507}
508
Colin Crossfd4f7432019-03-05 15:06:16 -0800509func (r *rule) appliesToModuleType(moduleType string) bool {
510 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
511}
512
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513func (r *rule) appliesToProperties(properties []interface{}) bool {
514 includeProps := hasAllProperties(properties, r.props)
515 excludeProps := hasAnyProperty(properties, r.unlessProps)
516 return includeProps && !excludeProps
517}
518
Paul Duffinc8111702019-07-22 12:13:55 +0100519func StartsWith(prefix string) ValueMatcher {
520 return &startsWithMatcher{prefix}
521}
522
Anton Hansson45376402020-04-09 14:18:21 +0100523func Regexp(re string) ValueMatcher {
524 r, err := regexp.Compile(re)
525 if err != nil {
526 panic(err)
527 }
528 return &regexMatcher{r}
529}
530
Steven Moreland65b3fd92017-12-06 14:18:35 -0800531// assorted utils
532
533func cleanPaths(paths []string) []string {
534 res := make([]string, len(paths))
535 for i, v := range paths {
536 res[i] = filepath.Clean(v) + "/"
537 }
538 return res
539}
540
541func fieldNamesForProperties(propertyNames string) []string {
542 names := strings.Split(propertyNames, ".")
543 for i, v := range names {
544 names[i] = proptools.FieldNameForProperty(v)
545 }
546 return names
547}
548
Steven Moreland65b3fd92017-12-06 14:18:35 -0800549func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
550 for _, v := range props {
551 if hasProperty(properties, v) {
552 return true
553 }
554 }
555 return false
556}
557
558func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
559 for _, v := range props {
560 if !hasProperty(properties, v) {
561 return false
562 }
563 }
564 return true
565}
566
567func hasProperty(properties []interface{}, prop ruleProperty) bool {
568 for _, propertyStruct := range properties {
569 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
570 for _, v := range prop.fields {
571 if !propertiesValue.IsValid() {
572 break
573 }
574 propertiesValue = propertiesValue.FieldByName(v)
575 }
576 if !propertiesValue.IsValid() {
577 continue
578 }
579
Paul Duffin73bf0542019-07-12 14:12:49 +0100580 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100581 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800582 }
583
584 if matchValue(propertiesValue, check) {
585 return true
586 }
587 }
588 return false
589}
590
591func matchValue(value reflect.Value, check func(string) bool) bool {
592 if !value.IsValid() {
593 return false
594 }
595
596 if value.Kind() == reflect.Ptr {
597 if value.IsNil() {
598 return check("")
599 }
600 value = value.Elem()
601 }
602
603 switch value.Kind() {
604 case reflect.String:
605 return check(value.String())
606 case reflect.Bool:
607 return check(strconv.FormatBool(value.Bool()))
608 case reflect.Int:
609 return check(strconv.FormatInt(value.Int(), 10))
610 case reflect.Slice:
611 slice, ok := value.Interface().([]string)
612 if !ok {
613 panic("Can only handle slice of string")
614 }
615 for _, v := range slice {
616 if check(v) {
617 return true
618 }
619 }
620 return false
621 }
622
623 panic("Can't handle type: " + value.Kind().String())
624}
Paul Duffin115445b2019-08-07 15:31:07 +0100625
626var neverallowRulesKey = NewOnceKey("neverallowRules")
627
628func neverallowRules(config Config) []Rule {
629 return config.Once(neverallowRulesKey, func() interface{} {
630 // No test rules were set by setTestNeverallowRules, use the global rules
631 return neverallows
632 }).([]Rule)
633}
634
635// Overrides the default neverallow rules for the supplied config.
636//
637// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100638func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100639 config.Once(neverallowRulesKey, func() interface{} { return testRules })
640}