blob: 28597505c021488abf999d92722970f3076735d5 [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").
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
Liz Kammera3d79152021-10-28 18:14:04 -0400375func (r *ruleProperty) String() string {
376 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
377}
378
379type ruleProperties []ruleProperty
380
381func (r ruleProperties) String() string {
382 var s []string
383 for _, r := range r {
384 s = append(s, r.String())
385 }
386 return strings.Join(s, " ")
387}
388
Paul Duffin730f2a52019-06-27 14:08:51 +0100389// A NeverAllow rule.
390type Rule interface {
391 In(path ...string) Rule
392
393 NotIn(path ...string) Rule
394
Paul Duffin35781882019-07-25 15:41:09 +0100395 InDirectDeps(deps ...string) Rule
396
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100397 WithOsClass(osClasses ...OsClass) Rule
398
Paul Duffin730f2a52019-06-27 14:08:51 +0100399 ModuleType(types ...string) Rule
400
401 NotModuleType(types ...string) Rule
402
Andrei Onea115e7e72020-06-05 21:14:03 +0100403 BootclasspathJar() Rule
404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405 With(properties, value string) Rule
406
Paul Duffinc8111702019-07-22 12:13:55 +0100407 WithMatcher(properties string, matcher ValueMatcher) Rule
408
Paul Duffin730f2a52019-06-27 14:08:51 +0100409 Without(properties, value string) Rule
410
Paul Duffinc8111702019-07-22 12:13:55 +0100411 WithoutMatcher(properties string, matcher ValueMatcher) Rule
412
Paul Duffin730f2a52019-06-27 14:08:51 +0100413 Because(reason string) Rule
414}
415
Steven Moreland65b3fd92017-12-06 14:18:35 -0800416type rule struct {
417 // User string for why this is a thing.
418 reason string
419
420 paths []string
421 unlessPaths []string
422
Paul Duffin35781882019-07-25 15:41:09 +0100423 directDeps map[string]bool
424
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100425 osClasses []OsClass
426
Colin Crossfd4f7432019-03-05 15:06:16 -0800427 moduleTypes []string
428 unlessModuleTypes []string
429
Liz Kammera3d79152021-10-28 18:14:04 -0400430 props ruleProperties
431 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100432
433 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800434}
435
Paul Duffin730f2a52019-06-27 14:08:51 +0100436// Create a new NeverAllow rule.
437func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100438 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800439}
Colin Crossfd4f7432019-03-05 15:06:16 -0800440
Liz Kammera3d79152021-10-28 18:14:04 -0400441// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100442func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800443 r.paths = append(r.paths, cleanPaths(path)...)
444 return r
445}
Colin Crossfd4f7432019-03-05 15:06:16 -0800446
Liz Kammera3d79152021-10-28 18:14:04 -0400447// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100448func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800449 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
450 return r
451}
Colin Crossfd4f7432019-03-05 15:06:16 -0800452
Liz Kammera3d79152021-10-28 18:14:04 -0400453// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100454func (r *rule) InDirectDeps(deps ...string) Rule {
455 for _, d := range deps {
456 r.directDeps[d] = true
457 }
458 return r
459}
460
Liz Kammera3d79152021-10-28 18:14:04 -0400461// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100462func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
463 r.osClasses = append(r.osClasses, osClasses...)
464 return r
465}
466
Liz Kammera3d79152021-10-28 18:14:04 -0400467// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100468func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800469 r.moduleTypes = append(r.moduleTypes, types...)
470 return r
471}
472
Liz Kammera3d79152021-10-28 18:14:04 -0400473// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100474func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800475 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
476 return r
477}
478
Liz Kammera3d79152021-10-28 18:14:04 -0400479// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100480func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100481 return r.WithMatcher(properties, selectMatcher(value))
482}
483
Liz Kammera3d79152021-10-28 18:14:04 -0400484// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100485func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100487 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100488 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800489 })
490 return r
491}
Colin Crossfd4f7432019-03-05 15:06:16 -0800492
Liz Kammera3d79152021-10-28 18:14:04 -0400493// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100494func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100495 return r.WithoutMatcher(properties, selectMatcher(value))
496}
497
Liz Kammera3d79152021-10-28 18:14:04 -0400498// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100499func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100501 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100502 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800503 })
504 return r
505}
Colin Crossfd4f7432019-03-05 15:06:16 -0800506
Paul Duffin73bf0542019-07-12 14:12:49 +0100507func selectMatcher(expected string) ValueMatcher {
508 if expected == "*" {
509 return anyMatcherInstance
510 }
511 return &equalMatcher{expected: expected}
512}
513
Liz Kammera3d79152021-10-28 18:14:04 -0400514// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100515func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800516 r.reason = reason
517 return r
518}
519
Liz Kammera3d79152021-10-28 18:14:04 -0400520// BootclasspathJar whether this rule only applies to Jars in the Bootclasspath
Andrei Onea115e7e72020-06-05 21:14:03 +0100521func (r *rule) BootclasspathJar() Rule {
522 r.onlyBootclasspathJar = true
523 return r
524}
525
Steven Moreland65b3fd92017-12-06 14:18:35 -0800526func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400527 s := []string{"neverallow requirements. Not allowed:"}
528 if len(r.paths) > 0 {
529 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800530 }
Liz Kammera3d79152021-10-28 18:14:04 -0400531 if len(r.moduleTypes) > 0 {
532 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800533 }
Liz Kammera3d79152021-10-28 18:14:04 -0400534 if len(r.props) > 0 {
535 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800536 }
Liz Kammera3d79152021-10-28 18:14:04 -0400537 if len(r.directDeps) > 0 {
538 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800539 }
Liz Kammera3d79152021-10-28 18:14:04 -0400540 if len(r.osClasses) > 0 {
541 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100542 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100543 if r.onlyBootclasspathJar {
Liz Kammera3d79152021-10-28 18:14:04 -0400544 s = append(s, "in bootclasspath jar")
545 }
546 if len(r.unlessPaths) > 0 {
547 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
548 }
549 if len(r.unlessModuleTypes) > 0 {
550 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
551 }
552 if len(r.unlessProps) > 0 {
553 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100554 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800555 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400556 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800557 }
Liz Kammera3d79152021-10-28 18:14:04 -0400558 if len(s) == 1 {
559 s[0] = "neverallow requirements (empty)"
560 }
561 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800562}
563
564func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800565 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
566 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800567 return includePath && !excludePath
568}
569
Paul Duffin35781882019-07-25 15:41:09 +0100570func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
571 if len(r.directDeps) == 0 {
572 return true
573 }
574
575 matches := false
576 ctx.VisitDirectDeps(func(m Module) {
577 if !matches {
578 name := ctx.OtherModuleName(m)
579 matches = r.directDeps[name]
580 }
581 })
582
583 return matches
584}
585
Andrei Onea115e7e72020-06-05 21:14:03 +0100586func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
587 if !r.onlyBootclasspathJar {
588 return true
589 }
590
591 return InList(ctx.ModuleName(), ctx.Config().BootJars())
592}
593
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100594func (r *rule) appliesToOsClass(osClass OsClass) bool {
595 if len(r.osClasses) == 0 {
596 return true
597 }
598
599 for _, c := range r.osClasses {
600 if c == osClass {
601 return true
602 }
603 }
604
605 return false
606}
607
Colin Crossfd4f7432019-03-05 15:06:16 -0800608func (r *rule) appliesToModuleType(moduleType string) bool {
609 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
610}
611
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900612func (r *rule) appliesToProperties(ctx ValueMatcherContext,
613 properties []interface{}) bool {
614 includeProps := hasAllProperties(ctx, properties, r.props)
615 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800616 return includeProps && !excludeProps
617}
618
Paul Duffinc8111702019-07-22 12:13:55 +0100619func StartsWith(prefix string) ValueMatcher {
620 return &startsWithMatcher{prefix}
621}
622
Anton Hansson45376402020-04-09 14:18:21 +0100623func Regexp(re string) ValueMatcher {
624 r, err := regexp.Compile(re)
625 if err != nil {
626 panic(err)
627 }
628 return &regexMatcher{r}
629}
630
Andrei Onea115e7e72020-06-05 21:14:03 +0100631func NotInList(allowed []string) ValueMatcher {
632 return &notInListMatcher{allowed}
633}
634
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900635func LessThanSdkVersion(sdk string) ValueMatcher {
636 return &sdkVersionMatcher{
637 condition: func(ctx ValueMatcherContext, spec SdkSpec) bool {
638 return spec.ApiLevel.LessThan(
639 SdkSpecFromWithConfig(ctx.Config(), sdk).ApiLevel)
640 },
641 description: "lessThan=" + sdk,
642 }
643}
644
Steven Moreland65b3fd92017-12-06 14:18:35 -0800645// assorted utils
646
647func cleanPaths(paths []string) []string {
648 res := make([]string, len(paths))
649 for i, v := range paths {
650 res[i] = filepath.Clean(v) + "/"
651 }
652 return res
653}
654
655func fieldNamesForProperties(propertyNames string) []string {
656 names := strings.Split(propertyNames, ".")
657 for i, v := range names {
658 names[i] = proptools.FieldNameForProperty(v)
659 }
660 return names
661}
662
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900663func hasAnyProperty(ctx ValueMatcherContext, properties []interface{},
664 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900666 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800667 return true
668 }
669 }
670 return false
671}
672
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900673func hasAllProperties(ctx ValueMatcherContext, properties []interface{},
674 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800675 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900676 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800677 return false
678 }
679 }
680 return true
681}
682
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900683func hasProperty(ctx ValueMatcherContext, properties []interface{},
684 prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800685 for _, propertyStruct := range properties {
686 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
687 for _, v := range prop.fields {
688 if !propertiesValue.IsValid() {
689 break
690 }
691 propertiesValue = propertiesValue.FieldByName(v)
692 }
693 if !propertiesValue.IsValid() {
694 continue
695 }
696
Paul Duffin73bf0542019-07-12 14:12:49 +0100697 check := func(value string) bool {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900698 return prop.matcher.Test(ctx, value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800699 }
700
701 if matchValue(propertiesValue, check) {
702 return true
703 }
704 }
705 return false
706}
707
708func matchValue(value reflect.Value, check func(string) bool) bool {
709 if !value.IsValid() {
710 return false
711 }
712
713 if value.Kind() == reflect.Ptr {
714 if value.IsNil() {
715 return check("")
716 }
717 value = value.Elem()
718 }
719
720 switch value.Kind() {
721 case reflect.String:
722 return check(value.String())
723 case reflect.Bool:
724 return check(strconv.FormatBool(value.Bool()))
725 case reflect.Int:
726 return check(strconv.FormatInt(value.Int(), 10))
727 case reflect.Slice:
728 slice, ok := value.Interface().([]string)
729 if !ok {
730 panic("Can only handle slice of string")
731 }
732 for _, v := range slice {
733 if check(v) {
734 return true
735 }
736 }
737 return false
738 }
739
740 panic("Can't handle type: " + value.Kind().String())
741}
Paul Duffin115445b2019-08-07 15:31:07 +0100742
743var neverallowRulesKey = NewOnceKey("neverallowRules")
744
745func neverallowRules(config Config) []Rule {
746 return config.Once(neverallowRulesKey, func() interface{} {
747 // No test rules were set by setTestNeverallowRules, use the global rules
748 return neverallows
749 }).([]Rule)
750}
751
752// Overrides the default neverallow rules for the supplied config.
753//
754// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100755func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100756 config.Once(neverallowRulesKey, func() interface{} { return testRules })
757}
Paul Duffin45338f02021-03-30 23:07:52 +0100758
759// Prepares for a test by setting neverallow rules and enabling the mutator.
760//
761// If the supplied rules are nil then the default rules are used.
762func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
763 return GroupFixturePreparers(
764 FixtureModifyConfig(func(config Config) {
765 if testRules != nil {
766 setTestNeverallowRules(config, testRules)
767 }
768 }),
769 FixtureRegisterWithContext(func(ctx RegistrationContext) {
770 ctx.PostDepsMutators(registerNeverallowMutator)
771 }),
772 )
773}