blob: a5e641ca55635a035b9ec1d4e93d879353f38c94 [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 Hanssonfec6c232020-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 Satayevb39ea9b2020-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 Cross01fd7cc2020-02-19 16:54:04 -080057 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbecky98c71222020-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 Yun98df0d12020-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 Duffincd9b6972020-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 Hanssonfec6c232020-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 Cross01fd7cc2020-02-19 16:54:04 -0800183func 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 Albert55576052020-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",
194 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Colin Cross01fd7cc2020-02-19 16:54:04 -0800195 }
196
197 platformVariantPropertiesWhitelist := []string{
198 // android_native_app_glue and libRSSupport use native_window.h but target old
199 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
200 // so they can't add libnativewindow to shared_libs to get the header directory
201 // for the platform variant. Allow them to use the platform variant
202 // property to set shared_libs.
203 "prebuilts/ndk",
204 "frameworks/rs",
205 }
206
207 return []Rule{
208 NeverAllow().
209 NotIn(sdkVersionOnlyWhitelist...).
210 WithMatcher("sdk_variant_only", isSetMatcherInstance).
211 Because("sdk_variant_only can only be used in whitelisted projects"),
212 NeverAllow().
213 NotIn(platformVariantPropertiesWhitelist...).
214 WithMatcher("platform.shared_libs", isSetMatcherInstance).
215 Because("platform variant properties can only be used in whitelisted projects"),
216 }
217}
218
David Srbecky98c71222020-05-20 22:20:28 +0100219func createUncompressDexRules() []Rule {
220 return []Rule{
221 NeverAllow().
222 NotIn("art").
223 WithMatcher("uncompress_dex", isSetMatcherInstance).
224 Because("uncompress_dex is only allowed for certain jars for test in art."),
225 }
226}
227
Steven Moreland65b3fd92017-12-06 14:18:35 -0800228func neverallowMutator(ctx BottomUpMutatorContext) {
229 m, ok := ctx.Module().(Module)
230 if !ok {
231 return
232 }
233
234 dir := ctx.ModuleDir() + "/"
235 properties := m.GetProperties()
236
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100237 osClass := ctx.Module().Target().Os.Class
238
Paul Duffin115445b2019-08-07 15:31:07 +0100239 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100240 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800241 if !n.appliesToPath(dir) {
242 continue
243 }
244
Colin Crossfd4f7432019-03-05 15:06:16 -0800245 if !n.appliesToModuleType(ctx.ModuleType()) {
246 continue
247 }
248
Steven Moreland65b3fd92017-12-06 14:18:35 -0800249 if !n.appliesToProperties(properties) {
250 continue
251 }
252
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100253 if !n.appliesToOsClass(osClass) {
254 continue
255 }
256
Paul Duffin35781882019-07-25 15:41:09 +0100257 if !n.appliesToDirectDeps(ctx) {
258 continue
259 }
260
Steven Moreland65b3fd92017-12-06 14:18:35 -0800261 ctx.ModuleErrorf("violates " + n.String())
262 }
263}
264
Paul Duffin73bf0542019-07-12 14:12:49 +0100265type ValueMatcher interface {
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100266 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100267 String() string
268}
269
270type equalMatcher struct {
271 expected string
272}
273
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100274func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100275 return m.expected == value
276}
277
278func (m *equalMatcher) String() string {
279 return "=" + m.expected
280}
281
282type anyMatcher struct {
283}
284
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100285func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100286 return true
287}
288
289func (m *anyMatcher) String() string {
290 return "=*"
291}
292
293var anyMatcherInstance = &anyMatcher{}
294
Paul Duffinc8111702019-07-22 12:13:55 +0100295type startsWithMatcher struct {
296 prefix string
297}
298
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100299func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100300 return strings.HasPrefix(value, m.prefix)
301}
302
303func (m *startsWithMatcher) String() string {
304 return ".starts-with(" + m.prefix + ")"
305}
306
Anton Hanssonfec6c232020-04-09 14:18:21 +0100307type regexMatcher struct {
308 re *regexp.Regexp
309}
310
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100311func (m *regexMatcher) Test(value string) bool {
Anton Hanssonfec6c232020-04-09 14:18:21 +0100312 return m.re.MatchString(value)
313}
314
315func (m *regexMatcher) String() string {
316 return ".regexp(" + m.re.String() + ")"
317}
318
Colin Cross01fd7cc2020-02-19 16:54:04 -0800319type isSetMatcher struct{}
320
321func (m *isSetMatcher) Test(value string) bool {
322 return value != ""
323}
324
325func (m *isSetMatcher) String() string {
326 return ".is-set"
327}
328
329var isSetMatcherInstance = &isSetMatcher{}
330
Steven Moreland65b3fd92017-12-06 14:18:35 -0800331type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100332 fields []string // e.x.: Vndk.Enabled
333 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800334}
335
Paul Duffin730f2a52019-06-27 14:08:51 +0100336// A NeverAllow rule.
337type Rule interface {
338 In(path ...string) Rule
339
340 NotIn(path ...string) Rule
341
Paul Duffin35781882019-07-25 15:41:09 +0100342 InDirectDeps(deps ...string) Rule
343
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100344 WithOsClass(osClasses ...OsClass) Rule
345
Paul Duffin730f2a52019-06-27 14:08:51 +0100346 ModuleType(types ...string) Rule
347
348 NotModuleType(types ...string) Rule
349
350 With(properties, value string) Rule
351
Paul Duffinc8111702019-07-22 12:13:55 +0100352 WithMatcher(properties string, matcher ValueMatcher) Rule
353
Paul Duffin730f2a52019-06-27 14:08:51 +0100354 Without(properties, value string) Rule
355
Paul Duffinc8111702019-07-22 12:13:55 +0100356 WithoutMatcher(properties string, matcher ValueMatcher) Rule
357
Paul Duffin730f2a52019-06-27 14:08:51 +0100358 Because(reason string) Rule
359}
360
Steven Moreland65b3fd92017-12-06 14:18:35 -0800361type rule struct {
362 // User string for why this is a thing.
363 reason string
364
365 paths []string
366 unlessPaths []string
367
Paul Duffin35781882019-07-25 15:41:09 +0100368 directDeps map[string]bool
369
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100370 osClasses []OsClass
371
Colin Crossfd4f7432019-03-05 15:06:16 -0800372 moduleTypes []string
373 unlessModuleTypes []string
374
Steven Moreland65b3fd92017-12-06 14:18:35 -0800375 props []ruleProperty
376 unlessProps []ruleProperty
377}
378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379// Create a new NeverAllow rule.
380func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100381 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800382}
Colin Crossfd4f7432019-03-05 15:06:16 -0800383
Paul Duffin730f2a52019-06-27 14:08:51 +0100384func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385 r.paths = append(r.paths, cleanPaths(path)...)
386 return r
387}
Colin Crossfd4f7432019-03-05 15:06:16 -0800388
Paul Duffin730f2a52019-06-27 14:08:51 +0100389func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800390 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
391 return r
392}
Colin Crossfd4f7432019-03-05 15:06:16 -0800393
Paul Duffin35781882019-07-25 15:41:09 +0100394func (r *rule) InDirectDeps(deps ...string) Rule {
395 for _, d := range deps {
396 r.directDeps[d] = true
397 }
398 return r
399}
400
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100401func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
402 r.osClasses = append(r.osClasses, osClasses...)
403 return r
404}
405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800407 r.moduleTypes = append(r.moduleTypes, types...)
408 return r
409}
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800412 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
413 return r
414}
415
Paul Duffin730f2a52019-06-27 14:08:51 +0100416func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100417 return r.WithMatcher(properties, selectMatcher(value))
418}
419
420func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800421 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100422 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100423 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800424 })
425 return r
426}
Colin Crossfd4f7432019-03-05 15:06:16 -0800427
Paul Duffin730f2a52019-06-27 14:08:51 +0100428func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100429 return r.WithoutMatcher(properties, selectMatcher(value))
430}
431
432func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800433 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100434 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100435 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800436 })
437 return r
438}
Colin Crossfd4f7432019-03-05 15:06:16 -0800439
Paul Duffin73bf0542019-07-12 14:12:49 +0100440func selectMatcher(expected string) ValueMatcher {
441 if expected == "*" {
442 return anyMatcherInstance
443 }
444 return &equalMatcher{expected: expected}
445}
446
Paul Duffin730f2a52019-06-27 14:08:51 +0100447func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800448 r.reason = reason
449 return r
450}
451
452func (r *rule) String() string {
453 s := "neverallow"
454 for _, v := range r.paths {
455 s += " dir:" + v + "*"
456 }
457 for _, v := range r.unlessPaths {
458 s += " -dir:" + v + "*"
459 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800460 for _, v := range r.moduleTypes {
461 s += " type:" + v
462 }
463 for _, v := range r.unlessModuleTypes {
464 s += " -type:" + v
465 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100467 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800468 }
469 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100470 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800471 }
Paul Duffin35781882019-07-25 15:41:09 +0100472 for k := range r.directDeps {
473 s += " deps:" + k
474 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100475 for _, v := range r.osClasses {
476 s += " os:" + v.String()
477 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800478 if len(r.reason) != 0 {
479 s += " which is restricted because " + r.reason
480 }
481 return s
482}
483
484func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800485 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
486 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487 return includePath && !excludePath
488}
489
Paul Duffin35781882019-07-25 15:41:09 +0100490func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
491 if len(r.directDeps) == 0 {
492 return true
493 }
494
495 matches := false
496 ctx.VisitDirectDeps(func(m Module) {
497 if !matches {
498 name := ctx.OtherModuleName(m)
499 matches = r.directDeps[name]
500 }
501 })
502
503 return matches
504}
505
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100506func (r *rule) appliesToOsClass(osClass OsClass) bool {
507 if len(r.osClasses) == 0 {
508 return true
509 }
510
511 for _, c := range r.osClasses {
512 if c == osClass {
513 return true
514 }
515 }
516
517 return false
518}
519
Colin Crossfd4f7432019-03-05 15:06:16 -0800520func (r *rule) appliesToModuleType(moduleType string) bool {
521 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
522}
523
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524func (r *rule) appliesToProperties(properties []interface{}) bool {
525 includeProps := hasAllProperties(properties, r.props)
526 excludeProps := hasAnyProperty(properties, r.unlessProps)
527 return includeProps && !excludeProps
528}
529
Paul Duffinc8111702019-07-22 12:13:55 +0100530func StartsWith(prefix string) ValueMatcher {
531 return &startsWithMatcher{prefix}
532}
533
Anton Hanssonfec6c232020-04-09 14:18:21 +0100534func Regexp(re string) ValueMatcher {
535 r, err := regexp.Compile(re)
536 if err != nil {
537 panic(err)
538 }
539 return &regexMatcher{r}
540}
541
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542// assorted utils
543
544func cleanPaths(paths []string) []string {
545 res := make([]string, len(paths))
546 for i, v := range paths {
547 res[i] = filepath.Clean(v) + "/"
548 }
549 return res
550}
551
552func fieldNamesForProperties(propertyNames string) []string {
553 names := strings.Split(propertyNames, ".")
554 for i, v := range names {
555 names[i] = proptools.FieldNameForProperty(v)
556 }
557 return names
558}
559
Steven Moreland65b3fd92017-12-06 14:18:35 -0800560func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
561 for _, v := range props {
562 if hasProperty(properties, v) {
563 return true
564 }
565 }
566 return false
567}
568
569func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
570 for _, v := range props {
571 if !hasProperty(properties, v) {
572 return false
573 }
574 }
575 return true
576}
577
578func hasProperty(properties []interface{}, prop ruleProperty) bool {
579 for _, propertyStruct := range properties {
580 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
581 for _, v := range prop.fields {
582 if !propertiesValue.IsValid() {
583 break
584 }
585 propertiesValue = propertiesValue.FieldByName(v)
586 }
587 if !propertiesValue.IsValid() {
588 continue
589 }
590
Paul Duffin73bf0542019-07-12 14:12:49 +0100591 check := func(value string) bool {
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100592 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800593 }
594
595 if matchValue(propertiesValue, check) {
596 return true
597 }
598 }
599 return false
600}
601
602func matchValue(value reflect.Value, check func(string) bool) bool {
603 if !value.IsValid() {
604 return false
605 }
606
607 if value.Kind() == reflect.Ptr {
608 if value.IsNil() {
609 return check("")
610 }
611 value = value.Elem()
612 }
613
614 switch value.Kind() {
615 case reflect.String:
616 return check(value.String())
617 case reflect.Bool:
618 return check(strconv.FormatBool(value.Bool()))
619 case reflect.Int:
620 return check(strconv.FormatInt(value.Int(), 10))
621 case reflect.Slice:
622 slice, ok := value.Interface().([]string)
623 if !ok {
624 panic("Can only handle slice of string")
625 }
626 for _, v := range slice {
627 if check(v) {
628 return true
629 }
630 }
631 return false
632 }
633
634 panic("Can't handle type: " + value.Kind().String())
635}
Paul Duffin115445b2019-08-07 15:31:07 +0100636
637var neverallowRulesKey = NewOnceKey("neverallowRules")
638
639func neverallowRules(config Config) []Rule {
640 return config.Once(neverallowRulesKey, func() interface{} {
641 // No test rules were set by setTestNeverallowRules, use the global rules
642 return neverallows
643 }).([]Rule)
644}
645
646// Overrides the default neverallow rules for the supplied config.
647//
648// For testing only.
Artur Satayevb39ea9b2020-04-09 16:06:36 +0100649func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100650 config.Once(neverallowRulesKey, func() interface{} { return testRules })
651}