blob: e93763b7b5f906054f26f3effd7fbfd3b110be3c [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) {
Colin Cross8a962802024-10-09 15:29:27 -070047 ctx.BottomUp("neverallow", neverallowMutator)
Steven Moreland65b3fd92017-12-06 14:18:35 -080048}
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()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090059 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Alan Stokes73feba32022-11-14 12:21:24 +000060 AddNeverAllowRules(createCcStubsRule())
Mark Whitea15790a2023-08-22 21:28:11 +000061 AddNeverAllowRules(createProhibitHeaderOnlyRule())
Steven Moreland0db999c2024-09-03 22:06:24 +000062 AddNeverAllowRules(createLimitNdkExportRule()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010063}
Steven Moreland65b3fd92017-12-06 14:18:35 -080064
Paul Duffin730f2a52019-06-27 14:08:51 +010065// Add a NeverAllow rule to the set of rules to apply.
66func AddNeverAllowRules(rules ...Rule) {
67 neverallows = append(neverallows, rules...)
68}
69
Sam Delmerico46d08b42022-11-15 15:51:04 -050070var (
71 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010072 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000073 "art/libnativebridge",
74 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010075 "libcore",
76 "libnativehelper",
77 "external/apache-harmony",
78 "external/apache-xml",
79 "external/boringssl",
80 "external/bouncycastle",
81 "external/conscrypt",
82 "external/icu",
83 "external/okhttp",
84 "external/vixl",
85 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010086 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050087 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000088 "frameworks/av/apex",
89 "frameworks/av/tools",
90 "frameworks/native/cmds",
91 "system/apex",
92 "system/bpf",
93 "system/gatekeeper",
94 "system/hwservicemanager",
95 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000097 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050099)
Paul Duffinc8111702019-07-22 12:13:55 +0100100
Sam Delmerico46d08b42022-11-15 15:51:04 -0500101func createIncludeDirsRules() []Rule {
102 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000103
Sam Delmerico46d08b42022-11-15 15:51:04 -0500104 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100105 rule :=
106 NeverAllow().
107 WithMatcher("include_dirs", StartsWith(path+"/")).
108 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
109 " to use alternate mechanisms and so can no longer be used.")
110
111 rules = append(rules, rule)
112 }
113
Sam Delmerico46d08b42022-11-15 15:51:04 -0500114 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000115 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
116 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
117 " to use alternate mechanisms and so can no longer be used.")
118 rules = append(rules, rule)
119 }
120
Paul Duffinc8111702019-07-22 12:13:55 +0100121 return rules
122}
123
Paul Duffin730f2a52019-06-27 14:08:51 +0100124func createTrebleRules() []Rule {
125 return []Rule{
126 NeverAllow().
127 In("vendor", "device").
128 With("vndk.enabled", "true").
129 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900130 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100131 Because("the VNDK can never contain a library that is device dependent."),
132 NeverAllow().
133 With("vndk.enabled", "true").
134 Without("vendor", "true").
135 Without("owner", "").
136 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800137
Neil Fullerdf5f3562018-10-21 17:19:10 +0100138 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100139 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800140 Without("name", "libhidlbase-combined-impl").
141 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100142 With("product_variables.enforce_vintf_manifest.cflags", "*").
143 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100144
145 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 NeverAllow().
147 Without("name", "libc_bionic_ndk").
148 With("product_variables.treble_linker_namespaces.cflags", "*").
149 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100150
151 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100152 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100153 }
154}
155
Paul Duffin730f2a52019-06-27 14:08:51 +0100156func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700157 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700158 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700159 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400160 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800161 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000162 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000163 "frameworks/base/ravenwood",
164 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000165 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800166 }
167
Paul Duffin730f2a52019-06-27 14:08:51 +0100168 return []Rule{
169 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700170 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100171 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700172 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800173 }
174}
175
Colin Crossc511bc52020-04-07 16:50:32 +0000176func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700177 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000178 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
179 // This sometimes works because the APEX modules that contain derive_sdk and
180 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
181 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100182 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700183 // These are for apps and shouldn't be used by non-SDK variant modules.
184 "prebuilts/ndk",
Jiyong Parka574d532024-08-28 18:06:43 +0900185 "frameworks/native/libs/binder/ndk",
Dan Alberte2054a92020-04-20 14:46:47 -0700186 "tools/test/graphicsbenchmark/apps/sample_app",
187 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700188 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000189 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000190 }
191
Colin Cross440e0d02020-06-11 11:32:11 -0700192 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000193 // android_native_app_glue and libRSSupport use native_window.h but target old
194 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
195 // so they can't add libnativewindow to shared_libs to get the header directory
196 // for the platform variant. Allow them to use the platform variant
197 // property to set shared_libs.
198 "prebuilts/ndk",
199 "frameworks/rs",
200 }
201
202 return []Rule{
203 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700204 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000205 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700206 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000207 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700208 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000209 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700210 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000211 }
212}
213
Alan Stokes73feba32022-11-14 12:21:24 +0000214func createCcStubsRule() Rule {
215 ccStubsImplementationInstallableProjectsAllowedList := []string{
Jiyong Parkf6736c72024-07-22 11:22:35 +0900216 "packages/modules/Virtualization/libs/libvm_payload",
Alan Stokes73feba32022-11-14 12:21:24 +0000217 }
218
219 return NeverAllow().
220 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
221 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
222 Because("implementation_installable can only be used in allowed projects.")
223}
224
David Srbeckye033cba2020-05-20 22:20:28 +0100225func createUncompressDexRules() []Rule {
226 return []Rule{
227 NeverAllow().
228 NotIn("art").
229 WithMatcher("uncompress_dex", isSetMatcherInstance).
230 Because("uncompress_dex is only allowed for certain jars for test in art."),
231 }
232}
233
Inseob Kim800d1142021-06-14 12:03:51 +0900234func createInitFirstStageRules() []Rule {
235 return []Rule{
236 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100237 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900238 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100239 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900240 With("install_in_root", "true").
Inseob Kimbe6a66d2024-07-11 15:43:44 +0900241 NotModuleType("prebuilt_root").
Inseob Kim800d1142021-06-14 12:03:51 +0900242 Because("install_in_root is only for init_first_stage."),
243 }
244}
245
Jiyong Park3c306f32022-04-05 15:29:53 +0900246func createProhibitFrameworkAccessRules() []Rule {
247 return []Rule{
248 NeverAllow().
249 With("libs", "framework").
250 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
251 Because("framework can't be used when building against SDK"),
252 }
253}
254
Mark Whitea15790a2023-08-22 21:28:11 +0000255func createProhibitHeaderOnlyRule() Rule {
256 return NeverAllow().
257 Without("name", "framework-minus-apex-headers").
258 With("headers_only", "true").
259 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
260}
261
Steven Moreland0db999c2024-09-03 22:06:24 +0000262func createLimitNdkExportRule() []Rule {
263 reason := "If the headers you're trying to export are meant to be a part of the NDK, they should be exposed by an ndk_headers module. If the headers shouldn't be a part of the NDK, the headers should instead be exposed from a separate `cc_library_headers` which consumers depend on."
264 // DO NOT ADD HERE - please consult danalbert@
265 // b/357711733
266 return []Rule{
267 NeverAllow().
268 NotIn("frameworks/native/libs/binder/ndk").
269 ModuleType("ndk_library").
270 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
271 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
272 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
273 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
274 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
275 }
276}
277
Steven Moreland65b3fd92017-12-06 14:18:35 -0800278func neverallowMutator(ctx BottomUpMutatorContext) {
279 m, ok := ctx.Module().(Module)
280 if !ok {
281 return
282 }
283
284 dir := ctx.ModuleDir() + "/"
285 properties := m.GetProperties()
286
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100287 osClass := ctx.Module().Target().Os.Class
288
Paul Duffin115445b2019-08-07 15:31:07 +0100289 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100290 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800291 if !n.appliesToPath(dir) {
292 continue
293 }
294
Colin Crossfd4f7432019-03-05 15:06:16 -0800295 if !n.appliesToModuleType(ctx.ModuleType()) {
296 continue
297 }
298
Cole Faust5b35cb92024-08-27 15:47:06 -0700299 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800300 continue
301 }
302
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100303 if !n.appliesToOsClass(osClass) {
304 continue
305 }
306
Paul Duffin35781882019-07-25 15:41:09 +0100307 if !n.appliesToDirectDeps(ctx) {
308 continue
309 }
310
Steven Moreland65b3fd92017-12-06 14:18:35 -0800311 ctx.ModuleErrorf("violates " + n.String())
312 }
313}
314
Paul Duffin73bf0542019-07-12 14:12:49 +0100315type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000316 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100317 String() string
318}
319
320type equalMatcher struct {
321 expected string
322}
323
Anton Hanssone1b18362021-12-23 15:05:38 +0000324func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100325 return m.expected == value
326}
327
328func (m *equalMatcher) String() string {
329 return "=" + m.expected
330}
331
332type anyMatcher struct {
333}
334
Anton Hanssone1b18362021-12-23 15:05:38 +0000335func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100336 return true
337}
338
339func (m *anyMatcher) String() string {
340 return "=*"
341}
342
343var anyMatcherInstance = &anyMatcher{}
344
Paul Duffinc8111702019-07-22 12:13:55 +0100345type startsWithMatcher struct {
346 prefix string
347}
348
Anton Hanssone1b18362021-12-23 15:05:38 +0000349func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100350 return strings.HasPrefix(value, m.prefix)
351}
352
353func (m *startsWithMatcher) String() string {
354 return ".starts-with(" + m.prefix + ")"
355}
356
Anton Hansson45376402020-04-09 14:18:21 +0100357type regexMatcher struct {
358 re *regexp.Regexp
359}
360
Anton Hanssone1b18362021-12-23 15:05:38 +0000361func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100362 return m.re.MatchString(value)
363}
364
365func (m *regexMatcher) String() string {
366 return ".regexp(" + m.re.String() + ")"
367}
368
Andrei Onea115e7e72020-06-05 21:14:03 +0100369type notInListMatcher struct {
370 allowed []string
371}
372
Anton Hanssone1b18362021-12-23 15:05:38 +0000373func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100374 return !InList(value, m.allowed)
375}
376
377func (m *notInListMatcher) String() string {
378 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
379}
380
Colin Crossc511bc52020-04-07 16:50:32 +0000381type isSetMatcher struct{}
382
Anton Hanssone1b18362021-12-23 15:05:38 +0000383func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000384 return value != ""
385}
386
387func (m *isSetMatcher) String() string {
388 return ".is-set"
389}
390
391var isSetMatcherInstance = &isSetMatcher{}
392
Steven Moreland65b3fd92017-12-06 14:18:35 -0800393type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100394 fields []string // e.x.: Vndk.Enabled
395 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800396}
397
Liz Kammera3d79152021-10-28 18:14:04 -0400398func (r *ruleProperty) String() string {
399 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
400}
401
402type ruleProperties []ruleProperty
403
404func (r ruleProperties) String() string {
405 var s []string
406 for _, r := range r {
407 s = append(s, r.String())
408 }
409 return strings.Join(s, " ")
410}
411
Paul Duffin730f2a52019-06-27 14:08:51 +0100412// A NeverAllow rule.
413type Rule interface {
414 In(path ...string) Rule
415
416 NotIn(path ...string) Rule
417
Paul Duffin35781882019-07-25 15:41:09 +0100418 InDirectDeps(deps ...string) Rule
419
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100420 WithOsClass(osClasses ...OsClass) Rule
421
Paul Duffin730f2a52019-06-27 14:08:51 +0100422 ModuleType(types ...string) Rule
423
424 NotModuleType(types ...string) Rule
425
426 With(properties, value string) Rule
427
Paul Duffinc8111702019-07-22 12:13:55 +0100428 WithMatcher(properties string, matcher ValueMatcher) Rule
429
Paul Duffin730f2a52019-06-27 14:08:51 +0100430 Without(properties, value string) Rule
431
Paul Duffinc8111702019-07-22 12:13:55 +0100432 WithoutMatcher(properties string, matcher ValueMatcher) Rule
433
Paul Duffin730f2a52019-06-27 14:08:51 +0100434 Because(reason string) Rule
435}
436
Steven Moreland65b3fd92017-12-06 14:18:35 -0800437type rule struct {
438 // User string for why this is a thing.
439 reason string
440
441 paths []string
442 unlessPaths []string
443
Paul Duffin35781882019-07-25 15:41:09 +0100444 directDeps map[string]bool
445
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100446 osClasses []OsClass
447
Colin Crossfd4f7432019-03-05 15:06:16 -0800448 moduleTypes []string
449 unlessModuleTypes []string
450
Liz Kammera3d79152021-10-28 18:14:04 -0400451 props ruleProperties
452 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100453
454 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800455}
456
Paul Duffin730f2a52019-06-27 14:08:51 +0100457// Create a new NeverAllow rule.
458func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100459 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800460}
Colin Crossfd4f7432019-03-05 15:06:16 -0800461
Liz Kammera3d79152021-10-28 18:14:04 -0400462// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100463func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800464 r.paths = append(r.paths, cleanPaths(path)...)
465 return r
466}
Colin Crossfd4f7432019-03-05 15:06:16 -0800467
Liz Kammera3d79152021-10-28 18:14:04 -0400468// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100469func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800470 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
471 return r
472}
Colin Crossfd4f7432019-03-05 15:06:16 -0800473
Liz Kammera3d79152021-10-28 18:14:04 -0400474// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100475func (r *rule) InDirectDeps(deps ...string) Rule {
476 for _, d := range deps {
477 r.directDeps[d] = true
478 }
479 return r
480}
481
Liz Kammera3d79152021-10-28 18:14:04 -0400482// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100483func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
484 r.osClasses = append(r.osClasses, osClasses...)
485 return r
486}
487
Liz Kammera3d79152021-10-28 18:14:04 -0400488// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100489func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800490 r.moduleTypes = append(r.moduleTypes, types...)
491 return r
492}
493
Liz Kammera3d79152021-10-28 18:14:04 -0400494// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100495func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800496 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
497 return r
498}
499
Liz Kammera3d79152021-10-28 18:14:04 -0400500// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100501func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100502 return r.WithMatcher(properties, selectMatcher(value))
503}
504
Liz Kammera3d79152021-10-28 18:14:04 -0400505// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100506func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800507 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100508 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100509 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800510 })
511 return r
512}
Colin Crossfd4f7432019-03-05 15:06:16 -0800513
Liz Kammera3d79152021-10-28 18:14:04 -0400514// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100515func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100516 return r.WithoutMatcher(properties, selectMatcher(value))
517}
518
Liz Kammera3d79152021-10-28 18:14:04 -0400519// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100520func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800521 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100522 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100523 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524 })
525 return r
526}
Colin Crossfd4f7432019-03-05 15:06:16 -0800527
Paul Duffin73bf0542019-07-12 14:12:49 +0100528func selectMatcher(expected string) ValueMatcher {
529 if expected == "*" {
530 return anyMatcherInstance
531 }
532 return &equalMatcher{expected: expected}
533}
534
Liz Kammera3d79152021-10-28 18:14:04 -0400535// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100536func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 r.reason = reason
538 return r
539}
540
541func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400542 s := []string{"neverallow requirements. Not allowed:"}
543 if len(r.paths) > 0 {
544 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545 }
Liz Kammera3d79152021-10-28 18:14:04 -0400546 if len(r.moduleTypes) > 0 {
547 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800548 }
Liz Kammera3d79152021-10-28 18:14:04 -0400549 if len(r.props) > 0 {
550 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800551 }
Liz Kammera3d79152021-10-28 18:14:04 -0400552 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800553 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800554 }
Liz Kammera3d79152021-10-28 18:14:04 -0400555 if len(r.osClasses) > 0 {
556 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100557 }
Liz Kammera3d79152021-10-28 18:14:04 -0400558 if len(r.unlessPaths) > 0 {
559 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
560 }
561 if len(r.unlessModuleTypes) > 0 {
562 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
563 }
564 if len(r.unlessProps) > 0 {
565 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100566 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800567 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400568 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800569 }
Liz Kammera3d79152021-10-28 18:14:04 -0400570 if len(s) == 1 {
571 s[0] = "neverallow requirements (empty)"
572 }
573 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800574}
575
576func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800577 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
578 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800579 return includePath && !excludePath
580}
581
Paul Duffin35781882019-07-25 15:41:09 +0100582func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
583 if len(r.directDeps) == 0 {
584 return true
585 }
586
587 matches := false
588 ctx.VisitDirectDeps(func(m Module) {
589 if !matches {
590 name := ctx.OtherModuleName(m)
591 matches = r.directDeps[name]
592 }
593 })
594
595 return matches
596}
597
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100598func (r *rule) appliesToOsClass(osClass OsClass) bool {
599 if len(r.osClasses) == 0 {
600 return true
601 }
602
603 for _, c := range r.osClasses {
604 if c == osClass {
605 return true
606 }
607 }
608
609 return false
610}
611
Colin Crossfd4f7432019-03-05 15:06:16 -0800612func (r *rule) appliesToModuleType(moduleType string) bool {
613 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
614}
615
Cole Faust5b35cb92024-08-27 15:47:06 -0700616func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
617 includeProps := hasAllProperties(ctx, properties, r.props)
618 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800619 return includeProps && !excludeProps
620}
621
Paul Duffinc8111702019-07-22 12:13:55 +0100622func StartsWith(prefix string) ValueMatcher {
623 return &startsWithMatcher{prefix}
624}
625
Anton Hansson45376402020-04-09 14:18:21 +0100626func Regexp(re string) ValueMatcher {
627 r, err := regexp.Compile(re)
628 if err != nil {
629 panic(err)
630 }
631 return &regexMatcher{r}
632}
633
Andrei Onea115e7e72020-06-05 21:14:03 +0100634func NotInList(allowed []string) ValueMatcher {
635 return &notInListMatcher{allowed}
636}
637
Steven Moreland65b3fd92017-12-06 14:18:35 -0800638// assorted utils
639
640func cleanPaths(paths []string) []string {
641 res := make([]string, len(paths))
642 for i, v := range paths {
643 res[i] = filepath.Clean(v) + "/"
644 }
645 return res
646}
647
648func fieldNamesForProperties(propertyNames string) []string {
649 names := strings.Split(propertyNames, ".")
650 for i, v := range names {
651 names[i] = proptools.FieldNameForProperty(v)
652 }
653 return names
654}
655
Cole Faust5b35cb92024-08-27 15:47:06 -0700656func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800657 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700658 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800659 return true
660 }
661 }
662 return false
663}
664
Cole Faust5b35cb92024-08-27 15:47:06 -0700665func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800666 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700667 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800668 return false
669 }
670 }
671 return true
672}
673
Cole Faust5b35cb92024-08-27 15:47:06 -0700674func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800675 for _, propertyStruct := range properties {
676 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
677 for _, v := range prop.fields {
678 if !propertiesValue.IsValid() {
679 break
680 }
681 propertiesValue = propertiesValue.FieldByName(v)
682 }
683 if !propertiesValue.IsValid() {
684 continue
685 }
686
Paul Duffin73bf0542019-07-12 14:12:49 +0100687 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000688 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800689 }
690
Cole Faust5b35cb92024-08-27 15:47:06 -0700691 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800692 return true
693 }
694 }
695 return false
696}
697
Cole Faust5b35cb92024-08-27 15:47:06 -0700698func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800699 if !value.IsValid() {
700 return false
701 }
702
703 if value.Kind() == reflect.Ptr {
704 if value.IsNil() {
705 return check("")
706 }
707 value = value.Elem()
708 }
709
Cole Faust5b35cb92024-08-27 15:47:06 -0700710 switch v := value.Interface().(type) {
711 case string:
712 return check(v)
713 case bool:
714 return check(strconv.FormatBool(v))
715 case int:
716 return check(strconv.FormatInt((int64)(v), 10))
717 case []string:
718 for _, v := range v {
719 if check(v) {
720 return true
721 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800722 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700723 return false
724 case proptools.Configurable[string]:
725 return check(v.GetOrDefault(ctx, ""))
726 case proptools.Configurable[bool]:
727 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
728 case proptools.Configurable[[]string]:
729 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800730 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}