blob: f87cebbc9b81fc520cb4741a6c6dc8526d9da3ed [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()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010060}
Steven Moreland65b3fd92017-12-06 14:18:35 -080061
Paul Duffin730f2a52019-06-27 14:08:51 +010062// Add a NeverAllow rule to the set of rules to apply.
63func AddNeverAllowRules(rules ...Rule) {
64 neverallows = append(neverallows, rules...)
65}
66
Paul Duffinc8111702019-07-22 12:13:55 +010067func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000068 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010069 "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 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000084 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000085 "frameworks/av/apex",
86 "frameworks/av/tools",
87 "frameworks/native/cmds",
88 "system/apex",
89 "system/bpf",
90 "system/gatekeeper",
91 "system/hwservicemanager",
92 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000093 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000094 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000095 }
Paul Duffinc8111702019-07-22 12:13:55 +010096
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000097 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
98
99 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100100 rule :=
101 NeverAllow().
102 WithMatcher("include_dirs", StartsWith(path+"/")).
103 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
104 " to use alternate mechanisms and so can no longer be used.")
105
106 rules = append(rules, rule)
107 }
108
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000109 for _, path := range noUseIncludeDir {
110 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
111 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
112 " to use alternate mechanisms and so can no longer be used.")
113 rules = append(rules, rule)
114 }
115
Paul Duffinc8111702019-07-22 12:13:55 +0100116 return rules
117}
118
Paul Duffin730f2a52019-06-27 14:08:51 +0100119func createTrebleRules() []Rule {
120 return []Rule{
121 NeverAllow().
122 In("vendor", "device").
123 With("vndk.enabled", "true").
124 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900125 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100126 Because("the VNDK can never contain a library that is device dependent."),
127 NeverAllow().
128 With("vndk.enabled", "true").
129 Without("vendor", "true").
130 Without("owner", "").
131 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800132
Neil Fullerdf5f3562018-10-21 17:19:10 +0100133 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100134 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800135 Without("name", "libhidlbase-combined-impl").
136 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100137 With("product_variables.enforce_vintf_manifest.cflags", "*").
138 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100139
140 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 NeverAllow().
142 Without("name", "libc_bionic_ndk").
143 With("product_variables.treble_linker_namespaces.cflags", "*").
144 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145
146 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148 }
149}
150
Paul Duffin730f2a52019-06-27 14:08:51 +0100151func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700152 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700153 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700154 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800155 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000156 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800157 }
158
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 return []Rule{
160 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700161 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100162 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700163 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800164 }
165}
166
Colin Crossc511bc52020-04-07 16:50:32 +0000167func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700168 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000169 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
170 // This sometimes works because the APEX modules that contain derive_sdk and
171 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
172 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100173 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700174 // These are for apps and shouldn't be used by non-SDK variant modules.
175 "prebuilts/ndk",
176 "tools/test/graphicsbenchmark/apps/sample_app",
177 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700178 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000179 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000180 }
181
Colin Cross440e0d02020-06-11 11:32:11 -0700182 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // android_native_app_glue and libRSSupport use native_window.h but target old
184 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
185 // so they can't add libnativewindow to shared_libs to get the header directory
186 // for the platform variant. Allow them to use the platform variant
187 // property to set shared_libs.
188 "prebuilts/ndk",
189 "frameworks/rs",
190 }
191
192 return []Rule{
193 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700194 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000195 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700196 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000197 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700198 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000199 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700200 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000201 }
202}
203
David Srbeckye033cba2020-05-20 22:20:28 +0100204func createUncompressDexRules() []Rule {
205 return []Rule{
206 NeverAllow().
207 NotIn("art").
208 WithMatcher("uncompress_dex", isSetMatcherInstance).
209 Because("uncompress_dex is only allowed for certain jars for test in art."),
210 }
211}
212
Yifan Hong696ed4d2020-07-27 12:59:58 -0700213func createMakefileGoalRules() []Rule {
214 return []Rule{
215 NeverAllow().
216 ModuleType("makefile_goal").
217 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Inseob Kima9078742021-12-29 08:59:00 +0000218 Because("Only boot images may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700219 }
220}
221
Inseob Kim800d1142021-06-14 12:03:51 +0900222func createInitFirstStageRules() []Rule {
223 return []Rule{
224 NeverAllow().
225 Without("name", "init_first_stage").
226 With("install_in_root", "true").
227 Because("install_in_root is only for init_first_stage."),
228 }
229}
230
Steven Moreland65b3fd92017-12-06 14:18:35 -0800231func neverallowMutator(ctx BottomUpMutatorContext) {
232 m, ok := ctx.Module().(Module)
233 if !ok {
234 return
235 }
236
237 dir := ctx.ModuleDir() + "/"
238 properties := m.GetProperties()
239
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100240 osClass := ctx.Module().Target().Os.Class
241
Paul Duffin115445b2019-08-07 15:31:07 +0100242 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100243 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800244 if !n.appliesToPath(dir) {
245 continue
246 }
247
Colin Crossfd4f7432019-03-05 15:06:16 -0800248 if !n.appliesToModuleType(ctx.ModuleType()) {
249 continue
250 }
251
Anton Hanssone1b18362021-12-23 15:05:38 +0000252 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800253 continue
254 }
255
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100256 if !n.appliesToOsClass(osClass) {
257 continue
258 }
259
Paul Duffin35781882019-07-25 15:41:09 +0100260 if !n.appliesToDirectDeps(ctx) {
261 continue
262 }
263
Steven Moreland65b3fd92017-12-06 14:18:35 -0800264 ctx.ModuleErrorf("violates " + n.String())
265 }
266}
267
Paul Duffin73bf0542019-07-12 14:12:49 +0100268type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000269 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100270 String() string
271}
272
273type equalMatcher struct {
274 expected string
275}
276
Anton Hanssone1b18362021-12-23 15:05:38 +0000277func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100278 return m.expected == value
279}
280
281func (m *equalMatcher) String() string {
282 return "=" + m.expected
283}
284
285type anyMatcher struct {
286}
287
Anton Hanssone1b18362021-12-23 15:05:38 +0000288func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100289 return true
290}
291
292func (m *anyMatcher) String() string {
293 return "=*"
294}
295
296var anyMatcherInstance = &anyMatcher{}
297
Paul Duffinc8111702019-07-22 12:13:55 +0100298type startsWithMatcher struct {
299 prefix string
300}
301
Anton Hanssone1b18362021-12-23 15:05:38 +0000302func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100303 return strings.HasPrefix(value, m.prefix)
304}
305
306func (m *startsWithMatcher) String() string {
307 return ".starts-with(" + m.prefix + ")"
308}
309
Anton Hansson45376402020-04-09 14:18:21 +0100310type regexMatcher struct {
311 re *regexp.Regexp
312}
313
Anton Hanssone1b18362021-12-23 15:05:38 +0000314func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100315 return m.re.MatchString(value)
316}
317
318func (m *regexMatcher) String() string {
319 return ".regexp(" + m.re.String() + ")"
320}
321
Andrei Onea115e7e72020-06-05 21:14:03 +0100322type notInListMatcher struct {
323 allowed []string
324}
325
Anton Hanssone1b18362021-12-23 15:05:38 +0000326func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100327 return !InList(value, m.allowed)
328}
329
330func (m *notInListMatcher) String() string {
331 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
332}
333
Colin Crossc511bc52020-04-07 16:50:32 +0000334type isSetMatcher struct{}
335
Anton Hanssone1b18362021-12-23 15:05:38 +0000336func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000337 return value != ""
338}
339
340func (m *isSetMatcher) String() string {
341 return ".is-set"
342}
343
344var isSetMatcherInstance = &isSetMatcher{}
345
Steven Moreland65b3fd92017-12-06 14:18:35 -0800346type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100347 fields []string // e.x.: Vndk.Enabled
348 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800349}
350
Liz Kammera3d79152021-10-28 18:14:04 -0400351func (r *ruleProperty) String() string {
352 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
353}
354
355type ruleProperties []ruleProperty
356
357func (r ruleProperties) String() string {
358 var s []string
359 for _, r := range r {
360 s = append(s, r.String())
361 }
362 return strings.Join(s, " ")
363}
364
Paul Duffin730f2a52019-06-27 14:08:51 +0100365// A NeverAllow rule.
366type Rule interface {
367 In(path ...string) Rule
368
369 NotIn(path ...string) Rule
370
Paul Duffin35781882019-07-25 15:41:09 +0100371 InDirectDeps(deps ...string) Rule
372
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100373 WithOsClass(osClasses ...OsClass) Rule
374
Paul Duffin730f2a52019-06-27 14:08:51 +0100375 ModuleType(types ...string) Rule
376
377 NotModuleType(types ...string) Rule
378
379 With(properties, value string) Rule
380
Paul Duffinc8111702019-07-22 12:13:55 +0100381 WithMatcher(properties string, matcher ValueMatcher) Rule
382
Paul Duffin730f2a52019-06-27 14:08:51 +0100383 Without(properties, value string) Rule
384
Paul Duffinc8111702019-07-22 12:13:55 +0100385 WithoutMatcher(properties string, matcher ValueMatcher) Rule
386
Paul Duffin730f2a52019-06-27 14:08:51 +0100387 Because(reason string) Rule
388}
389
Steven Moreland65b3fd92017-12-06 14:18:35 -0800390type rule struct {
391 // User string for why this is a thing.
392 reason string
393
394 paths []string
395 unlessPaths []string
396
Paul Duffin35781882019-07-25 15:41:09 +0100397 directDeps map[string]bool
398
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100399 osClasses []OsClass
400
Colin Crossfd4f7432019-03-05 15:06:16 -0800401 moduleTypes []string
402 unlessModuleTypes []string
403
Liz Kammera3d79152021-10-28 18:14:04 -0400404 props ruleProperties
405 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100406
407 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800408}
409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410// Create a new NeverAllow rule.
411func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100412 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800413}
Colin Crossfd4f7432019-03-05 15:06:16 -0800414
Liz Kammera3d79152021-10-28 18:14:04 -0400415// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100416func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800417 r.paths = append(r.paths, cleanPaths(path)...)
418 return r
419}
Colin Crossfd4f7432019-03-05 15:06:16 -0800420
Liz Kammera3d79152021-10-28 18:14:04 -0400421// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100422func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
424 return r
425}
Colin Crossfd4f7432019-03-05 15:06:16 -0800426
Liz Kammera3d79152021-10-28 18:14:04 -0400427// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100428func (r *rule) InDirectDeps(deps ...string) Rule {
429 for _, d := range deps {
430 r.directDeps[d] = true
431 }
432 return r
433}
434
Liz Kammera3d79152021-10-28 18:14:04 -0400435// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100436func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
437 r.osClasses = append(r.osClasses, osClasses...)
438 return r
439}
440
Liz Kammera3d79152021-10-28 18:14:04 -0400441// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100442func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800443 r.moduleTypes = append(r.moduleTypes, types...)
444 return r
445}
446
Liz Kammera3d79152021-10-28 18:14:04 -0400447// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100448func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800449 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
450 return r
451}
452
Liz Kammera3d79152021-10-28 18:14:04 -0400453// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100454func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100455 return r.WithMatcher(properties, selectMatcher(value))
456}
457
Liz Kammera3d79152021-10-28 18:14:04 -0400458// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100459func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800460 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100461 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100462 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463 })
464 return r
465}
Colin Crossfd4f7432019-03-05 15:06:16 -0800466
Liz Kammera3d79152021-10-28 18:14:04 -0400467// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100468func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100469 return r.WithoutMatcher(properties, selectMatcher(value))
470}
471
Liz Kammera3d79152021-10-28 18:14:04 -0400472// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100473func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800474 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100475 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100476 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800477 })
478 return r
479}
Colin Crossfd4f7432019-03-05 15:06:16 -0800480
Paul Duffin73bf0542019-07-12 14:12:49 +0100481func selectMatcher(expected string) ValueMatcher {
482 if expected == "*" {
483 return anyMatcherInstance
484 }
485 return &equalMatcher{expected: expected}
486}
487
Liz Kammera3d79152021-10-28 18:14:04 -0400488// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100489func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800490 r.reason = reason
491 return r
492}
493
494func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400495 s := []string{"neverallow requirements. Not allowed:"}
496 if len(r.paths) > 0 {
497 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800498 }
Liz Kammera3d79152021-10-28 18:14:04 -0400499 if len(r.moduleTypes) > 0 {
500 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800501 }
Liz Kammera3d79152021-10-28 18:14:04 -0400502 if len(r.props) > 0 {
503 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800504 }
Liz Kammera3d79152021-10-28 18:14:04 -0400505 if len(r.directDeps) > 0 {
506 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800507 }
Liz Kammera3d79152021-10-28 18:14:04 -0400508 if len(r.osClasses) > 0 {
509 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100510 }
Liz Kammera3d79152021-10-28 18:14:04 -0400511 if len(r.unlessPaths) > 0 {
512 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
513 }
514 if len(r.unlessModuleTypes) > 0 {
515 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
516 }
517 if len(r.unlessProps) > 0 {
518 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100519 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800520 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400521 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800522 }
Liz Kammera3d79152021-10-28 18:14:04 -0400523 if len(s) == 1 {
524 s[0] = "neverallow requirements (empty)"
525 }
526 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800527}
528
529func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800530 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
531 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 return includePath && !excludePath
533}
534
Paul Duffin35781882019-07-25 15:41:09 +0100535func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
536 if len(r.directDeps) == 0 {
537 return true
538 }
539
540 matches := false
541 ctx.VisitDirectDeps(func(m Module) {
542 if !matches {
543 name := ctx.OtherModuleName(m)
544 matches = r.directDeps[name]
545 }
546 })
547
548 return matches
549}
550
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100551func (r *rule) appliesToOsClass(osClass OsClass) bool {
552 if len(r.osClasses) == 0 {
553 return true
554 }
555
556 for _, c := range r.osClasses {
557 if c == osClass {
558 return true
559 }
560 }
561
562 return false
563}
564
Colin Crossfd4f7432019-03-05 15:06:16 -0800565func (r *rule) appliesToModuleType(moduleType string) bool {
566 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
567}
568
Anton Hanssone1b18362021-12-23 15:05:38 +0000569func (r *rule) appliesToProperties(properties []interface{}) bool {
570 includeProps := hasAllProperties(properties, r.props)
571 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800572 return includeProps && !excludeProps
573}
574
Paul Duffinc8111702019-07-22 12:13:55 +0100575func StartsWith(prefix string) ValueMatcher {
576 return &startsWithMatcher{prefix}
577}
578
Anton Hansson45376402020-04-09 14:18:21 +0100579func Regexp(re string) ValueMatcher {
580 r, err := regexp.Compile(re)
581 if err != nil {
582 panic(err)
583 }
584 return &regexMatcher{r}
585}
586
Andrei Onea115e7e72020-06-05 21:14:03 +0100587func NotInList(allowed []string) ValueMatcher {
588 return &notInListMatcher{allowed}
589}
590
Steven Moreland65b3fd92017-12-06 14:18:35 -0800591// assorted utils
592
593func cleanPaths(paths []string) []string {
594 res := make([]string, len(paths))
595 for i, v := range paths {
596 res[i] = filepath.Clean(v) + "/"
597 }
598 return res
599}
600
601func fieldNamesForProperties(propertyNames string) []string {
602 names := strings.Split(propertyNames, ".")
603 for i, v := range names {
604 names[i] = proptools.FieldNameForProperty(v)
605 }
606 return names
607}
608
Anton Hanssone1b18362021-12-23 15:05:38 +0000609func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800610 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000611 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800612 return true
613 }
614 }
615 return false
616}
617
Anton Hanssone1b18362021-12-23 15:05:38 +0000618func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800619 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000620 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800621 return false
622 }
623 }
624 return true
625}
626
Anton Hanssone1b18362021-12-23 15:05:38 +0000627func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800628 for _, propertyStruct := range properties {
629 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
630 for _, v := range prop.fields {
631 if !propertiesValue.IsValid() {
632 break
633 }
634 propertiesValue = propertiesValue.FieldByName(v)
635 }
636 if !propertiesValue.IsValid() {
637 continue
638 }
639
Paul Duffin73bf0542019-07-12 14:12:49 +0100640 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000641 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800642 }
643
644 if matchValue(propertiesValue, check) {
645 return true
646 }
647 }
648 return false
649}
650
651func matchValue(value reflect.Value, check func(string) bool) bool {
652 if !value.IsValid() {
653 return false
654 }
655
656 if value.Kind() == reflect.Ptr {
657 if value.IsNil() {
658 return check("")
659 }
660 value = value.Elem()
661 }
662
663 switch value.Kind() {
664 case reflect.String:
665 return check(value.String())
666 case reflect.Bool:
667 return check(strconv.FormatBool(value.Bool()))
668 case reflect.Int:
669 return check(strconv.FormatInt(value.Int(), 10))
670 case reflect.Slice:
671 slice, ok := value.Interface().([]string)
672 if !ok {
673 panic("Can only handle slice of string")
674 }
675 for _, v := range slice {
676 if check(v) {
677 return true
678 }
679 }
680 return false
681 }
682
683 panic("Can't handle type: " + value.Kind().String())
684}
Paul Duffin115445b2019-08-07 15:31:07 +0100685
686var neverallowRulesKey = NewOnceKey("neverallowRules")
687
688func neverallowRules(config Config) []Rule {
689 return config.Once(neverallowRulesKey, func() interface{} {
690 // No test rules were set by setTestNeverallowRules, use the global rules
691 return neverallows
692 }).([]Rule)
693}
694
695// Overrides the default neverallow rules for the supplied config.
696//
697// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100698func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100699 config.Once(neverallowRulesKey, func() interface{} { return testRules })
700}
Paul Duffin45338f02021-03-30 23:07:52 +0100701
702// Prepares for a test by setting neverallow rules and enabling the mutator.
703//
704// If the supplied rules are nil then the default rules are used.
705func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
706 return GroupFixturePreparers(
707 FixtureModifyConfig(func(config Config) {
708 if testRules != nil {
709 setTestNeverallowRules(config, testRules)
710 }
711 }),
712 FixtureRegisterWithContext(func(ctx RegistrationContext) {
713 ctx.PostDepsMutators(registerNeverallowMutator)
714 }),
715 )
716}