blob: f9fc03caa34a9b4fde79033962818fc0c926d586 [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",
189 }
190
191 platformVariantPropertiesWhitelist := []string{
192 // android_native_app_glue and libRSSupport use native_window.h but target old
193 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
194 // so they can't add libnativewindow to shared_libs to get the header directory
195 // for the platform variant. Allow them to use the platform variant
196 // property to set shared_libs.
197 "prebuilts/ndk",
198 "frameworks/rs",
199 }
200
201 return []Rule{
202 NeverAllow().
203 NotIn(sdkVersionOnlyWhitelist...).
204 WithMatcher("sdk_variant_only", isSetMatcherInstance).
205 Because("sdk_variant_only can only be used in whitelisted projects"),
206 NeverAllow().
207 NotIn(platformVariantPropertiesWhitelist...).
208 WithMatcher("platform.shared_libs", isSetMatcherInstance).
209 Because("platform variant properties can only be used in whitelisted projects"),
210 }
211}
212
Steven Moreland65b3fd92017-12-06 14:18:35 -0800213func neverallowMutator(ctx BottomUpMutatorContext) {
214 m, ok := ctx.Module().(Module)
215 if !ok {
216 return
217 }
218
219 dir := ctx.ModuleDir() + "/"
220 properties := m.GetProperties()
221
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100222 osClass := ctx.Module().Target().Os.Class
223
Paul Duffin115445b2019-08-07 15:31:07 +0100224 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100225 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800226 if !n.appliesToPath(dir) {
227 continue
228 }
229
Colin Crossfd4f7432019-03-05 15:06:16 -0800230 if !n.appliesToModuleType(ctx.ModuleType()) {
231 continue
232 }
233
Steven Moreland65b3fd92017-12-06 14:18:35 -0800234 if !n.appliesToProperties(properties) {
235 continue
236 }
237
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100238 if !n.appliesToOsClass(osClass) {
239 continue
240 }
241
Paul Duffin35781882019-07-25 15:41:09 +0100242 if !n.appliesToDirectDeps(ctx) {
243 continue
244 }
245
Steven Moreland65b3fd92017-12-06 14:18:35 -0800246 ctx.ModuleErrorf("violates " + n.String())
247 }
248}
249
Paul Duffin73bf0542019-07-12 14:12:49 +0100250type ValueMatcher interface {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100251 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100252 String() string
253}
254
255type equalMatcher struct {
256 expected string
257}
258
Artur Satayevc5570ac2020-04-09 16:06:36 +0100259func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100260 return m.expected == value
261}
262
263func (m *equalMatcher) String() string {
264 return "=" + m.expected
265}
266
267type anyMatcher struct {
268}
269
Artur Satayevc5570ac2020-04-09 16:06:36 +0100270func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100271 return true
272}
273
274func (m *anyMatcher) String() string {
275 return "=*"
276}
277
278var anyMatcherInstance = &anyMatcher{}
279
Paul Duffinc8111702019-07-22 12:13:55 +0100280type startsWithMatcher struct {
281 prefix string
282}
283
Artur Satayevc5570ac2020-04-09 16:06:36 +0100284func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100285 return strings.HasPrefix(value, m.prefix)
286}
287
288func (m *startsWithMatcher) String() string {
289 return ".starts-with(" + m.prefix + ")"
290}
291
Anton Hansson45376402020-04-09 14:18:21 +0100292type regexMatcher struct {
293 re *regexp.Regexp
294}
295
Artur Satayevc5570ac2020-04-09 16:06:36 +0100296func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100297 return m.re.MatchString(value)
298}
299
300func (m *regexMatcher) String() string {
301 return ".regexp(" + m.re.String() + ")"
302}
303
Colin Crossc511bc52020-04-07 16:50:32 +0000304type isSetMatcher struct{}
305
Artur Satayevc5570ac2020-04-09 16:06:36 +0100306func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000307 return value != ""
308}
309
310func (m *isSetMatcher) String() string {
311 return ".is-set"
312}
313
314var isSetMatcherInstance = &isSetMatcher{}
315
Steven Moreland65b3fd92017-12-06 14:18:35 -0800316type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100317 fields []string // e.x.: Vndk.Enabled
318 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800319}
320
Paul Duffin730f2a52019-06-27 14:08:51 +0100321// A NeverAllow rule.
322type Rule interface {
323 In(path ...string) Rule
324
325 NotIn(path ...string) Rule
326
Paul Duffin35781882019-07-25 15:41:09 +0100327 InDirectDeps(deps ...string) Rule
328
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100329 WithOsClass(osClasses ...OsClass) Rule
330
Paul Duffin730f2a52019-06-27 14:08:51 +0100331 ModuleType(types ...string) Rule
332
333 NotModuleType(types ...string) Rule
334
335 With(properties, value string) Rule
336
Paul Duffinc8111702019-07-22 12:13:55 +0100337 WithMatcher(properties string, matcher ValueMatcher) Rule
338
Paul Duffin730f2a52019-06-27 14:08:51 +0100339 Without(properties, value string) Rule
340
Paul Duffinc8111702019-07-22 12:13:55 +0100341 WithoutMatcher(properties string, matcher ValueMatcher) Rule
342
Paul Duffin730f2a52019-06-27 14:08:51 +0100343 Because(reason string) Rule
344}
345
Steven Moreland65b3fd92017-12-06 14:18:35 -0800346type rule struct {
347 // User string for why this is a thing.
348 reason string
349
350 paths []string
351 unlessPaths []string
352
Paul Duffin35781882019-07-25 15:41:09 +0100353 directDeps map[string]bool
354
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100355 osClasses []OsClass
356
Colin Crossfd4f7432019-03-05 15:06:16 -0800357 moduleTypes []string
358 unlessModuleTypes []string
359
Steven Moreland65b3fd92017-12-06 14:18:35 -0800360 props []ruleProperty
361 unlessProps []ruleProperty
362}
363
Paul Duffin730f2a52019-06-27 14:08:51 +0100364// Create a new NeverAllow rule.
365func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100366 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800367}
Colin Crossfd4f7432019-03-05 15:06:16 -0800368
Paul Duffin730f2a52019-06-27 14:08:51 +0100369func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370 r.paths = append(r.paths, cleanPaths(path)...)
371 return r
372}
Colin Crossfd4f7432019-03-05 15:06:16 -0800373
Paul Duffin730f2a52019-06-27 14:08:51 +0100374func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800375 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
376 return r
377}
Colin Crossfd4f7432019-03-05 15:06:16 -0800378
Paul Duffin35781882019-07-25 15:41:09 +0100379func (r *rule) InDirectDeps(deps ...string) Rule {
380 for _, d := range deps {
381 r.directDeps[d] = true
382 }
383 return r
384}
385
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100386func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
387 r.osClasses = append(r.osClasses, osClasses...)
388 return r
389}
390
Paul Duffin730f2a52019-06-27 14:08:51 +0100391func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800392 r.moduleTypes = append(r.moduleTypes, types...)
393 return r
394}
395
Paul Duffin730f2a52019-06-27 14:08:51 +0100396func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800397 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
398 return r
399}
400
Paul Duffin730f2a52019-06-27 14:08:51 +0100401func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100402 return r.WithMatcher(properties, selectMatcher(value))
403}
404
405func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800406 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100407 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100408 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800409 })
410 return r
411}
Colin Crossfd4f7432019-03-05 15:06:16 -0800412
Paul Duffin730f2a52019-06-27 14:08:51 +0100413func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100414 return r.WithoutMatcher(properties, selectMatcher(value))
415}
416
417func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800418 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100419 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100420 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800421 })
422 return r
423}
Colin Crossfd4f7432019-03-05 15:06:16 -0800424
Paul Duffin73bf0542019-07-12 14:12:49 +0100425func selectMatcher(expected string) ValueMatcher {
426 if expected == "*" {
427 return anyMatcherInstance
428 }
429 return &equalMatcher{expected: expected}
430}
431
Paul Duffin730f2a52019-06-27 14:08:51 +0100432func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800433 r.reason = reason
434 return r
435}
436
437func (r *rule) String() string {
438 s := "neverallow"
439 for _, v := range r.paths {
440 s += " dir:" + v + "*"
441 }
442 for _, v := range r.unlessPaths {
443 s += " -dir:" + v + "*"
444 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800445 for _, v := range r.moduleTypes {
446 s += " type:" + v
447 }
448 for _, v := range r.unlessModuleTypes {
449 s += " -type:" + v
450 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800451 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100452 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800453 }
454 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100455 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800456 }
Paul Duffin35781882019-07-25 15:41:09 +0100457 for k := range r.directDeps {
458 s += " deps:" + k
459 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100460 for _, v := range r.osClasses {
461 s += " os:" + v.String()
462 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463 if len(r.reason) != 0 {
464 s += " which is restricted because " + r.reason
465 }
466 return s
467}
468
469func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800470 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
471 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800472 return includePath && !excludePath
473}
474
Paul Duffin35781882019-07-25 15:41:09 +0100475func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
476 if len(r.directDeps) == 0 {
477 return true
478 }
479
480 matches := false
481 ctx.VisitDirectDeps(func(m Module) {
482 if !matches {
483 name := ctx.OtherModuleName(m)
484 matches = r.directDeps[name]
485 }
486 })
487
488 return matches
489}
490
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100491func (r *rule) appliesToOsClass(osClass OsClass) bool {
492 if len(r.osClasses) == 0 {
493 return true
494 }
495
496 for _, c := range r.osClasses {
497 if c == osClass {
498 return true
499 }
500 }
501
502 return false
503}
504
Colin Crossfd4f7432019-03-05 15:06:16 -0800505func (r *rule) appliesToModuleType(moduleType string) bool {
506 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
507}
508
Steven Moreland65b3fd92017-12-06 14:18:35 -0800509func (r *rule) appliesToProperties(properties []interface{}) bool {
510 includeProps := hasAllProperties(properties, r.props)
511 excludeProps := hasAnyProperty(properties, r.unlessProps)
512 return includeProps && !excludeProps
513}
514
Paul Duffinc8111702019-07-22 12:13:55 +0100515func StartsWith(prefix string) ValueMatcher {
516 return &startsWithMatcher{prefix}
517}
518
Anton Hansson45376402020-04-09 14:18:21 +0100519func Regexp(re string) ValueMatcher {
520 r, err := regexp.Compile(re)
521 if err != nil {
522 panic(err)
523 }
524 return &regexMatcher{r}
525}
526
Steven Moreland65b3fd92017-12-06 14:18:35 -0800527// assorted utils
528
529func cleanPaths(paths []string) []string {
530 res := make([]string, len(paths))
531 for i, v := range paths {
532 res[i] = filepath.Clean(v) + "/"
533 }
534 return res
535}
536
537func fieldNamesForProperties(propertyNames string) []string {
538 names := strings.Split(propertyNames, ".")
539 for i, v := range names {
540 names[i] = proptools.FieldNameForProperty(v)
541 }
542 return names
543}
544
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
546 for _, v := range props {
547 if hasProperty(properties, v) {
548 return true
549 }
550 }
551 return false
552}
553
554func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
555 for _, v := range props {
556 if !hasProperty(properties, v) {
557 return false
558 }
559 }
560 return true
561}
562
563func hasProperty(properties []interface{}, prop ruleProperty) bool {
564 for _, propertyStruct := range properties {
565 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
566 for _, v := range prop.fields {
567 if !propertiesValue.IsValid() {
568 break
569 }
570 propertiesValue = propertiesValue.FieldByName(v)
571 }
572 if !propertiesValue.IsValid() {
573 continue
574 }
575
Paul Duffin73bf0542019-07-12 14:12:49 +0100576 check := func(value string) bool {
Artur Satayevc5570ac2020-04-09 16:06:36 +0100577 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800578 }
579
580 if matchValue(propertiesValue, check) {
581 return true
582 }
583 }
584 return false
585}
586
587func matchValue(value reflect.Value, check func(string) bool) bool {
588 if !value.IsValid() {
589 return false
590 }
591
592 if value.Kind() == reflect.Ptr {
593 if value.IsNil() {
594 return check("")
595 }
596 value = value.Elem()
597 }
598
599 switch value.Kind() {
600 case reflect.String:
601 return check(value.String())
602 case reflect.Bool:
603 return check(strconv.FormatBool(value.Bool()))
604 case reflect.Int:
605 return check(strconv.FormatInt(value.Int(), 10))
606 case reflect.Slice:
607 slice, ok := value.Interface().([]string)
608 if !ok {
609 panic("Can only handle slice of string")
610 }
611 for _, v := range slice {
612 if check(v) {
613 return true
614 }
615 }
616 return false
617 }
618
619 panic("Can't handle type: " + value.Kind().String())
620}
Paul Duffin115445b2019-08-07 15:31:07 +0100621
622var neverallowRulesKey = NewOnceKey("neverallowRules")
623
624func neverallowRules(config Config) []Rule {
625 return config.Once(neverallowRulesKey, func() interface{} {
626 // No test rules were set by setTestNeverallowRules, use the global rules
627 return neverallows
628 }).([]Rule)
629}
630
631// Overrides the default neverallow rules for the supplied config.
632//
633// For testing only.
Artur Satayevc5570ac2020-04-09 16:06:36 +0100634func SetTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100635 config.Once(neverallowRulesKey, func() interface{} { return testRules })
636}