blob: aa47bcaebc5e70745b6eba24b2725d31139d2912 [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 (
Liz Kammera3d79152021-10-28 18:14:04 -040018 "fmt"
Steven Moreland65b3fd92017-12-06 14:18:35 -080019 "path/filepath"
20 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010021 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080022 "strconv"
23 "strings"
24
25 "github.com/google/blueprint/proptools"
26)
27
28// "neverallow" rules for the build system.
29//
30// This allows things which aren't related to the build system and are enforced
Joe Onoratob4638c12021-10-27 15:47:06 -070031// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080032// straightforward away disjoint from implementations and tests which should
33// work regardless of these restrictions.
34//
35// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010036// - it is in one of the "In" paths
37// - it is not in one of the "NotIn" paths
38// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080039// - - values are matched in their entirety
40// - - nil is interpreted as an empty string
41// - - nested properties are separated with a '.'
42// - - if the property is a list, any of the values in the list being matches
43// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010044// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080045
Paul Duffin45338f02021-03-30 23:07:52 +010046func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080047 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
48}
49
Paul Duffin730f2a52019-06-27 14:08:51 +010050var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080051
Paul Duffin730f2a52019-06-27 14:08:51 +010052func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010053 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010055 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000056 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010057 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070058 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090059 AddNeverAllowRules(createInitFirstStageRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090060 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010061}
Steven Moreland65b3fd92017-12-06 14:18:35 -080062
Paul Duffin730f2a52019-06-27 14:08:51 +010063// Add a NeverAllow rule to the set of rules to apply.
64func AddNeverAllowRules(rules ...Rule) {
65 neverallows = append(neverallows, rules...)
66}
67
Paul Duffinc8111702019-07-22 12:13:55 +010068func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000069 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010070 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000071 "art/libnativebridge",
72 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010073 "libcore",
74 "libnativehelper",
75 "external/apache-harmony",
76 "external/apache-xml",
77 "external/boringssl",
78 "external/bouncycastle",
79 "external/conscrypt",
80 "external/icu",
81 "external/okhttp",
82 "external/vixl",
83 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010084 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000085 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000086 "frameworks/av/apex",
87 "frameworks/av/tools",
88 "frameworks/native/cmds",
89 "system/apex",
90 "system/bpf",
91 "system/gatekeeper",
92 "system/hwservicemanager",
93 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000094 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000095 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 }
Paul Duffinc8111702019-07-22 12:13:55 +010097
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
99
100 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100101 rule :=
102 NeverAllow().
103 WithMatcher("include_dirs", StartsWith(path+"/")).
104 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
105 " to use alternate mechanisms and so can no longer be used.")
106
107 rules = append(rules, rule)
108 }
109
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000110 for _, path := range noUseIncludeDir {
111 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
112 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
113 " to use alternate mechanisms and so can no longer be used.")
114 rules = append(rules, rule)
115 }
116
Paul Duffinc8111702019-07-22 12:13:55 +0100117 return rules
118}
119
Paul Duffin730f2a52019-06-27 14:08:51 +0100120func createTrebleRules() []Rule {
121 return []Rule{
122 NeverAllow().
123 In("vendor", "device").
124 With("vndk.enabled", "true").
125 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900126 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100127 Because("the VNDK can never contain a library that is device dependent."),
128 NeverAllow().
129 With("vndk.enabled", "true").
130 Without("vendor", "true").
131 Without("owner", "").
132 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800133
Neil Fullerdf5f3562018-10-21 17:19:10 +0100134 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100135 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800136 Without("name", "libhidlbase-combined-impl").
137 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100138 With("product_variables.enforce_vintf_manifest.cflags", "*").
139 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100140
141 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100142 NeverAllow().
143 Without("name", "libc_bionic_ndk").
144 With("product_variables.treble_linker_namespaces.cflags", "*").
145 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146
147 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100148 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100149 }
150}
151
Paul Duffin730f2a52019-06-27 14:08:51 +0100152func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700153 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700154 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700155 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800156 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000157 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800158 }
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 return []Rule{
161 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700162 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100163 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700164 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800165 }
166}
167
Colin Crossc511bc52020-04-07 16:50:32 +0000168func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700169 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000170 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
171 // This sometimes works because the APEX modules that contain derive_sdk and
172 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
173 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100174 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700175 // These are for apps and shouldn't be used by non-SDK variant modules.
176 "prebuilts/ndk",
177 "tools/test/graphicsbenchmark/apps/sample_app",
178 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700179 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000180 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000181 }
182
Colin Cross440e0d02020-06-11 11:32:11 -0700183 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000184 // android_native_app_glue and libRSSupport use native_window.h but target old
185 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
186 // so they can't add libnativewindow to shared_libs to get the header directory
187 // for the platform variant. Allow them to use the platform variant
188 // property to set shared_libs.
189 "prebuilts/ndk",
190 "frameworks/rs",
191 }
192
193 return []Rule{
194 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700195 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000196 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700197 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000198 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700199 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000200 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700201 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000202 }
203}
204
David Srbeckye033cba2020-05-20 22:20:28 +0100205func createUncompressDexRules() []Rule {
206 return []Rule{
207 NeverAllow().
208 NotIn("art").
209 WithMatcher("uncompress_dex", isSetMatcherInstance).
210 Because("uncompress_dex is only allowed for certain jars for test in art."),
211 }
212}
213
Yifan Hong696ed4d2020-07-27 12:59:58 -0700214func createMakefileGoalRules() []Rule {
215 return []Rule{
216 NeverAllow().
217 ModuleType("makefile_goal").
218 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Inseob Kima9078742021-12-29 08:59:00 +0000219 Because("Only boot images may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700220 }
221}
222
Inseob Kim800d1142021-06-14 12:03:51 +0900223func createInitFirstStageRules() []Rule {
224 return []Rule{
225 NeverAllow().
226 Without("name", "init_first_stage").
227 With("install_in_root", "true").
228 Because("install_in_root is only for init_first_stage."),
229 }
230}
231
Jiyong Park3c306f32022-04-05 15:29:53 +0900232func createProhibitFrameworkAccessRules() []Rule {
233 return []Rule{
234 NeverAllow().
235 With("libs", "framework").
236 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
237 Because("framework can't be used when building against SDK"),
238 }
239}
240
Steven Moreland65b3fd92017-12-06 14:18:35 -0800241func neverallowMutator(ctx BottomUpMutatorContext) {
242 m, ok := ctx.Module().(Module)
243 if !ok {
244 return
245 }
246
247 dir := ctx.ModuleDir() + "/"
248 properties := m.GetProperties()
249
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100250 osClass := ctx.Module().Target().Os.Class
251
Paul Duffin115445b2019-08-07 15:31:07 +0100252 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100253 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800254 if !n.appliesToPath(dir) {
255 continue
256 }
257
Colin Crossfd4f7432019-03-05 15:06:16 -0800258 if !n.appliesToModuleType(ctx.ModuleType()) {
259 continue
260 }
261
Anton Hanssone1b18362021-12-23 15:05:38 +0000262 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800263 continue
264 }
265
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100266 if !n.appliesToOsClass(osClass) {
267 continue
268 }
269
Paul Duffin35781882019-07-25 15:41:09 +0100270 if !n.appliesToDirectDeps(ctx) {
271 continue
272 }
273
Steven Moreland65b3fd92017-12-06 14:18:35 -0800274 ctx.ModuleErrorf("violates " + n.String())
275 }
276}
277
Paul Duffin73bf0542019-07-12 14:12:49 +0100278type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000279 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100280 String() string
281}
282
283type equalMatcher struct {
284 expected string
285}
286
Anton Hanssone1b18362021-12-23 15:05:38 +0000287func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100288 return m.expected == value
289}
290
291func (m *equalMatcher) String() string {
292 return "=" + m.expected
293}
294
295type anyMatcher struct {
296}
297
Anton Hanssone1b18362021-12-23 15:05:38 +0000298func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100299 return true
300}
301
302func (m *anyMatcher) String() string {
303 return "=*"
304}
305
306var anyMatcherInstance = &anyMatcher{}
307
Paul Duffinc8111702019-07-22 12:13:55 +0100308type startsWithMatcher struct {
309 prefix string
310}
311
Anton Hanssone1b18362021-12-23 15:05:38 +0000312func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100313 return strings.HasPrefix(value, m.prefix)
314}
315
316func (m *startsWithMatcher) String() string {
317 return ".starts-with(" + m.prefix + ")"
318}
319
Anton Hansson45376402020-04-09 14:18:21 +0100320type regexMatcher struct {
321 re *regexp.Regexp
322}
323
Anton Hanssone1b18362021-12-23 15:05:38 +0000324func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100325 return m.re.MatchString(value)
326}
327
328func (m *regexMatcher) String() string {
329 return ".regexp(" + m.re.String() + ")"
330}
331
Andrei Onea115e7e72020-06-05 21:14:03 +0100332type notInListMatcher struct {
333 allowed []string
334}
335
Anton Hanssone1b18362021-12-23 15:05:38 +0000336func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100337 return !InList(value, m.allowed)
338}
339
340func (m *notInListMatcher) String() string {
341 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
342}
343
Colin Crossc511bc52020-04-07 16:50:32 +0000344type isSetMatcher struct{}
345
Anton Hanssone1b18362021-12-23 15:05:38 +0000346func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000347 return value != ""
348}
349
350func (m *isSetMatcher) String() string {
351 return ".is-set"
352}
353
354var isSetMatcherInstance = &isSetMatcher{}
355
Steven Moreland65b3fd92017-12-06 14:18:35 -0800356type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100357 fields []string // e.x.: Vndk.Enabled
358 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800359}
360
Liz Kammera3d79152021-10-28 18:14:04 -0400361func (r *ruleProperty) String() string {
362 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
363}
364
365type ruleProperties []ruleProperty
366
367func (r ruleProperties) String() string {
368 var s []string
369 for _, r := range r {
370 s = append(s, r.String())
371 }
372 return strings.Join(s, " ")
373}
374
Paul Duffin730f2a52019-06-27 14:08:51 +0100375// A NeverAllow rule.
376type Rule interface {
377 In(path ...string) Rule
378
379 NotIn(path ...string) Rule
380
Paul Duffin35781882019-07-25 15:41:09 +0100381 InDirectDeps(deps ...string) Rule
382
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100383 WithOsClass(osClasses ...OsClass) Rule
384
Paul Duffin730f2a52019-06-27 14:08:51 +0100385 ModuleType(types ...string) Rule
386
387 NotModuleType(types ...string) Rule
388
389 With(properties, value string) Rule
390
Paul Duffinc8111702019-07-22 12:13:55 +0100391 WithMatcher(properties string, matcher ValueMatcher) Rule
392
Paul Duffin730f2a52019-06-27 14:08:51 +0100393 Without(properties, value string) Rule
394
Paul Duffinc8111702019-07-22 12:13:55 +0100395 WithoutMatcher(properties string, matcher ValueMatcher) Rule
396
Paul Duffin730f2a52019-06-27 14:08:51 +0100397 Because(reason string) Rule
398}
399
Steven Moreland65b3fd92017-12-06 14:18:35 -0800400type rule struct {
401 // User string for why this is a thing.
402 reason string
403
404 paths []string
405 unlessPaths []string
406
Paul Duffin35781882019-07-25 15:41:09 +0100407 directDeps map[string]bool
408
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100409 osClasses []OsClass
410
Colin Crossfd4f7432019-03-05 15:06:16 -0800411 moduleTypes []string
412 unlessModuleTypes []string
413
Liz Kammera3d79152021-10-28 18:14:04 -0400414 props ruleProperties
415 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100416
417 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800418}
419
Paul Duffin730f2a52019-06-27 14:08:51 +0100420// Create a new NeverAllow rule.
421func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100422 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423}
Colin Crossfd4f7432019-03-05 15:06:16 -0800424
Liz Kammera3d79152021-10-28 18:14:04 -0400425// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100426func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800427 r.paths = append(r.paths, cleanPaths(path)...)
428 return r
429}
Colin Crossfd4f7432019-03-05 15:06:16 -0800430
Liz Kammera3d79152021-10-28 18:14:04 -0400431// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100432func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800433 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
434 return r
435}
Colin Crossfd4f7432019-03-05 15:06:16 -0800436
Liz Kammera3d79152021-10-28 18:14:04 -0400437// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100438func (r *rule) InDirectDeps(deps ...string) Rule {
439 for _, d := range deps {
440 r.directDeps[d] = true
441 }
442 return r
443}
444
Liz Kammera3d79152021-10-28 18:14:04 -0400445// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100446func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
447 r.osClasses = append(r.osClasses, osClasses...)
448 return r
449}
450
Liz Kammera3d79152021-10-28 18:14:04 -0400451// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100452func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800453 r.moduleTypes = append(r.moduleTypes, types...)
454 return r
455}
456
Liz Kammera3d79152021-10-28 18:14:04 -0400457// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100458func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800459 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
460 return r
461}
462
Liz Kammera3d79152021-10-28 18:14:04 -0400463// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100464func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100465 return r.WithMatcher(properties, selectMatcher(value))
466}
467
Liz Kammera3d79152021-10-28 18:14:04 -0400468// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100469func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100471 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100472 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800473 })
474 return r
475}
Colin Crossfd4f7432019-03-05 15:06:16 -0800476
Liz Kammera3d79152021-10-28 18:14:04 -0400477// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100478func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100479 return r.WithoutMatcher(properties, selectMatcher(value))
480}
481
Liz Kammera3d79152021-10-28 18:14:04 -0400482// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100483func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800484 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100485 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100486 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487 })
488 return r
489}
Colin Crossfd4f7432019-03-05 15:06:16 -0800490
Paul Duffin73bf0542019-07-12 14:12:49 +0100491func selectMatcher(expected string) ValueMatcher {
492 if expected == "*" {
493 return anyMatcherInstance
494 }
495 return &equalMatcher{expected: expected}
496}
497
Liz Kammera3d79152021-10-28 18:14:04 -0400498// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100499func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 r.reason = reason
501 return r
502}
503
504func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400505 s := []string{"neverallow requirements. Not allowed:"}
506 if len(r.paths) > 0 {
507 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800508 }
Liz Kammera3d79152021-10-28 18:14:04 -0400509 if len(r.moduleTypes) > 0 {
510 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800511 }
Liz Kammera3d79152021-10-28 18:14:04 -0400512 if len(r.props) > 0 {
513 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800514 }
Liz Kammera3d79152021-10-28 18:14:04 -0400515 if len(r.directDeps) > 0 {
516 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800517 }
Liz Kammera3d79152021-10-28 18:14:04 -0400518 if len(r.osClasses) > 0 {
519 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100520 }
Liz Kammera3d79152021-10-28 18:14:04 -0400521 if len(r.unlessPaths) > 0 {
522 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
523 }
524 if len(r.unlessModuleTypes) > 0 {
525 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
526 }
527 if len(r.unlessProps) > 0 {
528 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100529 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800530 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400531 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 }
Liz Kammera3d79152021-10-28 18:14:04 -0400533 if len(s) == 1 {
534 s[0] = "neverallow requirements (empty)"
535 }
536 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537}
538
539func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800540 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
541 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542 return includePath && !excludePath
543}
544
Paul Duffin35781882019-07-25 15:41:09 +0100545func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
546 if len(r.directDeps) == 0 {
547 return true
548 }
549
550 matches := false
551 ctx.VisitDirectDeps(func(m Module) {
552 if !matches {
553 name := ctx.OtherModuleName(m)
554 matches = r.directDeps[name]
555 }
556 })
557
558 return matches
559}
560
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100561func (r *rule) appliesToOsClass(osClass OsClass) bool {
562 if len(r.osClasses) == 0 {
563 return true
564 }
565
566 for _, c := range r.osClasses {
567 if c == osClass {
568 return true
569 }
570 }
571
572 return false
573}
574
Colin Crossfd4f7432019-03-05 15:06:16 -0800575func (r *rule) appliesToModuleType(moduleType string) bool {
576 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
577}
578
Anton Hanssone1b18362021-12-23 15:05:38 +0000579func (r *rule) appliesToProperties(properties []interface{}) bool {
580 includeProps := hasAllProperties(properties, r.props)
581 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800582 return includeProps && !excludeProps
583}
584
Paul Duffinc8111702019-07-22 12:13:55 +0100585func StartsWith(prefix string) ValueMatcher {
586 return &startsWithMatcher{prefix}
587}
588
Anton Hansson45376402020-04-09 14:18:21 +0100589func Regexp(re string) ValueMatcher {
590 r, err := regexp.Compile(re)
591 if err != nil {
592 panic(err)
593 }
594 return &regexMatcher{r}
595}
596
Andrei Onea115e7e72020-06-05 21:14:03 +0100597func NotInList(allowed []string) ValueMatcher {
598 return &notInListMatcher{allowed}
599}
600
Steven Moreland65b3fd92017-12-06 14:18:35 -0800601// assorted utils
602
603func cleanPaths(paths []string) []string {
604 res := make([]string, len(paths))
605 for i, v := range paths {
606 res[i] = filepath.Clean(v) + "/"
607 }
608 return res
609}
610
611func fieldNamesForProperties(propertyNames string) []string {
612 names := strings.Split(propertyNames, ".")
613 for i, v := range names {
614 names[i] = proptools.FieldNameForProperty(v)
615 }
616 return names
617}
618
Anton Hanssone1b18362021-12-23 15:05:38 +0000619func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800620 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000621 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800622 return true
623 }
624 }
625 return false
626}
627
Anton Hanssone1b18362021-12-23 15:05:38 +0000628func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800629 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000630 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800631 return false
632 }
633 }
634 return true
635}
636
Anton Hanssone1b18362021-12-23 15:05:38 +0000637func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800638 for _, propertyStruct := range properties {
639 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
640 for _, v := range prop.fields {
641 if !propertiesValue.IsValid() {
642 break
643 }
644 propertiesValue = propertiesValue.FieldByName(v)
645 }
646 if !propertiesValue.IsValid() {
647 continue
648 }
649
Paul Duffin73bf0542019-07-12 14:12:49 +0100650 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000651 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800652 }
653
654 if matchValue(propertiesValue, check) {
655 return true
656 }
657 }
658 return false
659}
660
661func matchValue(value reflect.Value, check func(string) bool) bool {
662 if !value.IsValid() {
663 return false
664 }
665
666 if value.Kind() == reflect.Ptr {
667 if value.IsNil() {
668 return check("")
669 }
670 value = value.Elem()
671 }
672
673 switch value.Kind() {
674 case reflect.String:
675 return check(value.String())
676 case reflect.Bool:
677 return check(strconv.FormatBool(value.Bool()))
678 case reflect.Int:
679 return check(strconv.FormatInt(value.Int(), 10))
680 case reflect.Slice:
681 slice, ok := value.Interface().([]string)
682 if !ok {
683 panic("Can only handle slice of string")
684 }
685 for _, v := range slice {
686 if check(v) {
687 return true
688 }
689 }
690 return false
691 }
692
693 panic("Can't handle type: " + value.Kind().String())
694}
Paul Duffin115445b2019-08-07 15:31:07 +0100695
696var neverallowRulesKey = NewOnceKey("neverallowRules")
697
698func neverallowRules(config Config) []Rule {
699 return config.Once(neverallowRulesKey, func() interface{} {
700 // No test rules were set by setTestNeverallowRules, use the global rules
701 return neverallows
702 }).([]Rule)
703}
704
705// Overrides the default neverallow rules for the supplied config.
706//
707// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100708func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100709 config.Once(neverallowRulesKey, func() interface{} { return testRules })
710}
Paul Duffin45338f02021-03-30 23:07:52 +0100711
712// Prepares for a test by setting neverallow rules and enabling the mutator.
713//
714// If the supplied rules are nil then the default rules are used.
715func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
716 return GroupFixturePreparers(
717 FixtureModifyConfig(func(config Config) {
718 if testRules != nil {
719 setTestNeverallowRules(config, testRules)
720 }
721 }),
722 FixtureRegisterWithContext(func(ctx RegistrationContext) {
723 ctx.PostDepsMutators(registerNeverallowMutator)
724 }),
725 )
726}