blob: be3f7123b094b5335da117c23864ce1b6fae9d65 [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()...)
David Srbeckye033cba2020-05-20 22:20:28 +010058 AddNeverAllowRules(createUncompressDexRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010059}
Steven Moreland65b3fd92017-12-06 14:18:35 -080060
Paul Duffin730f2a52019-06-27 14:08:51 +010061// Add a NeverAllow rule to the set of rules to apply.
62func AddNeverAllowRules(rules ...Rule) {
63 neverallows = append(neverallows, rules...)
64}
65
Paul Duffinc8111702019-07-22 12:13:55 +010066func createIncludeDirsRules() []Rule {
67 // The list of paths that cannot be referenced using include_dirs
68 paths := []string{
69 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000070 "art/libnativebridge",
71 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010072 "libcore",
73 "libnativehelper",
74 "external/apache-harmony",
75 "external/apache-xml",
76 "external/boringssl",
77 "external/bouncycastle",
78 "external/conscrypt",
79 "external/icu",
80 "external/okhttp",
81 "external/vixl",
82 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010083 }
84
85 // Create a composite matcher that will match if the value starts with any of the restricted
86 // paths. A / is appended to the prefix to ensure that restricting path X does not affect paths
87 // XY.
88 rules := make([]Rule, 0, len(paths))
89 for _, path := range paths {
90 rule :=
91 NeverAllow().
92 WithMatcher("include_dirs", StartsWith(path+"/")).
93 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
94 " to use alternate mechanisms and so can no longer be used.")
95
96 rules = append(rules, rule)
97 }
98
99 return rules
100}
101
Paul Duffin730f2a52019-06-27 14:08:51 +0100102func createTrebleRules() []Rule {
103 return []Rule{
104 NeverAllow().
105 In("vendor", "device").
106 With("vndk.enabled", "true").
107 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900108 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100109 Because("the VNDK can never contain a library that is device dependent."),
110 NeverAllow().
111 With("vndk.enabled", "true").
112 Without("vendor", "true").
113 Without("owner", "").
114 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800115
Neil Fullerdf5f3562018-10-21 17:19:10 +0100116 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100117 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800118 Without("name", "libhidlbase-combined-impl").
119 Without("name", "libhidlbase").
120 Without("name", "libhidlbase_pgo").
Paul Duffin730f2a52019-06-27 14:08:51 +0100121 With("product_variables.enforce_vintf_manifest.cflags", "*").
122 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100123
124 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 NeverAllow().
126 Without("name", "libc_bionic_ndk").
127 With("product_variables.treble_linker_namespaces.cflags", "*").
128 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100129
130 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100131 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100132 }
133}
134
Paul Duffin730f2a52019-06-27 14:08:51 +0100135func createLibcoreRules() []Rule {
Neil Fullerdf5f3562018-10-21 17:19:10 +0100136 var coreLibraryProjects = []string{
137 "libcore",
138 "external/apache-harmony",
139 "external/apache-xml",
140 "external/bouncycastle",
141 "external/conscrypt",
142 "external/icu",
143 "external/okhttp",
144 "external/wycheproof",
Paul Duffine5c3b852020-05-12 15:27:56 +0100145 "prebuilts",
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146 }
147
Paul Duffina3d09862019-06-11 13:40:47 +0100148 // Core library constraints. The sdk_version: "none" can only be used in core library projects.
149 // Access to core library targets is restricted using visibility rules.
Paul Duffin730f2a52019-06-27 14:08:51 +0100150 rules := []Rule{
151 NeverAllow().
152 NotIn(coreLibraryProjects...).
Anton Hansson45376402020-04-09 14:18:21 +0100153 With("sdk_version", "none").
154 WithoutMatcher("name", Regexp("^android_.*stubs_current$")),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100155 }
156
Neil Fullerdf5f3562018-10-21 17:19:10 +0100157 return rules
Steven Moreland65b3fd92017-12-06 14:18:35 -0800158}
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160func createMediaRules() []Rule {
161 return []Rule{
162 NeverAllow().
163 With("libs", "updatable-media").
164 Because("updatable-media includes private APIs. Use updatable_media_stubs instead."),
Dongwon Kang50a299f2019-02-04 09:00:51 -0800165 }
166}
167
Paul Duffin730f2a52019-06-27 14:08:51 +0100168func createJavaDeviceForHostRules() []Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800169 javaDeviceForHostProjectsWhitelist := []string{
Colin Crossb5191a52019-04-11 14:07:38 -0700170 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800171 "external/robolectric-shadows",
172 "framework/layoutlib",
173 }
174
Paul Duffin730f2a52019-06-27 14:08:51 +0100175 return []Rule{
176 NeverAllow().
177 NotIn(javaDeviceForHostProjectsWhitelist...).
178 ModuleType("java_device_for_host", "java_host_for_device").
179 Because("java_device_for_host can only be used in whitelisted projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800180 }
181}
182
Colin Crossc511bc52020-04-07 16:50:32 +0000183func createCcSdkVariantRules() []Rule {
184 sdkVersionOnlyWhitelist := []string{
185 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
186 // This sometimes works because the APEX modules that contain derive_sdk and
187 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
188 // the APEX modules contain the SDK variant and the platform variant still exists.
189 "frameworks/base/apex/sdkextensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700190 // These are for apps and shouldn't be used by non-SDK variant modules.
191 "prebuilts/ndk",
192 "tools/test/graphicsbenchmark/apps/sample_app",
193 "tools/test/graphicsbenchmark/functional_tests/java",
Colin Crossc511bc52020-04-07 16:50:32 +0000194 }
195
196 platformVariantPropertiesWhitelist := []string{
197 // android_native_app_glue and libRSSupport use native_window.h but target old
198 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
199 // so they can't add libnativewindow to shared_libs to get the header directory
200 // for the platform variant. Allow them to use the platform variant
201 // property to set shared_libs.
202 "prebuilts/ndk",
203 "frameworks/rs",
204 }
205
206 return []Rule{
207 NeverAllow().
208 NotIn(sdkVersionOnlyWhitelist...).
209 WithMatcher("sdk_variant_only", isSetMatcherInstance).
210 Because("sdk_variant_only can only be used in whitelisted projects"),
211 NeverAllow().
212 NotIn(platformVariantPropertiesWhitelist...).
213 WithMatcher("platform.shared_libs", isSetMatcherInstance).
214 Because("platform variant properties can only be used in whitelisted projects"),
215 }
216}
217
David Srbeckye033cba2020-05-20 22:20:28 +0100218func createUncompressDexRules() []Rule {
219 return []Rule{
220 NeverAllow().
221 NotIn("art").
222 WithMatcher("uncompress_dex", isSetMatcherInstance).
223 Because("uncompress_dex is only allowed for certain jars for test in art."),
224 }
225}
226
Steven Moreland65b3fd92017-12-06 14:18:35 -0800227func neverallowMutator(ctx BottomUpMutatorContext) {
228 m, ok := ctx.Module().(Module)
229 if !ok {
230 return
231 }
232
233 dir := ctx.ModuleDir() + "/"
234 properties := m.GetProperties()
235
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100236 osClass := ctx.Module().Target().Os.Class
237
Paul Duffin115445b2019-08-07 15:31:07 +0100238 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100239 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800240 if !n.appliesToPath(dir) {
241 continue
242 }
243
Colin Crossfd4f7432019-03-05 15:06:16 -0800244 if !n.appliesToModuleType(ctx.ModuleType()) {
245 continue
246 }
247
Steven Moreland65b3fd92017-12-06 14:18:35 -0800248 if !n.appliesToProperties(properties) {
249 continue
250 }
251
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100252 if !n.appliesToOsClass(osClass) {
253 continue
254 }
255
Paul Duffin35781882019-07-25 15:41:09 +0100256 if !n.appliesToDirectDeps(ctx) {
257 continue
258 }
259
Steven Moreland65b3fd92017-12-06 14:18:35 -0800260 ctx.ModuleErrorf("violates " + n.String())
261 }
262}
263
Paul Duffin73bf0542019-07-12 14:12:49 +0100264type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100265 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100266 String() string
267}
268
269type equalMatcher struct {
270 expected string
271}
272
Artur Satayevc5570ac2020-04-09 16:06:36 +0100273func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100274 return m.expected == value
275}
276
277func (m *equalMatcher) String() string {
278 return "=" + m.expected
279}
280
281type anyMatcher struct {
282}
283
Artur Satayevc5570ac2020-04-09 16:06:36 +0100284func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100285 return true
286}
287
288func (m *anyMatcher) String() string {
289 return "=*"
290}
291
292var anyMatcherInstance = &anyMatcher{}
293
Paul Duffinc8111702019-07-22 12:13:55 +0100294type startsWithMatcher struct {
295 prefix string
296}
297
Artur Satayevc5570ac2020-04-09 16:06:36 +0100298func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100299 return strings.HasPrefix(value, m.prefix)
300}
301
302func (m *startsWithMatcher) String() string {
303 return ".starts-with(" + m.prefix + ")"
304}
305
Anton Hansson45376402020-04-09 14:18:21 +0100306type regexMatcher struct {
307 re *regexp.Regexp
308}
309
Artur Satayevc5570ac2020-04-09 16:06:36 +0100310func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100311 return m.re.MatchString(value)
312}
313
314func (m *regexMatcher) String() string {
315 return ".regexp(" + m.re.String() + ")"
316}
317
Colin Crossc511bc52020-04-07 16:50:32 +0000318type isSetMatcher struct{}
319
Artur Satayevc5570ac2020-04-09 16:06:36 +0100320func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000321 return value != ""
322}
323
324func (m *isSetMatcher) String() string {
325 return ".is-set"
326}
327
328var isSetMatcherInstance = &isSetMatcher{}
329
Steven Moreland65b3fd92017-12-06 14:18:35 -0800330type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100331 fields []string // e.x.: Vndk.Enabled
332 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800333}
334
Paul Duffin730f2a52019-06-27 14:08:51 +0100335// A NeverAllow rule.
336type Rule interface {
337 In(path ...string) Rule
338
339 NotIn(path ...string) Rule
340
Paul Duffin35781882019-07-25 15:41:09 +0100341 InDirectDeps(deps ...string) Rule
342
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100343 WithOsClass(osClasses ...OsClass) Rule
344
Paul Duffin730f2a52019-06-27 14:08:51 +0100345 ModuleType(types ...string) Rule
346
347 NotModuleType(types ...string) Rule
348
349 With(properties, value string) Rule
350
Paul Duffinc8111702019-07-22 12:13:55 +0100351 WithMatcher(properties string, matcher ValueMatcher) Rule
352
Paul Duffin730f2a52019-06-27 14:08:51 +0100353 Without(properties, value string) Rule
354
Paul Duffinc8111702019-07-22 12:13:55 +0100355 WithoutMatcher(properties string, matcher ValueMatcher) Rule
356
Paul Duffin730f2a52019-06-27 14:08:51 +0100357 Because(reason string) Rule
358}
359
Steven Moreland65b3fd92017-12-06 14:18:35 -0800360type rule struct {
361 // User string for why this is a thing.
362 reason string
363
364 paths []string
365 unlessPaths []string
366
Paul Duffin35781882019-07-25 15:41:09 +0100367 directDeps map[string]bool
368
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100369 osClasses []OsClass
370
Colin Crossfd4f7432019-03-05 15:06:16 -0800371 moduleTypes []string
372 unlessModuleTypes []string
373
Steven Moreland65b3fd92017-12-06 14:18:35 -0800374 props []ruleProperty
375 unlessProps []ruleProperty
376}
377
Paul Duffin730f2a52019-06-27 14:08:51 +0100378// Create a new NeverAllow rule.
379func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100380 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800381}
Colin Crossfd4f7432019-03-05 15:06:16 -0800382
Paul Duffin730f2a52019-06-27 14:08:51 +0100383func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800384 r.paths = append(r.paths, cleanPaths(path)...)
385 return r
386}
Colin Crossfd4f7432019-03-05 15:06:16 -0800387
Paul Duffin730f2a52019-06-27 14:08:51 +0100388func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800389 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
390 return r
391}
Colin Crossfd4f7432019-03-05 15:06:16 -0800392
Paul Duffin35781882019-07-25 15:41:09 +0100393func (r *rule) InDirectDeps(deps ...string) Rule {
394 for _, d := range deps {
395 r.directDeps[d] = true
396 }
397 return r
398}
399
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100400func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
401 r.osClasses = append(r.osClasses, osClasses...)
402 return r
403}
404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800406 r.moduleTypes = append(r.moduleTypes, types...)
407 return r
408}
409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800411 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
412 return r
413}
414
Paul Duffin730f2a52019-06-27 14:08:51 +0100415func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100416 return r.WithMatcher(properties, selectMatcher(value))
417}
418
419func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800420 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100421 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100422 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423 })
424 return r
425}
Colin Crossfd4f7432019-03-05 15:06:16 -0800426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100428 return r.WithoutMatcher(properties, selectMatcher(value))
429}
430
431func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800432 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100433 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100434 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800435 })
436 return r
437}
Colin Crossfd4f7432019-03-05 15:06:16 -0800438
Paul Duffin73bf0542019-07-12 14:12:49 +0100439func selectMatcher(expected string) ValueMatcher {
440 if expected == "*" {
441 return anyMatcherInstance
442 }
443 return &equalMatcher{expected: expected}
444}
445
Paul Duffin730f2a52019-06-27 14:08:51 +0100446func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447 r.reason = reason
448 return r
449}
450
451func (r *rule) String() string {
452 s := "neverallow"
453 for _, v := range r.paths {
454 s += " dir:" + v + "*"
455 }
456 for _, v := range r.unlessPaths {
457 s += " -dir:" + v + "*"
458 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800459 for _, v := range r.moduleTypes {
460 s += " type:" + v
461 }
462 for _, v := range r.unlessModuleTypes {
463 s += " -type:" + v
464 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800465 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100466 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800467 }
468 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100469 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470 }
Paul Duffin35781882019-07-25 15:41:09 +0100471 for k := range r.directDeps {
472 s += " deps:" + k
473 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100474 for _, v := range r.osClasses {
475 s += " os:" + v.String()
476 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800477 if len(r.reason) != 0 {
478 s += " which is restricted because " + r.reason
479 }
480 return s
481}
482
483func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800484 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
485 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486 return includePath && !excludePath
487}
488
Paul Duffin35781882019-07-25 15:41:09 +0100489func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
490 if len(r.directDeps) == 0 {
491 return true
492 }
493
494 matches := false
495 ctx.VisitDirectDeps(func(m Module) {
496 if !matches {
497 name := ctx.OtherModuleName(m)
498 matches = r.directDeps[name]
499 }
500 })
501
502 return matches
503}
504
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100505func (r *rule) appliesToOsClass(osClass OsClass) bool {
506 if len(r.osClasses) == 0 {
507 return true
508 }
509
510 for _, c := range r.osClasses {
511 if c == osClass {
512 return true
513 }
514 }
515
516 return false
517}
518
Colin Crossfd4f7432019-03-05 15:06:16 -0800519func (r *rule) appliesToModuleType(moduleType string) bool {
520 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
521}
522
Steven Moreland65b3fd92017-12-06 14:18:35 -0800523func (r *rule) appliesToProperties(properties []interface{}) bool {
524 includeProps := hasAllProperties(properties, r.props)
525 excludeProps := hasAnyProperty(properties, r.unlessProps)
526 return includeProps && !excludeProps
527}
528
Paul Duffinc8111702019-07-22 12:13:55 +0100529func StartsWith(prefix string) ValueMatcher {
530 return &startsWithMatcher{prefix}
531}
532
Anton Hansson45376402020-04-09 14:18:21 +0100533func Regexp(re string) ValueMatcher {
534 r, err := regexp.Compile(re)
535 if err != nil {
536 panic(err)
537 }
538 return &regexMatcher{r}
539}
540
Steven Moreland65b3fd92017-12-06 14:18:35 -0800541// assorted utils
542
543func cleanPaths(paths []string) []string {
544 res := make([]string, len(paths))
545 for i, v := range paths {
546 res[i] = filepath.Clean(v) + "/"
547 }
548 return res
549}
550
551func fieldNamesForProperties(propertyNames string) []string {
552 names := strings.Split(propertyNames, ".")
553 for i, v := range names {
554 names[i] = proptools.FieldNameForProperty(v)
555 }
556 return names
557}
558
Steven Moreland65b3fd92017-12-06 14:18:35 -0800559func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
560 for _, v := range props {
561 if hasProperty(properties, v) {
562 return true
563 }
564 }
565 return false
566}
567
568func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
569 for _, v := range props {
570 if !hasProperty(properties, v) {
571 return false
572 }
573 }
574 return true
575}
576
577func hasProperty(properties []interface{}, prop ruleProperty) bool {
578 for _, propertyStruct := range properties {
579 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
580 for _, v := range prop.fields {
581 if !propertiesValue.IsValid() {
582 break
583 }
584 propertiesValue = propertiesValue.FieldByName(v)
585 }
586 if !propertiesValue.IsValid() {
587 continue
588 }
589
Paul Duffin73bf0542019-07-12 14:12:49 +0100590 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100591 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800592 }
593
594 if matchValue(propertiesValue, check) {
595 return true
596 }
597 }
598 return false
599}
600
601func matchValue(value reflect.Value, check func(string) bool) bool {
602 if !value.IsValid() {
603 return false
604 }
605
606 if value.Kind() == reflect.Ptr {
607 if value.IsNil() {
608 return check("")
609 }
610 value = value.Elem()
611 }
612
613 switch value.Kind() {
614 case reflect.String:
615 return check(value.String())
616 case reflect.Bool:
617 return check(strconv.FormatBool(value.Bool()))
618 case reflect.Int:
619 return check(strconv.FormatInt(value.Int(), 10))
620 case reflect.Slice:
621 slice, ok := value.Interface().([]string)
622 if !ok {
623 panic("Can only handle slice of string")
624 }
625 for _, v := range slice {
626 if check(v) {
627 return true
628 }
629 }
630 return false
631 }
632
633 panic("Can't handle type: " + value.Kind().String())
634}
Paul Duffin115445b2019-08-07 15:31:07 +0100635
636var neverallowRulesKey = NewOnceKey("neverallowRules")
637
638func neverallowRules(config Config) []Rule {
639 return config.Once(neverallowRulesKey, func() interface{} {
640 // No test rules were set by setTestNeverallowRules, use the global rules
641 return neverallows
642 }).([]Rule)
643}
644
645// Overrides the default neverallow rules for the supplied config.
646//
647// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100648func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100649 config.Once(neverallowRulesKey, func() interface{} { return testRules })
650}