blob: 6f9ae58d004f2081132a4af59229c1aafb91c126 [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
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900252 if !n.appliesToProperties(ctx, 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
Andrei Onea115e7e72020-06-05 21:14:03 +0100264 if !n.appliesToBootclasspathJar(ctx) {
265 continue
266 }
267
Steven Moreland65b3fd92017-12-06 14:18:35 -0800268 ctx.ModuleErrorf("violates " + n.String())
269 }
270}
271
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900272type ValueMatcherContext interface {
273 Config() Config
274}
275
Paul Duffin73bf0542019-07-12 14:12:49 +0100276type ValueMatcher interface {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900277 Test(ValueMatcherContext, string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100278 String() string
279}
280
281type equalMatcher struct {
282 expected string
283}
284
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900285func (m *equalMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100286 return m.expected == value
287}
288
289func (m *equalMatcher) String() string {
290 return "=" + m.expected
291}
292
293type anyMatcher struct {
294}
295
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900296func (m *anyMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100297 return true
298}
299
300func (m *anyMatcher) String() string {
301 return "=*"
302}
303
304var anyMatcherInstance = &anyMatcher{}
305
Paul Duffinc8111702019-07-22 12:13:55 +0100306type startsWithMatcher struct {
307 prefix string
308}
309
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900310func (m *startsWithMatcher) Test(ctx ValueMatcherContext, value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100311 return strings.HasPrefix(value, m.prefix)
312}
313
314func (m *startsWithMatcher) String() string {
315 return ".starts-with(" + m.prefix + ")"
316}
317
Anton Hansson45376402020-04-09 14:18:21 +0100318type regexMatcher struct {
319 re *regexp.Regexp
320}
321
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900322func (m *regexMatcher) Test(ctx ValueMatcherContext, value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100323 return m.re.MatchString(value)
324}
325
326func (m *regexMatcher) String() string {
327 return ".regexp(" + m.re.String() + ")"
328}
329
Andrei Onea115e7e72020-06-05 21:14:03 +0100330type notInListMatcher struct {
331 allowed []string
332}
333
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900334func (m *notInListMatcher) Test(ctx ValueMatcherContext, value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100335 return !InList(value, m.allowed)
336}
337
338func (m *notInListMatcher) String() string {
339 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
340}
341
Colin Crossc511bc52020-04-07 16:50:32 +0000342type isSetMatcher struct{}
343
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900344func (m *isSetMatcher) Test(ctx ValueMatcherContext, value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000345 return value != ""
346}
347
348func (m *isSetMatcher) String() string {
349 return ".is-set"
350}
351
352var isSetMatcherInstance = &isSetMatcher{}
353
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900354type sdkVersionMatcher struct {
355 condition func(ctx ValueMatcherContext, spec SdkSpec) bool
356 description string
357}
358
359func (m *sdkVersionMatcher) Test(ctx ValueMatcherContext, value string) bool {
360 return m.condition(ctx, SdkSpecFromWithConfig(ctx.Config(), value))
361}
362
363func (m *sdkVersionMatcher) String() string {
364 return ".sdk-version(" + m.description + ")"
365}
366
Steven Moreland65b3fd92017-12-06 14:18:35 -0800367type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100368 fields []string // e.x.: Vndk.Enabled
369 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370}
371
Liz Kammera3d79152021-10-28 18:14:04 -0400372func (r *ruleProperty) String() string {
373 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
374}
375
376type ruleProperties []ruleProperty
377
378func (r ruleProperties) String() string {
379 var s []string
380 for _, r := range r {
381 s = append(s, r.String())
382 }
383 return strings.Join(s, " ")
384}
385
Paul Duffin730f2a52019-06-27 14:08:51 +0100386// A NeverAllow rule.
387type Rule interface {
388 In(path ...string) Rule
389
390 NotIn(path ...string) Rule
391
Paul Duffin35781882019-07-25 15:41:09 +0100392 InDirectDeps(deps ...string) Rule
393
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100394 WithOsClass(osClasses ...OsClass) Rule
395
Paul Duffin730f2a52019-06-27 14:08:51 +0100396 ModuleType(types ...string) Rule
397
398 NotModuleType(types ...string) Rule
399
Andrei Onea115e7e72020-06-05 21:14:03 +0100400 BootclasspathJar() Rule
401
Paul Duffin730f2a52019-06-27 14:08:51 +0100402 With(properties, value string) Rule
403
Paul Duffinc8111702019-07-22 12:13:55 +0100404 WithMatcher(properties string, matcher ValueMatcher) Rule
405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406 Without(properties, value string) Rule
407
Paul Duffinc8111702019-07-22 12:13:55 +0100408 WithoutMatcher(properties string, matcher ValueMatcher) Rule
409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410 Because(reason string) Rule
411}
412
Steven Moreland65b3fd92017-12-06 14:18:35 -0800413type rule struct {
414 // User string for why this is a thing.
415 reason string
416
417 paths []string
418 unlessPaths []string
419
Paul Duffin35781882019-07-25 15:41:09 +0100420 directDeps map[string]bool
421
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100422 osClasses []OsClass
423
Colin Crossfd4f7432019-03-05 15:06:16 -0800424 moduleTypes []string
425 unlessModuleTypes []string
426
Liz Kammera3d79152021-10-28 18:14:04 -0400427 props ruleProperties
428 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100429
430 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800431}
432
Paul Duffin730f2a52019-06-27 14:08:51 +0100433// Create a new NeverAllow rule.
434func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100435 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800436}
Colin Crossfd4f7432019-03-05 15:06:16 -0800437
Liz Kammera3d79152021-10-28 18:14:04 -0400438// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100439func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800440 r.paths = append(r.paths, cleanPaths(path)...)
441 return r
442}
Colin Crossfd4f7432019-03-05 15:06:16 -0800443
Liz Kammera3d79152021-10-28 18:14:04 -0400444// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100445func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800446 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
447 return r
448}
Colin Crossfd4f7432019-03-05 15:06:16 -0800449
Liz Kammera3d79152021-10-28 18:14:04 -0400450// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100451func (r *rule) InDirectDeps(deps ...string) Rule {
452 for _, d := range deps {
453 r.directDeps[d] = true
454 }
455 return r
456}
457
Liz Kammera3d79152021-10-28 18:14:04 -0400458// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100459func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
460 r.osClasses = append(r.osClasses, osClasses...)
461 return r
462}
463
Liz Kammera3d79152021-10-28 18:14:04 -0400464// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100465func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800466 r.moduleTypes = append(r.moduleTypes, types...)
467 return r
468}
469
Liz Kammera3d79152021-10-28 18:14:04 -0400470// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100471func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800472 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
473 return r
474}
475
Liz Kammera3d79152021-10-28 18:14:04 -0400476// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100477func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100478 return r.WithMatcher(properties, selectMatcher(value))
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100482func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800483 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100484 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100485 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486 })
487 return r
488}
Colin Crossfd4f7432019-03-05 15:06:16 -0800489
Liz Kammera3d79152021-10-28 18:14:04 -0400490// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100491func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100492 return r.WithoutMatcher(properties, selectMatcher(value))
493}
494
Liz Kammera3d79152021-10-28 18:14:04 -0400495// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100496func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100498 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100499 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 })
501 return r
502}
Colin Crossfd4f7432019-03-05 15:06:16 -0800503
Paul Duffin73bf0542019-07-12 14:12:49 +0100504func selectMatcher(expected string) ValueMatcher {
505 if expected == "*" {
506 return anyMatcherInstance
507 }
508 return &equalMatcher{expected: expected}
509}
510
Liz Kammera3d79152021-10-28 18:14:04 -0400511// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100512func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 r.reason = reason
514 return r
515}
516
Liz Kammera3d79152021-10-28 18:14:04 -0400517// BootclasspathJar whether this rule only applies to Jars in the Bootclasspath
Andrei Onea115e7e72020-06-05 21:14:03 +0100518func (r *rule) BootclasspathJar() Rule {
519 r.onlyBootclasspathJar = true
520 return r
521}
522
Steven Moreland65b3fd92017-12-06 14:18:35 -0800523func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400524 s := []string{"neverallow requirements. Not allowed:"}
525 if len(r.paths) > 0 {
526 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800527 }
Liz Kammera3d79152021-10-28 18:14:04 -0400528 if len(r.moduleTypes) > 0 {
529 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800530 }
Liz Kammera3d79152021-10-28 18:14:04 -0400531 if len(r.props) > 0 {
532 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800533 }
Liz Kammera3d79152021-10-28 18:14:04 -0400534 if len(r.directDeps) > 0 {
535 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800536 }
Liz Kammera3d79152021-10-28 18:14:04 -0400537 if len(r.osClasses) > 0 {
538 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100539 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100540 if r.onlyBootclasspathJar {
Liz Kammera3d79152021-10-28 18:14:04 -0400541 s = append(s, "in bootclasspath jar")
542 }
543 if len(r.unlessPaths) > 0 {
544 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
545 }
546 if len(r.unlessModuleTypes) > 0 {
547 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
548 }
549 if len(r.unlessProps) > 0 {
550 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100551 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800552 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400553 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800554 }
Liz Kammera3d79152021-10-28 18:14:04 -0400555 if len(s) == 1 {
556 s[0] = "neverallow requirements (empty)"
557 }
558 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800559}
560
561func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800562 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
563 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800564 return includePath && !excludePath
565}
566
Paul Duffin35781882019-07-25 15:41:09 +0100567func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
568 if len(r.directDeps) == 0 {
569 return true
570 }
571
572 matches := false
573 ctx.VisitDirectDeps(func(m Module) {
574 if !matches {
575 name := ctx.OtherModuleName(m)
576 matches = r.directDeps[name]
577 }
578 })
579
580 return matches
581}
582
Andrei Onea115e7e72020-06-05 21:14:03 +0100583func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
584 if !r.onlyBootclasspathJar {
585 return true
586 }
587
588 return InList(ctx.ModuleName(), ctx.Config().BootJars())
589}
590
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100591func (r *rule) appliesToOsClass(osClass OsClass) bool {
592 if len(r.osClasses) == 0 {
593 return true
594 }
595
596 for _, c := range r.osClasses {
597 if c == osClass {
598 return true
599 }
600 }
601
602 return false
603}
604
Colin Crossfd4f7432019-03-05 15:06:16 -0800605func (r *rule) appliesToModuleType(moduleType string) bool {
606 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
607}
608
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900609func (r *rule) appliesToProperties(ctx ValueMatcherContext,
610 properties []interface{}) bool {
611 includeProps := hasAllProperties(ctx, properties, r.props)
612 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800613 return includeProps && !excludeProps
614}
615
Paul Duffinc8111702019-07-22 12:13:55 +0100616func StartsWith(prefix string) ValueMatcher {
617 return &startsWithMatcher{prefix}
618}
619
Anton Hansson45376402020-04-09 14:18:21 +0100620func Regexp(re string) ValueMatcher {
621 r, err := regexp.Compile(re)
622 if err != nil {
623 panic(err)
624 }
625 return &regexMatcher{r}
626}
627
Andrei Onea115e7e72020-06-05 21:14:03 +0100628func NotInList(allowed []string) ValueMatcher {
629 return &notInListMatcher{allowed}
630}
631
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900632func LessThanSdkVersion(sdk string) ValueMatcher {
633 return &sdkVersionMatcher{
634 condition: func(ctx ValueMatcherContext, spec SdkSpec) bool {
635 return spec.ApiLevel.LessThan(
636 SdkSpecFromWithConfig(ctx.Config(), sdk).ApiLevel)
637 },
638 description: "lessThan=" + sdk,
639 }
640}
641
Steven Moreland65b3fd92017-12-06 14:18:35 -0800642// assorted utils
643
644func cleanPaths(paths []string) []string {
645 res := make([]string, len(paths))
646 for i, v := range paths {
647 res[i] = filepath.Clean(v) + "/"
648 }
649 return res
650}
651
652func fieldNamesForProperties(propertyNames string) []string {
653 names := strings.Split(propertyNames, ".")
654 for i, v := range names {
655 names[i] = proptools.FieldNameForProperty(v)
656 }
657 return names
658}
659
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900660func hasAnyProperty(ctx ValueMatcherContext, properties []interface{},
661 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800662 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900663 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800664 return true
665 }
666 }
667 return false
668}
669
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900670func hasAllProperties(ctx ValueMatcherContext, properties []interface{},
671 props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800672 for _, v := range props {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900673 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800674 return false
675 }
676 }
677 return true
678}
679
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900680func hasProperty(ctx ValueMatcherContext, properties []interface{},
681 prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800682 for _, propertyStruct := range properties {
683 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
684 for _, v := range prop.fields {
685 if !propertiesValue.IsValid() {
686 break
687 }
688 propertiesValue = propertiesValue.FieldByName(v)
689 }
690 if !propertiesValue.IsValid() {
691 continue
692 }
693
Paul Duffin73bf0542019-07-12 14:12:49 +0100694 check := func(value string) bool {
Remi NGUYEN VAN1fdd6ca2021-12-02 19:39:35 +0900695 return prop.matcher.Test(ctx, value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800696 }
697
698 if matchValue(propertiesValue, check) {
699 return true
700 }
701 }
702 return false
703}
704
705func matchValue(value reflect.Value, check func(string) bool) bool {
706 if !value.IsValid() {
707 return false
708 }
709
710 if value.Kind() == reflect.Ptr {
711 if value.IsNil() {
712 return check("")
713 }
714 value = value.Elem()
715 }
716
717 switch value.Kind() {
718 case reflect.String:
719 return check(value.String())
720 case reflect.Bool:
721 return check(strconv.FormatBool(value.Bool()))
722 case reflect.Int:
723 return check(strconv.FormatInt(value.Int(), 10))
724 case reflect.Slice:
725 slice, ok := value.Interface().([]string)
726 if !ok {
727 panic("Can only handle slice of string")
728 }
729 for _, v := range slice {
730 if check(v) {
731 return true
732 }
733 }
734 return false
735 }
736
737 panic("Can't handle type: " + value.Kind().String())
738}
Paul Duffin115445b2019-08-07 15:31:07 +0100739
740var neverallowRulesKey = NewOnceKey("neverallowRules")
741
742func neverallowRules(config Config) []Rule {
743 return config.Once(neverallowRulesKey, func() interface{} {
744 // No test rules were set by setTestNeverallowRules, use the global rules
745 return neverallows
746 }).([]Rule)
747}
748
749// Overrides the default neverallow rules for the supplied config.
750//
751// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100752func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100753 config.Once(neverallowRulesKey, func() interface{} { return testRules })
754}
Paul Duffin45338f02021-03-30 23:07:52 +0100755
756// Prepares for a test by setting neverallow rules and enabling the mutator.
757//
758// If the supplied rules are nil then the default rules are used.
759func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
760 return GroupFixturePreparers(
761 FixtureModifyConfig(func(config Config) {
762 if testRules != nil {
763 setTestNeverallowRules(config, testRules)
764 }
765 }),
766 FixtureRegisterWithContext(func(ctx RegistrationContext) {
767 ctx.PostDepsMutators(registerNeverallowMutator)
768 }),
769 )
770}