blob: 00095ad64b184ab4903371f997ead583ab5265c4 [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()...)
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())
Jihoon Kang381c2fa2023-06-01 22:17:32 +000061 AddNeverAllowRules(createJavaExcludeStaticLibsRule())
Mark Whitea15790a2023-08-22 21:28:11 +000062 AddNeverAllowRules(createProhibitHeaderOnlyRule())
Steven Moreland0db999c2024-09-03 22:06:24 +000063 AddNeverAllowRules(createLimitNdkExportRule()...)
Luca Stefania3efe922024-10-12 17:55:31 +020064 AddNeverAllowRules(createKotlinPluginRule()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010065}
Steven Moreland65b3fd92017-12-06 14:18:35 -080066
Paul Duffin730f2a52019-06-27 14:08:51 +010067// Add a NeverAllow rule to the set of rules to apply.
68func AddNeverAllowRules(rules ...Rule) {
69 neverallows = append(neverallows, rules...)
70}
71
Sam Delmerico46d08b42022-11-15 15:51:04 -050072var (
73 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010074 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000075 "art/libnativebridge",
76 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010077 "libcore",
78 "libnativehelper",
79 "external/apache-harmony",
80 "external/apache-xml",
81 "external/boringssl",
82 "external/bouncycastle",
83 "external/conscrypt",
84 "external/icu",
85 "external/okhttp",
86 "external/vixl",
87 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010088 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050089 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000090 "frameworks/av/apex",
91 "frameworks/av/tools",
92 "frameworks/native/cmds",
93 "system/apex",
94 "system/bpf",
95 "system/gatekeeper",
96 "system/hwservicemanager",
97 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000099 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000100 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500101)
Paul Duffinc8111702019-07-22 12:13:55 +0100102
Sam Delmerico46d08b42022-11-15 15:51:04 -0500103func createIncludeDirsRules() []Rule {
104 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000105
Sam Delmerico46d08b42022-11-15 15:51:04 -0500106 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100107 rule :=
108 NeverAllow().
109 WithMatcher("include_dirs", StartsWith(path+"/")).
110 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
111 " to use alternate mechanisms and so can no longer be used.")
112
113 rules = append(rules, rule)
114 }
115
Sam Delmerico46d08b42022-11-15 15:51:04 -0500116 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000117 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
118 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
119 " to use alternate mechanisms and so can no longer be used.")
120 rules = append(rules, rule)
121 }
122
Paul Duffinc8111702019-07-22 12:13:55 +0100123 return rules
124}
125
Paul Duffin730f2a52019-06-27 14:08:51 +0100126func createTrebleRules() []Rule {
127 return []Rule{
128 NeverAllow().
129 In("vendor", "device").
130 With("vndk.enabled", "true").
131 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900132 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100133 Because("the VNDK can never contain a library that is device dependent."),
134 NeverAllow().
135 With("vndk.enabled", "true").
136 Without("vendor", "true").
137 Without("owner", "").
138 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800139
Neil Fullerdf5f3562018-10-21 17:19:10 +0100140 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100141 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800142 Without("name", "libhidlbase-combined-impl").
143 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100144 With("product_variables.enforce_vintf_manifest.cflags", "*").
145 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146
147 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100148 NeverAllow().
149 Without("name", "libc_bionic_ndk").
150 With("product_variables.treble_linker_namespaces.cflags", "*").
151 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100152
153 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100154 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100155 }
156}
157
Paul Duffin730f2a52019-06-27 14:08:51 +0100158func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700159 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700160 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700161 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400162 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800163 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000164 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000165 "frameworks/base/ravenwood",
166 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000167 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800168 }
169
Paul Duffin730f2a52019-06-27 14:08:51 +0100170 return []Rule{
171 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700172 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100173 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700174 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800175 }
176}
177
Colin Crossc511bc52020-04-07 16:50:32 +0000178func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700179 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000180 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
181 // This sometimes works because the APEX modules that contain derive_sdk and
182 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
183 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100184 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700185 // These are for apps and shouldn't be used by non-SDK variant modules.
186 "prebuilts/ndk",
Jiyong Parka574d532024-08-28 18:06:43 +0900187 "frameworks/native/libs/binder/ndk",
Dan Alberte2054a92020-04-20 14:46:47 -0700188 "tools/test/graphicsbenchmark/apps/sample_app",
189 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700190 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000191 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000192 }
193
Colin Cross440e0d02020-06-11 11:32:11 -0700194 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000195 // android_native_app_glue and libRSSupport use native_window.h but target old
196 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
197 // so they can't add libnativewindow to shared_libs to get the header directory
198 // for the platform variant. Allow them to use the platform variant
199 // property to set shared_libs.
200 "prebuilts/ndk",
201 "frameworks/rs",
202 }
203
204 return []Rule{
205 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700206 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000207 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700208 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000209 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700210 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000211 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700212 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000213 }
214}
215
Alan Stokes73feba32022-11-14 12:21:24 +0000216func createCcStubsRule() Rule {
217 ccStubsImplementationInstallableProjectsAllowedList := []string{
Jiyong Parkf6736c72024-07-22 11:22:35 +0900218 "packages/modules/Virtualization/libs/libvm_payload",
Alan Stokes73feba32022-11-14 12:21:24 +0000219 }
220
221 return NeverAllow().
222 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
223 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
224 Because("implementation_installable can only be used in allowed projects.")
225}
226
David Srbeckye033cba2020-05-20 22:20:28 +0100227func createUncompressDexRules() []Rule {
228 return []Rule{
229 NeverAllow().
230 NotIn("art").
231 WithMatcher("uncompress_dex", isSetMatcherInstance).
232 Because("uncompress_dex is only allowed for certain jars for test in art."),
233 }
234}
235
Inseob Kim800d1142021-06-14 12:03:51 +0900236func createInitFirstStageRules() []Rule {
237 return []Rule{
238 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100239 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900240 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100241 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900242 With("install_in_root", "true").
Inseob Kimbe6a66d2024-07-11 15:43:44 +0900243 NotModuleType("prebuilt_root").
Inseob Kim800d1142021-06-14 12:03:51 +0900244 Because("install_in_root is only for init_first_stage."),
245 }
246}
247
Jiyong Park3c306f32022-04-05 15:29:53 +0900248func createProhibitFrameworkAccessRules() []Rule {
249 return []Rule{
250 NeverAllow().
251 With("libs", "framework").
252 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
253 Because("framework can't be used when building against SDK"),
254 }
255}
256
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000257func createJavaExcludeStaticLibsRule() Rule {
258 return NeverAllow().
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000259 NotIn("build/soong", "libcore", "frameworks/base/api").
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000260 ModuleType("java_library").
261 WithMatcher("exclude_static_libs", isSetMatcherInstance).
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000262 Because("exclude_static_libs property is only allowed for java modules defined in build/soong, libcore, and frameworks/base/api")
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000263}
264
Mark Whitea15790a2023-08-22 21:28:11 +0000265func createProhibitHeaderOnlyRule() Rule {
266 return NeverAllow().
267 Without("name", "framework-minus-apex-headers").
268 With("headers_only", "true").
269 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
270}
271
Steven Moreland0db999c2024-09-03 22:06:24 +0000272func createLimitNdkExportRule() []Rule {
273 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."
274 // DO NOT ADD HERE - please consult danalbert@
275 // b/357711733
276 return []Rule{
277 NeverAllow().
278 NotIn("frameworks/native/libs/binder/ndk").
279 ModuleType("ndk_library").
280 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
281 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
282 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
283 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
284 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
Luca Stefania3efe922024-10-12 17:55:31 +0200285 }
286}
287func createKotlinPluginRule() []Rule {
288 kotlinPluginProjectsAllowedList := []string{
289 // TODO: Migrate compose plugin to the bundled compiler plugin
290 // Actual path prebuilts/sdk/current/androidx/m2repository/androidx/compose/compiler/compiler-hosted
291 "prebuilts/sdk/current/androidx",
292 "external/kotlinc",
Luca Stefaniad0d7bb2024-11-02 11:45:21 +0100293 "vendor/bliss/kotlin",
Luca Stefania3efe922024-10-12 17:55:31 +0200294 }
295
296 return []Rule{
297 NeverAllow().
298 NotIn(kotlinPluginProjectsAllowedList...).
299 ModuleType("kotlin_plugin").
300 Because("kotlin_plugin can only be used in allowed projects"),
Steven Moreland0db999c2024-09-03 22:06:24 +0000301 }
302}
303
Steven Moreland65b3fd92017-12-06 14:18:35 -0800304func neverallowMutator(ctx BottomUpMutatorContext) {
305 m, ok := ctx.Module().(Module)
306 if !ok {
307 return
308 }
309
310 dir := ctx.ModuleDir() + "/"
311 properties := m.GetProperties()
312
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100313 osClass := ctx.Module().Target().Os.Class
314
Paul Duffin115445b2019-08-07 15:31:07 +0100315 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100316 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800317 if !n.appliesToPath(dir) {
318 continue
319 }
320
Colin Crossfd4f7432019-03-05 15:06:16 -0800321 if !n.appliesToModuleType(ctx.ModuleType()) {
322 continue
323 }
324
Cole Faust5b35cb92024-08-27 15:47:06 -0700325 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800326 continue
327 }
328
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100329 if !n.appliesToOsClass(osClass) {
330 continue
331 }
332
Paul Duffin35781882019-07-25 15:41:09 +0100333 if !n.appliesToDirectDeps(ctx) {
334 continue
335 }
336
Steven Moreland65b3fd92017-12-06 14:18:35 -0800337 ctx.ModuleErrorf("violates " + n.String())
338 }
339}
340
Paul Duffin73bf0542019-07-12 14:12:49 +0100341type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000342 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100343 String() string
344}
345
346type equalMatcher struct {
347 expected string
348}
349
Anton Hanssone1b18362021-12-23 15:05:38 +0000350func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100351 return m.expected == value
352}
353
354func (m *equalMatcher) String() string {
355 return "=" + m.expected
356}
357
358type anyMatcher struct {
359}
360
Anton Hanssone1b18362021-12-23 15:05:38 +0000361func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100362 return true
363}
364
365func (m *anyMatcher) String() string {
366 return "=*"
367}
368
369var anyMatcherInstance = &anyMatcher{}
370
Paul Duffinc8111702019-07-22 12:13:55 +0100371type startsWithMatcher struct {
372 prefix string
373}
374
Anton Hanssone1b18362021-12-23 15:05:38 +0000375func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100376 return strings.HasPrefix(value, m.prefix)
377}
378
379func (m *startsWithMatcher) String() string {
380 return ".starts-with(" + m.prefix + ")"
381}
382
Anton Hansson45376402020-04-09 14:18:21 +0100383type regexMatcher struct {
384 re *regexp.Regexp
385}
386
Anton Hanssone1b18362021-12-23 15:05:38 +0000387func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100388 return m.re.MatchString(value)
389}
390
391func (m *regexMatcher) String() string {
392 return ".regexp(" + m.re.String() + ")"
393}
394
Andrei Onea115e7e72020-06-05 21:14:03 +0100395type notInListMatcher struct {
396 allowed []string
397}
398
Anton Hanssone1b18362021-12-23 15:05:38 +0000399func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100400 return !InList(value, m.allowed)
401}
402
403func (m *notInListMatcher) String() string {
404 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
405}
406
Colin Crossc511bc52020-04-07 16:50:32 +0000407type isSetMatcher struct{}
408
Anton Hanssone1b18362021-12-23 15:05:38 +0000409func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000410 return value != ""
411}
412
413func (m *isSetMatcher) String() string {
414 return ".is-set"
415}
416
417var isSetMatcherInstance = &isSetMatcher{}
418
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100420 fields []string // e.x.: Vndk.Enabled
421 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800422}
423
Liz Kammera3d79152021-10-28 18:14:04 -0400424func (r *ruleProperty) String() string {
425 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
426}
427
428type ruleProperties []ruleProperty
429
430func (r ruleProperties) String() string {
431 var s []string
432 for _, r := range r {
433 s = append(s, r.String())
434 }
435 return strings.Join(s, " ")
436}
437
Paul Duffin730f2a52019-06-27 14:08:51 +0100438// A NeverAllow rule.
439type Rule interface {
440 In(path ...string) Rule
441
442 NotIn(path ...string) Rule
443
Paul Duffin35781882019-07-25 15:41:09 +0100444 InDirectDeps(deps ...string) Rule
445
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100446 WithOsClass(osClasses ...OsClass) Rule
447
Paul Duffin730f2a52019-06-27 14:08:51 +0100448 ModuleType(types ...string) Rule
449
450 NotModuleType(types ...string) Rule
451
452 With(properties, value string) Rule
453
Paul Duffinc8111702019-07-22 12:13:55 +0100454 WithMatcher(properties string, matcher ValueMatcher) Rule
455
Paul Duffin730f2a52019-06-27 14:08:51 +0100456 Without(properties, value string) Rule
457
Paul Duffinc8111702019-07-22 12:13:55 +0100458 WithoutMatcher(properties string, matcher ValueMatcher) Rule
459
Paul Duffin730f2a52019-06-27 14:08:51 +0100460 Because(reason string) Rule
461}
462
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463type rule struct {
464 // User string for why this is a thing.
465 reason string
466
467 paths []string
468 unlessPaths []string
469
Paul Duffin35781882019-07-25 15:41:09 +0100470 directDeps map[string]bool
471
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100472 osClasses []OsClass
473
Colin Crossfd4f7432019-03-05 15:06:16 -0800474 moduleTypes []string
475 unlessModuleTypes []string
476
Liz Kammera3d79152021-10-28 18:14:04 -0400477 props ruleProperties
478 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100479
480 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800481}
482
Paul Duffin730f2a52019-06-27 14:08:51 +0100483// Create a new NeverAllow rule.
484func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100485 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486}
Colin Crossfd4f7432019-03-05 15:06:16 -0800487
Liz Kammera3d79152021-10-28 18:14:04 -0400488// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100489func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800490 r.paths = append(r.paths, cleanPaths(path)...)
491 return r
492}
Colin Crossfd4f7432019-03-05 15:06:16 -0800493
Liz Kammera3d79152021-10-28 18:14:04 -0400494// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100495func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800496 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
497 return r
498}
Colin Crossfd4f7432019-03-05 15:06:16 -0800499
Liz Kammera3d79152021-10-28 18:14:04 -0400500// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100501func (r *rule) InDirectDeps(deps ...string) Rule {
502 for _, d := range deps {
503 r.directDeps[d] = true
504 }
505 return r
506}
507
Liz Kammera3d79152021-10-28 18:14:04 -0400508// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100509func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
510 r.osClasses = append(r.osClasses, osClasses...)
511 return r
512}
513
Liz Kammera3d79152021-10-28 18:14:04 -0400514// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100515func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800516 r.moduleTypes = append(r.moduleTypes, types...)
517 return r
518}
519
Liz Kammera3d79152021-10-28 18:14:04 -0400520// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100521func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800522 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
523 return r
524}
525
Liz Kammera3d79152021-10-28 18:14:04 -0400526// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100527func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100528 return r.WithMatcher(properties, selectMatcher(value))
529}
530
Liz Kammera3d79152021-10-28 18:14:04 -0400531// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100532func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800533 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100534 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100535 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800536 })
537 return r
538}
Colin Crossfd4f7432019-03-05 15:06:16 -0800539
Liz Kammera3d79152021-10-28 18:14:04 -0400540// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100541func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100542 return r.WithoutMatcher(properties, selectMatcher(value))
543}
544
Liz Kammera3d79152021-10-28 18:14:04 -0400545// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100546func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100548 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100549 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800550 })
551 return r
552}
Colin Crossfd4f7432019-03-05 15:06:16 -0800553
Paul Duffin73bf0542019-07-12 14:12:49 +0100554func selectMatcher(expected string) ValueMatcher {
555 if expected == "*" {
556 return anyMatcherInstance
557 }
558 return &equalMatcher{expected: expected}
559}
560
Liz Kammera3d79152021-10-28 18:14:04 -0400561// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100562func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800563 r.reason = reason
564 return r
565}
566
567func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400568 s := []string{"neverallow requirements. Not allowed:"}
569 if len(r.paths) > 0 {
570 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800571 }
Liz Kammera3d79152021-10-28 18:14:04 -0400572 if len(r.moduleTypes) > 0 {
573 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800574 }
Liz Kammera3d79152021-10-28 18:14:04 -0400575 if len(r.props) > 0 {
576 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800577 }
Liz Kammera3d79152021-10-28 18:14:04 -0400578 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800579 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800580 }
Liz Kammera3d79152021-10-28 18:14:04 -0400581 if len(r.osClasses) > 0 {
582 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100583 }
Liz Kammera3d79152021-10-28 18:14:04 -0400584 if len(r.unlessPaths) > 0 {
585 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
586 }
587 if len(r.unlessModuleTypes) > 0 {
588 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
589 }
590 if len(r.unlessProps) > 0 {
591 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100592 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800593 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400594 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800595 }
Liz Kammera3d79152021-10-28 18:14:04 -0400596 if len(s) == 1 {
597 s[0] = "neverallow requirements (empty)"
598 }
599 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800600}
601
602func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800603 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
604 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800605 return includePath && !excludePath
606}
607
Paul Duffin35781882019-07-25 15:41:09 +0100608func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
609 if len(r.directDeps) == 0 {
610 return true
611 }
612
613 matches := false
614 ctx.VisitDirectDeps(func(m Module) {
615 if !matches {
616 name := ctx.OtherModuleName(m)
617 matches = r.directDeps[name]
618 }
619 })
620
621 return matches
622}
623
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100624func (r *rule) appliesToOsClass(osClass OsClass) bool {
625 if len(r.osClasses) == 0 {
626 return true
627 }
628
629 for _, c := range r.osClasses {
630 if c == osClass {
631 return true
632 }
633 }
634
635 return false
636}
637
Colin Crossfd4f7432019-03-05 15:06:16 -0800638func (r *rule) appliesToModuleType(moduleType string) bool {
639 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
640}
641
Cole Faust5b35cb92024-08-27 15:47:06 -0700642func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
643 includeProps := hasAllProperties(ctx, properties, r.props)
644 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800645 return includeProps && !excludeProps
646}
647
Paul Duffinc8111702019-07-22 12:13:55 +0100648func StartsWith(prefix string) ValueMatcher {
649 return &startsWithMatcher{prefix}
650}
651
Anton Hansson45376402020-04-09 14:18:21 +0100652func Regexp(re string) ValueMatcher {
653 r, err := regexp.Compile(re)
654 if err != nil {
655 panic(err)
656 }
657 return &regexMatcher{r}
658}
659
Andrei Onea115e7e72020-06-05 21:14:03 +0100660func NotInList(allowed []string) ValueMatcher {
661 return &notInListMatcher{allowed}
662}
663
Steven Moreland65b3fd92017-12-06 14:18:35 -0800664// assorted utils
665
666func cleanPaths(paths []string) []string {
667 res := make([]string, len(paths))
668 for i, v := range paths {
669 res[i] = filepath.Clean(v) + "/"
670 }
671 return res
672}
673
674func fieldNamesForProperties(propertyNames string) []string {
675 names := strings.Split(propertyNames, ".")
676 for i, v := range names {
677 names[i] = proptools.FieldNameForProperty(v)
678 }
679 return names
680}
681
Cole Faust5b35cb92024-08-27 15:47:06 -0700682func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800683 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700684 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800685 return true
686 }
687 }
688 return false
689}
690
Cole Faust5b35cb92024-08-27 15:47:06 -0700691func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800692 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700693 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800694 return false
695 }
696 }
697 return true
698}
699
Cole Faust5b35cb92024-08-27 15:47:06 -0700700func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800701 for _, propertyStruct := range properties {
702 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
703 for _, v := range prop.fields {
704 if !propertiesValue.IsValid() {
705 break
706 }
707 propertiesValue = propertiesValue.FieldByName(v)
708 }
709 if !propertiesValue.IsValid() {
710 continue
711 }
712
Paul Duffin73bf0542019-07-12 14:12:49 +0100713 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000714 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800715 }
716
Cole Faust5b35cb92024-08-27 15:47:06 -0700717 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800718 return true
719 }
720 }
721 return false
722}
723
Cole Faust5b35cb92024-08-27 15:47:06 -0700724func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800725 if !value.IsValid() {
726 return false
727 }
728
729 if value.Kind() == reflect.Ptr {
730 if value.IsNil() {
731 return check("")
732 }
733 value = value.Elem()
734 }
735
Cole Faust5b35cb92024-08-27 15:47:06 -0700736 switch v := value.Interface().(type) {
737 case string:
738 return check(v)
739 case bool:
740 return check(strconv.FormatBool(v))
741 case int:
742 return check(strconv.FormatInt((int64)(v), 10))
743 case []string:
744 for _, v := range v {
745 if check(v) {
746 return true
747 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800748 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700749 return false
750 case proptools.Configurable[string]:
751 return check(v.GetOrDefault(ctx, ""))
752 case proptools.Configurable[bool]:
753 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
754 case proptools.Configurable[[]string]:
755 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800756 if check(v) {
757 return true
758 }
759 }
760 return false
761 }
762
763 panic("Can't handle type: " + value.Kind().String())
764}
Paul Duffin115445b2019-08-07 15:31:07 +0100765
766var neverallowRulesKey = NewOnceKey("neverallowRules")
767
768func neverallowRules(config Config) []Rule {
769 return config.Once(neverallowRulesKey, func() interface{} {
770 // No test rules were set by setTestNeverallowRules, use the global rules
771 return neverallows
772 }).([]Rule)
773}
774
775// Overrides the default neverallow rules for the supplied config.
776//
777// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100778func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100779 config.Once(neverallowRulesKey, func() interface{} { return testRules })
780}
Paul Duffin45338f02021-03-30 23:07:52 +0100781
782// Prepares for a test by setting neverallow rules and enabling the mutator.
783//
784// If the supplied rules are nil then the default rules are used.
785func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
786 return GroupFixturePreparers(
787 FixtureModifyConfig(func(config Config) {
788 if testRules != nil {
789 setTestNeverallowRules(config, testRules)
790 }
791 }),
792 FixtureRegisterWithContext(func(ctx RegistrationContext) {
793 ctx.PostDepsMutators(registerNeverallowMutator)
794 }),
795 )
796}