blob: 7512da7921f85e1d086976c92062cdd090c103e5 [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
Liz Kammera3d79152021-10-28 18:14:04 -040018 "fmt"
Steven Moreland65b3fd92017-12-06 14:18:35 -080019 "path/filepath"
20 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010021 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080022 "strconv"
23 "strings"
24
25 "github.com/google/blueprint/proptools"
26)
27
28// "neverallow" rules for the build system.
29//
30// This allows things which aren't related to the build system and are enforced
Joe Onoratob4638c12021-10-27 15:47:06 -070031// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080032// straightforward away disjoint from implementations and tests which should
33// work regardless of these restrictions.
34//
35// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010036// - it is in one of the "In" paths
37// - it is not in one of the "NotIn" paths
38// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080039// - - values are matched in their entirety
40// - - nil is interpreted as an empty string
41// - - nested properties are separated with a '.'
42// - - if the property is a list, any of the values in the list being matches
43// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010044// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080045
Paul Duffin45338f02021-03-30 23:07:52 +010046func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080047 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
48}
49
Paul Duffin730f2a52019-06-27 14:08:51 +010050var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080051
Paul Duffin730f2a52019-06-27 14:08:51 +010052func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010053 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010055 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000056 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010057 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070058 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090059 AddNeverAllowRules(createInitFirstStageRules()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010060}
Steven Moreland65b3fd92017-12-06 14:18:35 -080061
Paul Duffin730f2a52019-06-27 14:08:51 +010062// Add a NeverAllow rule to the set of rules to apply.
63func AddNeverAllowRules(rules ...Rule) {
64 neverallows = append(neverallows, rules...)
65}
66
Paul Duffinc8111702019-07-22 12:13:55 +010067func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000068 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010069 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000070 "art/libnativebridge",
71 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010072 "libcore",
73 "libnativehelper",
74 "external/apache-harmony",
75 "external/apache-xml",
76 "external/boringssl",
77 "external/bouncycastle",
78 "external/conscrypt",
79 "external/icu",
80 "external/okhttp",
81 "external/vixl",
82 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010083 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000084 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000085 "frameworks/av/apex",
86 "frameworks/av/tools",
87 "frameworks/native/cmds",
88 "system/apex",
89 "system/bpf",
90 "system/gatekeeper",
91 "system/hwservicemanager",
92 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000093 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000094 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000095 }
Paul Duffinc8111702019-07-22 12:13:55 +010096
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000097 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
98
99 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100100 rule :=
101 NeverAllow().
102 WithMatcher("include_dirs", StartsWith(path+"/")).
103 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
104 " to use alternate mechanisms and so can no longer be used.")
105
106 rules = append(rules, rule)
107 }
108
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000109 for _, path := range noUseIncludeDir {
110 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
111 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
112 " to use alternate mechanisms and so can no longer be used.")
113 rules = append(rules, rule)
114 }
115
Paul Duffinc8111702019-07-22 12:13:55 +0100116 return rules
117}
118
Paul Duffin730f2a52019-06-27 14:08:51 +0100119func createTrebleRules() []Rule {
120 return []Rule{
121 NeverAllow().
122 In("vendor", "device").
123 With("vndk.enabled", "true").
124 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900125 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100126 Because("the VNDK can never contain a library that is device dependent."),
127 NeverAllow().
128 With("vndk.enabled", "true").
129 Without("vendor", "true").
130 Without("owner", "").
131 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800132
Neil Fullerdf5f3562018-10-21 17:19:10 +0100133 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100134 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800135 Without("name", "libhidlbase-combined-impl").
136 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100137 With("product_variables.enforce_vintf_manifest.cflags", "*").
138 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100139
140 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 NeverAllow().
142 Without("name", "libc_bionic_ndk").
143 With("product_variables.treble_linker_namespaces.cflags", "*").
144 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145
146 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148 }
149}
150
Paul Duffin730f2a52019-06-27 14:08:51 +0100151func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700152 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700153 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700154 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800155 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000156 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800157 }
158
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 return []Rule{
160 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700161 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100162 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700163 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800164 }
165}
166
Colin Crossc511bc52020-04-07 16:50:32 +0000167func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700168 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000169 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
170 // This sometimes works because the APEX modules that contain derive_sdk and
171 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
172 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100173 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700174 // These are for apps and shouldn't be used by non-SDK variant modules.
175 "prebuilts/ndk",
176 "tools/test/graphicsbenchmark/apps/sample_app",
177 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700178 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000179 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000180 }
181
Colin Cross440e0d02020-06-11 11:32:11 -0700182 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // android_native_app_glue and libRSSupport use native_window.h but target old
184 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
185 // so they can't add libnativewindow to shared_libs to get the header directory
186 // for the platform variant. Allow them to use the platform variant
187 // property to set shared_libs.
188 "prebuilts/ndk",
189 "frameworks/rs",
190 }
191
192 return []Rule{
193 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700194 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000195 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700196 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000197 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700198 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000199 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700200 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000201 }
202}
203
David Srbeckye033cba2020-05-20 22:20:28 +0100204func createUncompressDexRules() []Rule {
205 return []Rule{
206 NeverAllow().
207 NotIn("art").
208 WithMatcher("uncompress_dex", isSetMatcherInstance).
209 Because("uncompress_dex is only allowed for certain jars for test in art."),
210 }
211}
212
Yifan Hong696ed4d2020-07-27 12:59:58 -0700213func createMakefileGoalRules() []Rule {
214 return []Rule{
215 NeverAllow().
216 ModuleType("makefile_goal").
217 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Inseob Kima9078742021-12-29 08:59:00 +0000218 Because("Only boot images may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700219 }
220}
221
Inseob Kim800d1142021-06-14 12:03:51 +0900222func createInitFirstStageRules() []Rule {
223 return []Rule{
224 NeverAllow().
225 Without("name", "init_first_stage").
226 With("install_in_root", "true").
227 Because("install_in_root is only for init_first_stage."),
228 }
229}
230
Steven Moreland65b3fd92017-12-06 14:18:35 -0800231func neverallowMutator(ctx BottomUpMutatorContext) {
232 m, ok := ctx.Module().(Module)
233 if !ok {
234 return
235 }
236
237 dir := ctx.ModuleDir() + "/"
238 properties := m.GetProperties()
239
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100240 osClass := ctx.Module().Target().Os.Class
241
Paul Duffin115445b2019-08-07 15:31:07 +0100242 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100243 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800244 if !n.appliesToPath(dir) {
245 continue
246 }
247
Colin Crossfd4f7432019-03-05 15:06:16 -0800248 if !n.appliesToModuleType(ctx.ModuleType()) {
249 continue
250 }
251
Anton Hanssone1b18362021-12-23 15:05:38 +0000252 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800253 continue
254 }
255
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100256 if !n.appliesToOsClass(osClass) {
257 continue
258 }
259
Paul Duffin35781882019-07-25 15:41:09 +0100260 if !n.appliesToDirectDeps(ctx) {
261 continue
262 }
263
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
Paul Duffin73bf0542019-07-12 14:12:49 +0100272type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000273 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100274 String() string
275}
276
277type equalMatcher struct {
278 expected string
279}
280
Anton Hanssone1b18362021-12-23 15:05:38 +0000281func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100282 return m.expected == value
283}
284
285func (m *equalMatcher) String() string {
286 return "=" + m.expected
287}
288
289type anyMatcher struct {
290}
291
Anton Hanssone1b18362021-12-23 15:05:38 +0000292func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100293 return true
294}
295
296func (m *anyMatcher) String() string {
297 return "=*"
298}
299
300var anyMatcherInstance = &anyMatcher{}
301
Paul Duffinc8111702019-07-22 12:13:55 +0100302type startsWithMatcher struct {
303 prefix string
304}
305
Anton Hanssone1b18362021-12-23 15:05:38 +0000306func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100307 return strings.HasPrefix(value, m.prefix)
308}
309
310func (m *startsWithMatcher) String() string {
311 return ".starts-with(" + m.prefix + ")"
312}
313
Anton Hansson45376402020-04-09 14:18:21 +0100314type regexMatcher struct {
315 re *regexp.Regexp
316}
317
Anton Hanssone1b18362021-12-23 15:05:38 +0000318func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100319 return m.re.MatchString(value)
320}
321
322func (m *regexMatcher) String() string {
323 return ".regexp(" + m.re.String() + ")"
324}
325
Andrei Onea115e7e72020-06-05 21:14:03 +0100326type notInListMatcher struct {
327 allowed []string
328}
329
Anton Hanssone1b18362021-12-23 15:05:38 +0000330func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100331 return !InList(value, m.allowed)
332}
333
334func (m *notInListMatcher) String() string {
335 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
336}
337
Colin Crossc511bc52020-04-07 16:50:32 +0000338type isSetMatcher struct{}
339
Anton Hanssone1b18362021-12-23 15:05:38 +0000340func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000341 return value != ""
342}
343
344func (m *isSetMatcher) String() string {
345 return ".is-set"
346}
347
348var isSetMatcherInstance = &isSetMatcher{}
349
Steven Moreland65b3fd92017-12-06 14:18:35 -0800350type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100351 fields []string // e.x.: Vndk.Enabled
352 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800353}
354
Liz Kammera3d79152021-10-28 18:14:04 -0400355func (r *ruleProperty) String() string {
356 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
357}
358
359type ruleProperties []ruleProperty
360
361func (r ruleProperties) String() string {
362 var s []string
363 for _, r := range r {
364 s = append(s, r.String())
365 }
366 return strings.Join(s, " ")
367}
368
Paul Duffin730f2a52019-06-27 14:08:51 +0100369// A NeverAllow rule.
370type Rule interface {
371 In(path ...string) Rule
372
373 NotIn(path ...string) Rule
374
Paul Duffin35781882019-07-25 15:41:09 +0100375 InDirectDeps(deps ...string) Rule
376
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100377 WithOsClass(osClasses ...OsClass) Rule
378
Paul Duffin730f2a52019-06-27 14:08:51 +0100379 ModuleType(types ...string) Rule
380
381 NotModuleType(types ...string) Rule
382
Andrei Onea115e7e72020-06-05 21:14:03 +0100383 BootclasspathJar() Rule
384
Paul Duffin730f2a52019-06-27 14:08:51 +0100385 With(properties, value string) Rule
386
Paul Duffinc8111702019-07-22 12:13:55 +0100387 WithMatcher(properties string, matcher ValueMatcher) Rule
388
Paul Duffin730f2a52019-06-27 14:08:51 +0100389 Without(properties, value string) Rule
390
Paul Duffinc8111702019-07-22 12:13:55 +0100391 WithoutMatcher(properties string, matcher ValueMatcher) Rule
392
Paul Duffin730f2a52019-06-27 14:08:51 +0100393 Because(reason string) Rule
394}
395
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396type rule struct {
397 // User string for why this is a thing.
398 reason string
399
400 paths []string
401 unlessPaths []string
402
Paul Duffin35781882019-07-25 15:41:09 +0100403 directDeps map[string]bool
404
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100405 osClasses []OsClass
406
Colin Crossfd4f7432019-03-05 15:06:16 -0800407 moduleTypes []string
408 unlessModuleTypes []string
409
Liz Kammera3d79152021-10-28 18:14:04 -0400410 props ruleProperties
411 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100412
413 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800414}
415
Paul Duffin730f2a52019-06-27 14:08:51 +0100416// Create a new NeverAllow rule.
417func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100418 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419}
Colin Crossfd4f7432019-03-05 15:06:16 -0800420
Liz Kammera3d79152021-10-28 18:14:04 -0400421// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100422func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423 r.paths = append(r.paths, cleanPaths(path)...)
424 return r
425}
Colin Crossfd4f7432019-03-05 15:06:16 -0800426
Liz Kammera3d79152021-10-28 18:14:04 -0400427// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100428func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800429 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
430 return r
431}
Colin Crossfd4f7432019-03-05 15:06:16 -0800432
Liz Kammera3d79152021-10-28 18:14:04 -0400433// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100434func (r *rule) InDirectDeps(deps ...string) Rule {
435 for _, d := range deps {
436 r.directDeps[d] = true
437 }
438 return r
439}
440
Liz Kammera3d79152021-10-28 18:14:04 -0400441// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100442func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
443 r.osClasses = append(r.osClasses, osClasses...)
444 return r
445}
446
Liz Kammera3d79152021-10-28 18:14:04 -0400447// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100448func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800449 r.moduleTypes = append(r.moduleTypes, types...)
450 return r
451}
452
Liz Kammera3d79152021-10-28 18:14:04 -0400453// NotModuleType adds type(s) that this rule does not apply to..
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
Liz Kammera3d79152021-10-28 18:14:04 -0400459// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100460func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100461 return r.WithMatcher(properties, selectMatcher(value))
462}
463
Liz Kammera3d79152021-10-28 18:14:04 -0400464// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100465func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800466 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100467 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100468 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800469 })
470 return r
471}
Colin Crossfd4f7432019-03-05 15:06:16 -0800472
Liz Kammera3d79152021-10-28 18:14:04 -0400473// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100474func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100475 return r.WithoutMatcher(properties, selectMatcher(value))
476}
477
Liz Kammera3d79152021-10-28 18:14:04 -0400478// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100479func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800480 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100481 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100482 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800483 })
484 return r
485}
Colin Crossfd4f7432019-03-05 15:06:16 -0800486
Paul Duffin73bf0542019-07-12 14:12:49 +0100487func selectMatcher(expected string) ValueMatcher {
488 if expected == "*" {
489 return anyMatcherInstance
490 }
491 return &equalMatcher{expected: expected}
492}
493
Liz Kammera3d79152021-10-28 18:14:04 -0400494// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100495func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800496 r.reason = reason
497 return r
498}
499
Liz Kammera3d79152021-10-28 18:14:04 -0400500// BootclasspathJar whether this rule only applies to Jars in the Bootclasspath
Andrei Onea115e7e72020-06-05 21:14:03 +0100501func (r *rule) BootclasspathJar() Rule {
502 r.onlyBootclasspathJar = true
503 return r
504}
505
Steven Moreland65b3fd92017-12-06 14:18:35 -0800506func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400507 s := []string{"neverallow requirements. Not allowed:"}
508 if len(r.paths) > 0 {
509 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800510 }
Liz Kammera3d79152021-10-28 18:14:04 -0400511 if len(r.moduleTypes) > 0 {
512 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 }
Liz Kammera3d79152021-10-28 18:14:04 -0400514 if len(r.props) > 0 {
515 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800516 }
Liz Kammera3d79152021-10-28 18:14:04 -0400517 if len(r.directDeps) > 0 {
518 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800519 }
Liz Kammera3d79152021-10-28 18:14:04 -0400520 if len(r.osClasses) > 0 {
521 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100522 }
Andrei Onea115e7e72020-06-05 21:14:03 +0100523 if r.onlyBootclasspathJar {
Liz Kammera3d79152021-10-28 18:14:04 -0400524 s = append(s, "in bootclasspath jar")
525 }
526 if len(r.unlessPaths) > 0 {
527 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
528 }
529 if len(r.unlessModuleTypes) > 0 {
530 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
531 }
532 if len(r.unlessProps) > 0 {
533 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100534 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800535 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400536 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 }
Liz Kammera3d79152021-10-28 18:14:04 -0400538 if len(s) == 1 {
539 s[0] = "neverallow requirements (empty)"
540 }
541 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542}
543
544func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800545 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
546 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 return includePath && !excludePath
548}
549
Paul Duffin35781882019-07-25 15:41:09 +0100550func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
551 if len(r.directDeps) == 0 {
552 return true
553 }
554
555 matches := false
556 ctx.VisitDirectDeps(func(m Module) {
557 if !matches {
558 name := ctx.OtherModuleName(m)
559 matches = r.directDeps[name]
560 }
561 })
562
563 return matches
564}
565
Andrei Onea115e7e72020-06-05 21:14:03 +0100566func (r *rule) appliesToBootclasspathJar(ctx BottomUpMutatorContext) bool {
567 if !r.onlyBootclasspathJar {
568 return true
569 }
570
571 return InList(ctx.ModuleName(), ctx.Config().BootJars())
572}
573
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100574func (r *rule) appliesToOsClass(osClass OsClass) bool {
575 if len(r.osClasses) == 0 {
576 return true
577 }
578
579 for _, c := range r.osClasses {
580 if c == osClass {
581 return true
582 }
583 }
584
585 return false
586}
587
Colin Crossfd4f7432019-03-05 15:06:16 -0800588func (r *rule) appliesToModuleType(moduleType string) bool {
589 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
590}
591
Anton Hanssone1b18362021-12-23 15:05:38 +0000592func (r *rule) appliesToProperties(properties []interface{}) bool {
593 includeProps := hasAllProperties(properties, r.props)
594 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800595 return includeProps && !excludeProps
596}
597
Paul Duffinc8111702019-07-22 12:13:55 +0100598func StartsWith(prefix string) ValueMatcher {
599 return &startsWithMatcher{prefix}
600}
601
Anton Hansson45376402020-04-09 14:18:21 +0100602func Regexp(re string) ValueMatcher {
603 r, err := regexp.Compile(re)
604 if err != nil {
605 panic(err)
606 }
607 return &regexMatcher{r}
608}
609
Andrei Onea115e7e72020-06-05 21:14:03 +0100610func NotInList(allowed []string) ValueMatcher {
611 return &notInListMatcher{allowed}
612}
613
Steven Moreland65b3fd92017-12-06 14:18:35 -0800614// assorted utils
615
616func cleanPaths(paths []string) []string {
617 res := make([]string, len(paths))
618 for i, v := range paths {
619 res[i] = filepath.Clean(v) + "/"
620 }
621 return res
622}
623
624func fieldNamesForProperties(propertyNames string) []string {
625 names := strings.Split(propertyNames, ".")
626 for i, v := range names {
627 names[i] = proptools.FieldNameForProperty(v)
628 }
629 return names
630}
631
Anton Hanssone1b18362021-12-23 15:05:38 +0000632func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800633 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000634 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800635 return true
636 }
637 }
638 return false
639}
640
Anton Hanssone1b18362021-12-23 15:05:38 +0000641func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800642 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000643 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800644 return false
645 }
646 }
647 return true
648}
649
Anton Hanssone1b18362021-12-23 15:05:38 +0000650func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800651 for _, propertyStruct := range properties {
652 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
653 for _, v := range prop.fields {
654 if !propertiesValue.IsValid() {
655 break
656 }
657 propertiesValue = propertiesValue.FieldByName(v)
658 }
659 if !propertiesValue.IsValid() {
660 continue
661 }
662
Paul Duffin73bf0542019-07-12 14:12:49 +0100663 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000664 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665 }
666
667 if matchValue(propertiesValue, check) {
668 return true
669 }
670 }
671 return false
672}
673
674func matchValue(value reflect.Value, check func(string) bool) bool {
675 if !value.IsValid() {
676 return false
677 }
678
679 if value.Kind() == reflect.Ptr {
680 if value.IsNil() {
681 return check("")
682 }
683 value = value.Elem()
684 }
685
686 switch value.Kind() {
687 case reflect.String:
688 return check(value.String())
689 case reflect.Bool:
690 return check(strconv.FormatBool(value.Bool()))
691 case reflect.Int:
692 return check(strconv.FormatInt(value.Int(), 10))
693 case reflect.Slice:
694 slice, ok := value.Interface().([]string)
695 if !ok {
696 panic("Can only handle slice of string")
697 }
698 for _, v := range slice {
699 if check(v) {
700 return true
701 }
702 }
703 return false
704 }
705
706 panic("Can't handle type: " + value.Kind().String())
707}
Paul Duffin115445b2019-08-07 15:31:07 +0100708
709var neverallowRulesKey = NewOnceKey("neverallowRules")
710
711func neverallowRules(config Config) []Rule {
712 return config.Once(neverallowRulesKey, func() interface{} {
713 // No test rules were set by setTestNeverallowRules, use the global rules
714 return neverallows
715 }).([]Rule)
716}
717
718// Overrides the default neverallow rules for the supplied config.
719//
720// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100721func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100722 config.Once(neverallowRulesKey, func() interface{} { return testRules })
723}
Paul Duffin45338f02021-03-30 23:07:52 +0100724
725// Prepares for a test by setting neverallow rules and enabling the mutator.
726//
727// If the supplied rules are nil then the default rules are used.
728func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
729 return GroupFixturePreparers(
730 FixtureModifyConfig(func(config Config) {
731 if testRules != nil {
732 setTestNeverallowRules(config, testRules)
733 }
734 }),
735 FixtureRegisterWithContext(func(ctx RegistrationContext) {
736 ctx.PostDepsMutators(registerNeverallowMutator)
737 }),
738 )
739}