blob: 9e075b719eeacbaeea19943365e21abf654413cf [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",
190 }
191
192 platformVariantPropertiesWhitelist := []string{
193 // android_native_app_glue and libRSSupport use native_window.h but target old
194 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
195 // so they can't add libnativewindow to shared_libs to get the header directory
196 // for the platform variant. Allow them to use the platform variant
197 // property to set shared_libs.
198 "prebuilts/ndk",
199 "frameworks/rs",
200 }
201
202 return []Rule{
203 NeverAllow().
204 NotIn(sdkVersionOnlyWhitelist...).
205 WithMatcher("sdk_variant_only", isSetMatcherInstance).
206 Because("sdk_variant_only can only be used in whitelisted projects"),
207 NeverAllow().
208 NotIn(platformVariantPropertiesWhitelist...).
209 WithMatcher("platform.shared_libs", isSetMatcherInstance).
210 Because("platform variant properties can only be used in whitelisted projects"),
211 }
212}
213
David Srbeckye033cba2020-05-20 22:20:28 +0100214func createUncompressDexRules() []Rule {
215 return []Rule{
216 NeverAllow().
217 NotIn("art").
218 WithMatcher("uncompress_dex", isSetMatcherInstance).
219 Because("uncompress_dex is only allowed for certain jars for test in art."),
220 }
221}
222
Steven Moreland65b3fd92017-12-06 14:18:35 -0800223func neverallowMutator(ctx BottomUpMutatorContext) {
224 m, ok := ctx.Module().(Module)
225 if !ok {
226 return
227 }
228
229 dir := ctx.ModuleDir() + "/"
230 properties := m.GetProperties()
231
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100232 osClass := ctx.Module().Target().Os.Class
233
Paul Duffin115445b2019-08-07 15:31:07 +0100234 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100235 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800236 if !n.appliesToPath(dir) {
237 continue
238 }
239
Colin Crossfd4f7432019-03-05 15:06:16 -0800240 if !n.appliesToModuleType(ctx.ModuleType()) {
241 continue
242 }
243
Steven Moreland65b3fd92017-12-06 14:18:35 -0800244 if !n.appliesToProperties(properties) {
245 continue
246 }
247
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100248 if !n.appliesToOsClass(osClass) {
249 continue
250 }
251
Paul Duffin35781882019-07-25 15:41:09 +0100252 if !n.appliesToDirectDeps(ctx) {
253 continue
254 }
255
Steven Moreland65b3fd92017-12-06 14:18:35 -0800256 ctx.ModuleErrorf("violates " + n.String())
257 }
258}
259
Paul Duffin73bf0542019-07-12 14:12:49 +0100260type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100261 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100262 String() string
263}
264
265type equalMatcher struct {
266 expected string
267}
268
Artur Satayevc5570ac2020-04-09 16:06:36 +0100269func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100270 return m.expected == value
271}
272
273func (m *equalMatcher) String() string {
274 return "=" + m.expected
275}
276
277type anyMatcher struct {
278}
279
Artur Satayevc5570ac2020-04-09 16:06:36 +0100280func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100281 return true
282}
283
284func (m *anyMatcher) String() string {
285 return "=*"
286}
287
288var anyMatcherInstance = &anyMatcher{}
289
Paul Duffinc8111702019-07-22 12:13:55 +0100290type startsWithMatcher struct {
291 prefix string
292}
293
Artur Satayevc5570ac2020-04-09 16:06:36 +0100294func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100295 return strings.HasPrefix(value, m.prefix)
296}
297
298func (m *startsWithMatcher) String() string {
299 return ".starts-with(" + m.prefix + ")"
300}
301
Anton Hansson45376402020-04-09 14:18:21 +0100302type regexMatcher struct {
303 re *regexp.Regexp
304}
305
Artur Satayevc5570ac2020-04-09 16:06:36 +0100306func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100307 return m.re.MatchString(value)
308}
309
310func (m *regexMatcher) String() string {
311 return ".regexp(" + m.re.String() + ")"
312}
313
Colin Crossc511bc52020-04-07 16:50:32 +0000314type isSetMatcher struct{}
315
Artur Satayevc5570ac2020-04-09 16:06:36 +0100316func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000317 return value != ""
318}
319
320func (m *isSetMatcher) String() string {
321 return ".is-set"
322}
323
324var isSetMatcherInstance = &isSetMatcher{}
325
Steven Moreland65b3fd92017-12-06 14:18:35 -0800326type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100327 fields []string // e.x.: Vndk.Enabled
328 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800329}
330
Paul Duffin730f2a52019-06-27 14:08:51 +0100331// A NeverAllow rule.
332type Rule interface {
333 In(path ...string) Rule
334
335 NotIn(path ...string) Rule
336
Paul Duffin35781882019-07-25 15:41:09 +0100337 InDirectDeps(deps ...string) Rule
338
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100339 WithOsClass(osClasses ...OsClass) Rule
340
Paul Duffin730f2a52019-06-27 14:08:51 +0100341 ModuleType(types ...string) Rule
342
343 NotModuleType(types ...string) Rule
344
345 With(properties, value string) Rule
346
Paul Duffinc8111702019-07-22 12:13:55 +0100347 WithMatcher(properties string, matcher ValueMatcher) Rule
348
Paul Duffin730f2a52019-06-27 14:08:51 +0100349 Without(properties, value string) Rule
350
Paul Duffinc8111702019-07-22 12:13:55 +0100351 WithoutMatcher(properties string, matcher ValueMatcher) Rule
352
Paul Duffin730f2a52019-06-27 14:08:51 +0100353 Because(reason string) Rule
354}
355
Steven Moreland65b3fd92017-12-06 14:18:35 -0800356type rule struct {
357 // User string for why this is a thing.
358 reason string
359
360 paths []string
361 unlessPaths []string
362
Paul Duffin35781882019-07-25 15:41:09 +0100363 directDeps map[string]bool
364
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100365 osClasses []OsClass
366
Colin Crossfd4f7432019-03-05 15:06:16 -0800367 moduleTypes []string
368 unlessModuleTypes []string
369
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370 props []ruleProperty
371 unlessProps []ruleProperty
372}
373
Paul Duffin730f2a52019-06-27 14:08:51 +0100374// Create a new NeverAllow rule.
375func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100376 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800377}
Colin Crossfd4f7432019-03-05 15:06:16 -0800378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800380 r.paths = append(r.paths, cleanPaths(path)...)
381 return r
382}
Colin Crossfd4f7432019-03-05 15:06:16 -0800383
Paul Duffin730f2a52019-06-27 14:08:51 +0100384func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
386 return r
387}
Colin Crossfd4f7432019-03-05 15:06:16 -0800388
Paul Duffin35781882019-07-25 15:41:09 +0100389func (r *rule) InDirectDeps(deps ...string) Rule {
390 for _, d := range deps {
391 r.directDeps[d] = true
392 }
393 return r
394}
395
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100396func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
397 r.osClasses = append(r.osClasses, osClasses...)
398 return r
399}
400
Paul Duffin730f2a52019-06-27 14:08:51 +0100401func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800402 r.moduleTypes = append(r.moduleTypes, types...)
403 return r
404}
405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800407 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
408 return r
409}
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100412 return r.WithMatcher(properties, selectMatcher(value))
413}
414
415func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800416 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100417 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100418 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419 })
420 return r
421}
Colin Crossfd4f7432019-03-05 15:06:16 -0800422
Paul Duffin730f2a52019-06-27 14:08:51 +0100423func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100424 return r.WithoutMatcher(properties, selectMatcher(value))
425}
426
427func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100429 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100430 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800431 })
432 return r
433}
Colin Crossfd4f7432019-03-05 15:06:16 -0800434
Paul Duffin73bf0542019-07-12 14:12:49 +0100435func selectMatcher(expected string) ValueMatcher {
436 if expected == "*" {
437 return anyMatcherInstance
438 }
439 return &equalMatcher{expected: expected}
440}
441
Paul Duffin730f2a52019-06-27 14:08:51 +0100442func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800443 r.reason = reason
444 return r
445}
446
447func (r *rule) String() string {
448 s := "neverallow"
449 for _, v := range r.paths {
450 s += " dir:" + v + "*"
451 }
452 for _, v := range r.unlessPaths {
453 s += " -dir:" + v + "*"
454 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800455 for _, v := range r.moduleTypes {
456 s += " type:" + v
457 }
458 for _, v := range r.unlessModuleTypes {
459 s += " -type:" + v
460 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800461 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100462 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463 }
464 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100465 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466 }
Paul Duffin35781882019-07-25 15:41:09 +0100467 for k := range r.directDeps {
468 s += " deps:" + k
469 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100470 for _, v := range r.osClasses {
471 s += " os:" + v.String()
472 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800473 if len(r.reason) != 0 {
474 s += " which is restricted because " + r.reason
475 }
476 return s
477}
478
479func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800480 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
481 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800482 return includePath && !excludePath
483}
484
Paul Duffin35781882019-07-25 15:41:09 +0100485func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
486 if len(r.directDeps) == 0 {
487 return true
488 }
489
490 matches := false
491 ctx.VisitDirectDeps(func(m Module) {
492 if !matches {
493 name := ctx.OtherModuleName(m)
494 matches = r.directDeps[name]
495 }
496 })
497
498 return matches
499}
500
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100501func (r *rule) appliesToOsClass(osClass OsClass) bool {
502 if len(r.osClasses) == 0 {
503 return true
504 }
505
506 for _, c := range r.osClasses {
507 if c == osClass {
508 return true
509 }
510 }
511
512 return false
513}
514
Colin Crossfd4f7432019-03-05 15:06:16 -0800515func (r *rule) appliesToModuleType(moduleType string) bool {
516 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
517}
518
Steven Moreland65b3fd92017-12-06 14:18:35 -0800519func (r *rule) appliesToProperties(properties []interface{}) bool {
520 includeProps := hasAllProperties(properties, r.props)
521 excludeProps := hasAnyProperty(properties, r.unlessProps)
522 return includeProps && !excludeProps
523}
524
Paul Duffinc8111702019-07-22 12:13:55 +0100525func StartsWith(prefix string) ValueMatcher {
526 return &startsWithMatcher{prefix}
527}
528
Anton Hansson45376402020-04-09 14:18:21 +0100529func Regexp(re string) ValueMatcher {
530 r, err := regexp.Compile(re)
531 if err != nil {
532 panic(err)
533 }
534 return &regexMatcher{r}
535}
536
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537// assorted utils
538
539func cleanPaths(paths []string) []string {
540 res := make([]string, len(paths))
541 for i, v := range paths {
542 res[i] = filepath.Clean(v) + "/"
543 }
544 return res
545}
546
547func fieldNamesForProperties(propertyNames string) []string {
548 names := strings.Split(propertyNames, ".")
549 for i, v := range names {
550 names[i] = proptools.FieldNameForProperty(v)
551 }
552 return names
553}
554
Steven Moreland65b3fd92017-12-06 14:18:35 -0800555func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
556 for _, v := range props {
557 if hasProperty(properties, v) {
558 return true
559 }
560 }
561 return false
562}
563
564func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
565 for _, v := range props {
566 if !hasProperty(properties, v) {
567 return false
568 }
569 }
570 return true
571}
572
573func hasProperty(properties []interface{}, prop ruleProperty) bool {
574 for _, propertyStruct := range properties {
575 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
576 for _, v := range prop.fields {
577 if !propertiesValue.IsValid() {
578 break
579 }
580 propertiesValue = propertiesValue.FieldByName(v)
581 }
582 if !propertiesValue.IsValid() {
583 continue
584 }
585
Paul Duffin73bf0542019-07-12 14:12:49 +0100586 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100587 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800588 }
589
590 if matchValue(propertiesValue, check) {
591 return true
592 }
593 }
594 return false
595}
596
597func matchValue(value reflect.Value, check func(string) bool) bool {
598 if !value.IsValid() {
599 return false
600 }
601
602 if value.Kind() == reflect.Ptr {
603 if value.IsNil() {
604 return check("")
605 }
606 value = value.Elem()
607 }
608
609 switch value.Kind() {
610 case reflect.String:
611 return check(value.String())
612 case reflect.Bool:
613 return check(strconv.FormatBool(value.Bool()))
614 case reflect.Int:
615 return check(strconv.FormatInt(value.Int(), 10))
616 case reflect.Slice:
617 slice, ok := value.Interface().([]string)
618 if !ok {
619 panic("Can only handle slice of string")
620 }
621 for _, v := range slice {
622 if check(v) {
623 return true
624 }
625 }
626 return false
627 }
628
629 panic("Can't handle type: " + value.Kind().String())
630}
Paul Duffin115445b2019-08-07 15:31:07 +0100631
632var neverallowRulesKey = NewOnceKey("neverallowRules")
633
634func neverallowRules(config Config) []Rule {
635 return config.Once(neverallowRulesKey, func() interface{} {
636 // No test rules were set by setTestNeverallowRules, use the global rules
637 return neverallows
638 }).([]Rule)
639}
640
641// Overrides the default neverallow rules for the supplied config.
642//
643// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100644func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100645 config.Once(neverallowRulesKey, func() interface{} { return testRules })
646}