blob: 0348619588c08ebb27a38002d82020a70e3b77bb [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
Joe Onoratob4638c12021-10-27 15:47:06 -070030// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080031// 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
Paul Duffin45338f02021-03-30 23:07:52 +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()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000055 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010056 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070057 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
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 {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000067 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010068 "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 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000083 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000084 "frameworks/av/apex",
85 "frameworks/av/tools",
86 "frameworks/native/cmds",
87 "system/apex",
88 "system/bpf",
89 "system/gatekeeper",
90 "system/hwservicemanager",
91 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000092 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000093 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000094 }
Paul Duffinc8111702019-07-22 12:13:55 +010095
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
97
98 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +010099 rule :=
100 NeverAllow().
101 WithMatcher("include_dirs", StartsWith(path+"/")).
102 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
103 " to use alternate mechanisms and so can no longer be used.")
104
105 rules = append(rules, rule)
106 }
107
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000108 for _, path := range noUseIncludeDir {
109 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
110 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
111 " to use alternate mechanisms and so can no longer be used.")
112 rules = append(rules, rule)
113 }
114
Paul Duffinc8111702019-07-22 12:13:55 +0100115 return rules
116}
117
Paul Duffin730f2a52019-06-27 14:08:51 +0100118func createTrebleRules() []Rule {
119 return []Rule{
120 NeverAllow().
121 In("vendor", "device").
122 With("vndk.enabled", "true").
123 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900124 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100125 Because("the VNDK can never contain a library that is device dependent."),
126 NeverAllow().
127 With("vndk.enabled", "true").
128 Without("vendor", "true").
129 Without("owner", "").
130 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800131
Neil Fullerdf5f3562018-10-21 17:19:10 +0100132 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100133 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800134 Without("name", "libhidlbase-combined-impl").
135 Without("name", "libhidlbase").
136 Without("name", "libhidlbase_pgo").
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").
Yuntao Xufeb07562021-11-18 22:33:02 +0000217 // TODO(b/33691272): remove this after migrating seapp to Soong
218 Without("product_out_path", "obj/ETC/plat_seapp_contexts_intermediates/plat_seapp_contexts").
219 Without("product_out_path", "obj/ETC/plat_seapp_neverallows_intermediates/plat_seapp_neverallows").
Yifan Hong696ed4d2020-07-27 12:59:58 -0700220 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Yuntao Xufeb07562021-11-18 22:33:02 +0000221 Because("Only boot images and seapp contexts may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700222 }
223}
224
Inseob Kim800d1142021-06-14 12:03:51 +0900225func createInitFirstStageRules() []Rule {
226 return []Rule{
227 NeverAllow().
228 Without("name", "init_first_stage").
229 With("install_in_root", "true").
230 Because("install_in_root is only for init_first_stage."),
231 }
232}
233
Steven Moreland65b3fd92017-12-06 14:18:35 -0800234func neverallowMutator(ctx BottomUpMutatorContext) {
235 m, ok := ctx.Module().(Module)
236 if !ok {
237 return
238 }
239
240 dir := ctx.ModuleDir() + "/"
241 properties := m.GetProperties()
242
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100243 osClass := ctx.Module().Target().Os.Class
244
Paul Duffin115445b2019-08-07 15:31:07 +0100245 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100246 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800247 if !n.appliesToPath(dir) {
248 continue
249 }
250
Colin Crossfd4f7432019-03-05 15:06:16 -0800251 if !n.appliesToModuleType(ctx.ModuleType()) {
252 continue
253 }
254
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900255 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800256 continue
257 }
258
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100259 if !n.appliesToOsClass(osClass) {
260 continue
261 }
262
Paul Duffin35781882019-07-25 15:41:09 +0100263 if !n.appliesToDirectDeps(ctx) {
264 continue
265 }
266
Andrei Onea115e7e72020-06-05 21:14:03 +0100267 if !n.appliesToBootclasspathJar(ctx) {
268 continue
269 }
270
Steven Moreland65b3fd92017-12-06 14:18:35 -0800271 ctx.ModuleErrorf("violates " + n.String())
272 }
273}
274
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900275type ValueMatcherContext interface {
276 Config() Config
277}
278
Paul Duffin73bf0542019-07-12 14:12:49 +0100279type ValueMatcher interface {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900280 Test(ValueMatcherContext, string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100281 String() string
282}
283
284type equalMatcher struct {
285 expected string
286}
287
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900288func (m *equalMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100289 return m.expected == value
290}
291
292func (m *equalMatcher) String() string {
293 return "=" + m.expected
294}
295
296type anyMatcher struct {
297}
298
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900299func (m *anyMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100300 return true
301}
302
303func (m *anyMatcher) String() string {
304 return "=*"
305}
306
307var anyMatcherInstance = &anyMatcher{}
308
Paul Duffinc8111702019-07-22 12:13:55 +0100309type startsWithMatcher struct {
310 prefix string
311}
312
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900313func (m *startsWithMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100314 return strings.HasPrefix(value, m.prefix)
315}
316
317func (m *startsWithMatcher) String() string {
318 return ".starts-with(" + m.prefix + ")"
319}
320
Anton Hansson45376402020-04-09 14:18:21 +0100321type regexMatcher struct {
322 re *regexp.Regexp
323}
324
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900325func (m *regexMatcher) Test(ctx ValueMatcherContext, value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100326 return m.re.MatchString(value)
327}
328
329func (m *regexMatcher) String() string {
330 return ".regexp(" + m.re.String() + ")"
331}
332
Andrei Onea115e7e72020-06-05 21:14:03 +0100333type notInListMatcher struct {
334 allowed []string
335}
336
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900337func (m *notInListMatcher) Test(ctx ValueMatcherContext, value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100338 return !InList(value, m.allowed)
339}
340
341func (m *notInListMatcher) String() string {
342 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
343}
344
Colin Crossc511bc52020-04-07 16:50:32 +0000345type isSetMatcher struct{}
346
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900347func (m *isSetMatcher) Test(ctx ValueMatcherContext, value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000348 return value != ""
349}
350
351func (m *isSetMatcher) String() string {
352 return ".is-set"
353}
354
355var isSetMatcherInstance = &isSetMatcher{}
356
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900357type sdkVersionMatcher struct {
358 condition func(ctx ValueMatcherContext, spec SdkSpec) bool
359 description string
360}
361
362func (m *sdkVersionMatcher) Test(ctx ValueMatcherContext, value string) bool {
363 return m.condition(ctx, SdkSpecFromWithConfig(ctx.Config(), value))
364}
365
366func (m *sdkVersionMatcher) String() string {
367 return ".sdk-version(" + m.description + ")"
368}
369
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100371 fields []string // e.x.: Vndk.Enabled
372 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800373}
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
Andrei Onea115e7e72020-06-05 21:14:03 +0100389 BootclasspathJar() Rule
390
Paul Duffin730f2a52019-06-27 14:08:51 +0100391 With(properties, value string) Rule
392
Paul Duffinc8111702019-07-22 12:13:55 +0100393 WithMatcher(properties string, matcher ValueMatcher) Rule
394
Paul Duffin730f2a52019-06-27 14:08:51 +0100395 Without(properties, value string) Rule
396
Paul Duffinc8111702019-07-22 12:13:55 +0100397 WithoutMatcher(properties string, matcher ValueMatcher) Rule
398
Paul Duffin730f2a52019-06-27 14:08:51 +0100399 Because(reason string) Rule
400}
401
Steven Moreland65b3fd92017-12-06 14:18:35 -0800402type rule struct {
403 // User string for why this is a thing.
404 reason string
405
406 paths []string
407 unlessPaths []string
408
Paul Duffin35781882019-07-25 15:41:09 +0100409 directDeps map[string]bool
410
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100411 osClasses []OsClass
412
Colin Crossfd4f7432019-03-05 15:06:16 -0800413 moduleTypes []string
414 unlessModuleTypes []string
415
Steven Moreland65b3fd92017-12-06 14:18:35 -0800416 props []ruleProperty
417 unlessProps []ruleProperty
Andrei Onea115e7e72020-06-05 21:14:03 +0100418
419 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800420}
421
Paul Duffin730f2a52019-06-27 14:08:51 +0100422// Create a new NeverAllow rule.
423func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100424 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800425}
Colin Crossfd4f7432019-03-05 15:06:16 -0800426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428 r.paths = append(r.paths, cleanPaths(path)...)
429 return r
430}
Colin Crossfd4f7432019-03-05 15:06:16 -0800431
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
Paul Duffin35781882019-07-25 15:41:09 +0100437func (r *rule) InDirectDeps(deps ...string) Rule {
438 for _, d := range deps {
439 r.directDeps[d] = true
440 }
441 return r
442}
443
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100444func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
445 r.osClasses = append(r.osClasses, osClasses...)
446 return r
447}
448
Paul Duffin730f2a52019-06-27 14:08:51 +0100449func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800450 r.moduleTypes = append(r.moduleTypes, types...)
451 return r
452}
453
Paul Duffin730f2a52019-06-27 14:08:51 +0100454func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800455 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
456 return r
457}
458
Paul Duffin730f2a52019-06-27 14:08:51 +0100459func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100460 return r.WithMatcher(properties, selectMatcher(value))
461}
462
463func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800464 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100465 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100466 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800467 })
468 return r
469}
Colin Crossfd4f7432019-03-05 15:06:16 -0800470
Paul Duffin730f2a52019-06-27 14:08:51 +0100471func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100472 return r.WithoutMatcher(properties, selectMatcher(value))
473}
474
475func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800476 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100477 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100478 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800479 })
480 return r
481}
Colin Crossfd4f7432019-03-05 15:06:16 -0800482
Paul Duffin73bf0542019-07-12 14:12:49 +0100483func selectMatcher(expected string) ValueMatcher {
484 if expected == "*" {
485 return anyMatcherInstance
486 }
487 return &equalMatcher{expected: expected}
488}
489
Paul Duffin730f2a52019-06-27 14:08:51 +0100490func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800491 r.reason = reason
492 return r
493}
494
Andrei Onea115e7e72020-06-05 21:14:03 +0100495func (r *rule) BootclasspathJar() Rule {
496 r.onlyBootclasspathJar = true
497 return r
498}
499
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500func (r *rule) String() string {
501 s := "neverallow"
502 for _, v := range r.paths {
503 s += " dir:" + v + "*"
504 }
505 for _, v := range r.unlessPaths {
506 s += " -dir:" + v + "*"
507 }
Colin Crossfd4f7432019-03-05 15:06:16 -0800508 for _, v := range r.moduleTypes {
509 s += " type:" + v
510 }
511 for _, v := range r.unlessModuleTypes {
512 s += " -type:" + v
513 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800514 for _, v := range r.props {
Paul Duffin73bf0542019-07-12 14:12:49 +0100515 s += " " + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800516 }
517 for _, v := range r.unlessProps {
Paul Duffin73bf0542019-07-12 14:12:49 +0100518 s += " -" + strings.Join(v.fields, ".") + v.matcher.String()
Steven Moreland65b3fd92017-12-06 14:18:35 -0800519 }
Paul Duffin35781882019-07-25 15:41:09 +0100520 for k := range r.directDeps {
521 s += " deps:" + k
522 }
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100523 for _, v := range r.osClasses {
524 s += " os:" + v.String()
525 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100526 if r.onlyBootclasspathJar {
527 s += " inBcp"
528 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800529 if len(r.reason) != 0 {
530 s += " which is restricted because " + r.reason
531 }
532 return s
533}
534
535func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800536 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
537 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800538 return includePath && !excludePath
539}
540
Paul Duffin35781882019-07-25 15:41:09 +0100541func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
542 if len(r.directDeps) == 0 {
543 return true
544 }
545
546 matches := false
547 ctx.VisitDirectDeps(func(m Module) {
548 if !matches {
549 name := ctx.OtherModuleName(m)
550 matches = r.directDeps[name]
551 }
552 })
553
554 return matches
555}
556
Andrei Onea115e7e72020-06-05 21:14:03 +0100557func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
558 if !r.onlyBootclasspathJar {
559 return true
560 }
561
562 return InList(ctx.ModuleName(), ctx.Config().BootJars())
563}
564
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100565func (r *rule) appliesToOsClass(osClass OsClass) bool {
566 if len(r.osClasses) == 0 {
567 return true
568 }
569
570 for _, c := range r.osClasses {
571 if c == osClass {
572 return true
573 }
574 }
575
576 return false
577}
578
Colin Crossfd4f7432019-03-05 15:06:16 -0800579func (r *rule) appliesToModuleType(moduleType string) bool {
580 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
581}
582
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900583func (r *rule) appliesToProperties(ctx ValueMatcherContext,
584 properties []interface{}) bool {
585 includeProps := hasAllProperties(ctx, properties, r.props)
586 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800587 return includeProps && !excludeProps
588}
589
Paul Duffinc8111702019-07-22 12:13:55 +0100590func StartsWith(prefix string) ValueMatcher {
591 return &startsWithMatcher{prefix}
592}
593
Anton Hansson45376402020-04-09 14:18:21 +0100594func Regexp(re string) ValueMatcher {
595 r, err := regexp.Compile(re)
596 if err != nil {
597 panic(err)
598 }
599 return &regexMatcher{r}
600}
601
Andrei Onea115e7e72020-06-05 21:14:03 +0100602func NotInList(allowed []string) ValueMatcher {
603 return &notInListMatcher{allowed}
604}
605
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900606func LessThanSdkVersion(sdk string) ValueMatcher {
607 return &sdkVersionMatcher{
608 condition: func(ctx ValueMatcherContext, spec SdkSpec) bool {
609 return spec.ApiLevel.LessThan(
610 SdkSpecFromWithConfig(ctx.Config(), sdk).ApiLevel)
611 },
612 description: "lessThan=" + sdk,
613 }
614}
615
Steven Moreland65b3fd92017-12-06 14:18:35 -0800616// assorted utils
617
618func cleanPaths(paths []string) []string {
619 res := make([]string, len(paths))
620 for i, v := range paths {
621 res[i] = filepath.Clean(v) + "/"
622 }
623 return res
624}
625
626func fieldNamesForProperties(propertyNames string) []string {
627 names := strings.Split(propertyNames, ".")
628 for i, v := range names {
629 names[i] = proptools.FieldNameForProperty(v)
630 }
631 return names
632}
633
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900634func hasAnyProperty(ctx ValueMatcherContext, properties []interface{},
635 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800636 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900637 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800638 return true
639 }
640 }
641 return false
642}
643
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900644func hasAllProperties(ctx ValueMatcherContext, properties []interface{},
645 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900647 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 return false
649 }
650 }
651 return true
652}
653
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900654func hasProperty(ctx ValueMatcherContext, properties []interface{},
655 prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800656 for _, propertyStruct := range properties {
657 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
658 for _, v := range prop.fields {
659 if !propertiesValue.IsValid() {
660 break
661 }
662 propertiesValue = propertiesValue.FieldByName(v)
663 }
664 if !propertiesValue.IsValid() {
665 continue
666 }
667
Paul Duffin73bf0542019-07-12 14:12:49 +0100668 check := func(value string) bool {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900669 return prop.matcher.Test(ctx, value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800670 }
671
672 if matchValue(propertiesValue, check) {
673 return true
674 }
675 }
676 return false
677}
678
679func matchValue(value reflect.Value, check func(string) bool) bool {
680 if !value.IsValid() {
681 return false
682 }
683
684 if value.Kind() == reflect.Ptr {
685 if value.IsNil() {
686 return check("")
687 }
688 value = value.Elem()
689 }
690
691 switch value.Kind() {
692 case reflect.String:
693 return check(value.String())
694 case reflect.Bool:
695 return check(strconv.FormatBool(value.Bool()))
696 case reflect.Int:
697 return check(strconv.FormatInt(value.Int(), 10))
698 case reflect.Slice:
699 slice, ok := value.Interface().([]string)
700 if !ok {
701 panic("Can only handle slice of string")
702 }
703 for _, v := range slice {
704 if check(v) {
705 return true
706 }
707 }
708 return false
709 }
710
711 panic("Can't handle type: " + value.Kind().String())
712}
Paul Duffin115445b2019-08-07 15:31:07 +0100713
714var neverallowRulesKey = NewOnceKey("neverallowRules")
715
716func neverallowRules(config Config) []Rule {
717 return config.Once(neverallowRulesKey, func() interface{} {
718 // No test rules were set by setTestNeverallowRules, use the global rules
719 return neverallows
720 }).([]Rule)
721}
722
723// Overrides the default neverallow rules for the supplied config.
724//
725// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100726func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100727 config.Once(neverallowRulesKey, func() interface{} { return testRules })
728}
Paul Duffin45338f02021-03-30 23:07:52 +0100729
730// Prepares for a test by setting neverallow rules and enabling the mutator.
731//
732// If the supplied rules are nil then the default rules are used.
733func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
734 return GroupFixturePreparers(
735 FixtureModifyConfig(func(config Config) {
736 if testRules != nil {
737 setTestNeverallowRules(config, testRules)
738 }
739 }),
740 FixtureRegisterWithContext(func(ctx RegistrationContext) {
741 ctx.PostDepsMutators(registerNeverallowMutator)
742 }),
743 )
744}