blob: 439fe2df801213ffe788e2925a5c7190bdbc63d9 [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()...)
Inseob Kim76e19852024-10-10 17:57:22 +090063 AddNeverAllowRules(createLimitDirgroupRule()...)
Jihoon Kang0d545b82024-10-11 00:21:57 +000064 AddNeverAllowRules(createFilesystemIsAutoGeneratedRule())
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
Mark Whitea15790a2023-08-22 21:28:11 +0000257func createProhibitHeaderOnlyRule() Rule {
258 return NeverAllow().
259 Without("name", "framework-minus-apex-headers").
260 With("headers_only", "true").
261 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
262}
263
Steven Moreland0db999c2024-09-03 22:06:24 +0000264func createLimitNdkExportRule() []Rule {
265 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."
266 // DO NOT ADD HERE - please consult danalbert@
267 // b/357711733
268 return []Rule{
269 NeverAllow().
270 NotIn("frameworks/native/libs/binder/ndk").
271 ModuleType("ndk_library").
272 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
273 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
274 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
275 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
276 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
277 }
278}
279
Inseob Kim76e19852024-10-10 17:57:22 +0900280func createLimitDirgroupRule() []Rule {
281 reason := "dirgroup module and dir_srcs property of genrule is allowed only to Trusty build rule."
282 return []Rule{
283 NeverAllow().
284 ModuleType("dirgroup").
285 WithMatcher("visibility", NotInList([]string{"//trusty/vendor/google/aosp/scripts"})).Because(reason),
286 NeverAllow().
287 ModuleType("dirgroup").
288 Without("visibility", "//trusty/vendor/google/aosp/scripts").Because(reason),
289 NeverAllow().
290 ModuleType("genrule").
291 Without("name", "lk.elf.arm64").
292 Without("name", "lk.elf.x86_64").
293 WithMatcher("dir_srcs", isSetMatcherInstance).Because(reason),
294 }
295}
296
Jihoon Kang0d545b82024-10-11 00:21:57 +0000297func createFilesystemIsAutoGeneratedRule() Rule {
298 return NeverAllow().
299 NotIn("build/soong/fsgen").
300 ModuleType("filesystem", "android_system_image").
301 WithMatcher("is_auto_generated", isSetMatcherInstance).
302 Because("is_auto_generated property is only allowed for filesystem modules in build/soong/fsgen directory")
303}
304
Steven Moreland65b3fd92017-12-06 14:18:35 -0800305func neverallowMutator(ctx BottomUpMutatorContext) {
306 m, ok := ctx.Module().(Module)
307 if !ok {
308 return
309 }
310
311 dir := ctx.ModuleDir() + "/"
312 properties := m.GetProperties()
313
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100314 osClass := ctx.Module().Target().Os.Class
315
Paul Duffin115445b2019-08-07 15:31:07 +0100316 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100317 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800318 if !n.appliesToPath(dir) {
319 continue
320 }
321
Colin Crossfd4f7432019-03-05 15:06:16 -0800322 if !n.appliesToModuleType(ctx.ModuleType()) {
323 continue
324 }
325
Cole Faust5b35cb92024-08-27 15:47:06 -0700326 if !n.appliesToProperties(ctx, properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800327 continue
328 }
329
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100330 if !n.appliesToOsClass(osClass) {
331 continue
332 }
333
Paul Duffin35781882019-07-25 15:41:09 +0100334 if !n.appliesToDirectDeps(ctx) {
335 continue
336 }
337
Steven Moreland65b3fd92017-12-06 14:18:35 -0800338 ctx.ModuleErrorf("violates " + n.String())
339 }
340}
341
Paul Duffin73bf0542019-07-12 14:12:49 +0100342type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000343 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100344 String() string
345}
346
347type equalMatcher struct {
348 expected string
349}
350
Anton Hanssone1b18362021-12-23 15:05:38 +0000351func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100352 return m.expected == value
353}
354
355func (m *equalMatcher) String() string {
356 return "=" + m.expected
357}
358
359type anyMatcher struct {
360}
361
Anton Hanssone1b18362021-12-23 15:05:38 +0000362func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100363 return true
364}
365
366func (m *anyMatcher) String() string {
367 return "=*"
368}
369
370var anyMatcherInstance = &anyMatcher{}
371
Paul Duffinc8111702019-07-22 12:13:55 +0100372type startsWithMatcher struct {
373 prefix string
374}
375
Anton Hanssone1b18362021-12-23 15:05:38 +0000376func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100377 return strings.HasPrefix(value, m.prefix)
378}
379
380func (m *startsWithMatcher) String() string {
381 return ".starts-with(" + m.prefix + ")"
382}
383
Anton Hansson45376402020-04-09 14:18:21 +0100384type regexMatcher struct {
385 re *regexp.Regexp
386}
387
Anton Hanssone1b18362021-12-23 15:05:38 +0000388func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100389 return m.re.MatchString(value)
390}
391
392func (m *regexMatcher) String() string {
393 return ".regexp(" + m.re.String() + ")"
394}
395
Andrei Onea115e7e72020-06-05 21:14:03 +0100396type notInListMatcher struct {
397 allowed []string
398}
399
Anton Hanssone1b18362021-12-23 15:05:38 +0000400func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100401 return !InList(value, m.allowed)
402}
403
404func (m *notInListMatcher) String() string {
405 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
406}
407
Colin Crossc511bc52020-04-07 16:50:32 +0000408type isSetMatcher struct{}
409
Anton Hanssone1b18362021-12-23 15:05:38 +0000410func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000411 return value != ""
412}
413
414func (m *isSetMatcher) String() string {
415 return ".is-set"
416}
417
418var isSetMatcherInstance = &isSetMatcher{}
419
Steven Moreland65b3fd92017-12-06 14:18:35 -0800420type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100421 fields []string // e.x.: Vndk.Enabled
422 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423}
424
Liz Kammera3d79152021-10-28 18:14:04 -0400425func (r *ruleProperty) String() string {
426 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
427}
428
429type ruleProperties []ruleProperty
430
431func (r ruleProperties) String() string {
432 var s []string
433 for _, r := range r {
434 s = append(s, r.String())
435 }
436 return strings.Join(s, " ")
437}
438
Paul Duffin730f2a52019-06-27 14:08:51 +0100439// A NeverAllow rule.
440type Rule interface {
441 In(path ...string) Rule
442
443 NotIn(path ...string) Rule
444
Paul Duffin35781882019-07-25 15:41:09 +0100445 InDirectDeps(deps ...string) Rule
446
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100447 WithOsClass(osClasses ...OsClass) Rule
448
Paul Duffin730f2a52019-06-27 14:08:51 +0100449 ModuleType(types ...string) Rule
450
451 NotModuleType(types ...string) Rule
452
453 With(properties, value string) Rule
454
Paul Duffinc8111702019-07-22 12:13:55 +0100455 WithMatcher(properties string, matcher ValueMatcher) Rule
456
Paul Duffin730f2a52019-06-27 14:08:51 +0100457 Without(properties, value string) Rule
458
Paul Duffinc8111702019-07-22 12:13:55 +0100459 WithoutMatcher(properties string, matcher ValueMatcher) Rule
460
Paul Duffin730f2a52019-06-27 14:08:51 +0100461 Because(reason string) Rule
462}
463
Steven Moreland65b3fd92017-12-06 14:18:35 -0800464type rule struct {
465 // User string for why this is a thing.
466 reason string
467
468 paths []string
469 unlessPaths []string
470
Paul Duffin35781882019-07-25 15:41:09 +0100471 directDeps map[string]bool
472
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100473 osClasses []OsClass
474
Colin Crossfd4f7432019-03-05 15:06:16 -0800475 moduleTypes []string
476 unlessModuleTypes []string
477
Liz Kammera3d79152021-10-28 18:14:04 -0400478 props ruleProperties
479 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100480
481 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800482}
483
Paul Duffin730f2a52019-06-27 14:08:51 +0100484// Create a new NeverAllow rule.
485func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100486 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487}
Colin Crossfd4f7432019-03-05 15:06:16 -0800488
Liz Kammera3d79152021-10-28 18:14:04 -0400489// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100490func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800491 r.paths = append(r.paths, cleanPaths(path)...)
492 return r
493}
Colin Crossfd4f7432019-03-05 15:06:16 -0800494
Liz Kammera3d79152021-10-28 18:14:04 -0400495// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100496func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
498 return r
499}
Colin Crossfd4f7432019-03-05 15:06:16 -0800500
Liz Kammera3d79152021-10-28 18:14:04 -0400501// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100502func (r *rule) InDirectDeps(deps ...string) Rule {
503 for _, d := range deps {
504 r.directDeps[d] = true
505 }
506 return r
507}
508
Liz Kammera3d79152021-10-28 18:14:04 -0400509// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100510func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
511 r.osClasses = append(r.osClasses, osClasses...)
512 return r
513}
514
Liz Kammera3d79152021-10-28 18:14:04 -0400515// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100516func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800517 r.moduleTypes = append(r.moduleTypes, types...)
518 return r
519}
520
Liz Kammera3d79152021-10-28 18:14:04 -0400521// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100522func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800523 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
524 return r
525}
526
Liz Kammera3d79152021-10-28 18:14:04 -0400527// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100528func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100529 return r.WithMatcher(properties, selectMatcher(value))
530}
531
Liz Kammera3d79152021-10-28 18:14:04 -0400532// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100533func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800534 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100535 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100536 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 })
538 return r
539}
Colin Crossfd4f7432019-03-05 15:06:16 -0800540
Liz Kammera3d79152021-10-28 18:14:04 -0400541// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100542func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100543 return r.WithoutMatcher(properties, selectMatcher(value))
544}
545
Liz Kammera3d79152021-10-28 18:14:04 -0400546// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100547func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800548 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100549 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100550 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800551 })
552 return r
553}
Colin Crossfd4f7432019-03-05 15:06:16 -0800554
Paul Duffin73bf0542019-07-12 14:12:49 +0100555func selectMatcher(expected string) ValueMatcher {
556 if expected == "*" {
557 return anyMatcherInstance
558 }
559 return &equalMatcher{expected: expected}
560}
561
Liz Kammera3d79152021-10-28 18:14:04 -0400562// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100563func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800564 r.reason = reason
565 return r
566}
567
568func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400569 s := []string{"neverallow requirements. Not allowed:"}
570 if len(r.paths) > 0 {
571 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800572 }
Liz Kammera3d79152021-10-28 18:14:04 -0400573 if len(r.moduleTypes) > 0 {
574 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800575 }
Liz Kammera3d79152021-10-28 18:14:04 -0400576 if len(r.props) > 0 {
577 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800578 }
Liz Kammera3d79152021-10-28 18:14:04 -0400579 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800580 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800581 }
Liz Kammera3d79152021-10-28 18:14:04 -0400582 if len(r.osClasses) > 0 {
583 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100584 }
Liz Kammera3d79152021-10-28 18:14:04 -0400585 if len(r.unlessPaths) > 0 {
586 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
587 }
588 if len(r.unlessModuleTypes) > 0 {
589 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
590 }
591 if len(r.unlessProps) > 0 {
592 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100593 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800594 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400595 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800596 }
Liz Kammera3d79152021-10-28 18:14:04 -0400597 if len(s) == 1 {
598 s[0] = "neverallow requirements (empty)"
599 }
600 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800601}
602
603func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800604 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
605 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800606 return includePath && !excludePath
607}
608
Paul Duffin35781882019-07-25 15:41:09 +0100609func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
610 if len(r.directDeps) == 0 {
611 return true
612 }
613
614 matches := false
615 ctx.VisitDirectDeps(func(m Module) {
616 if !matches {
617 name := ctx.OtherModuleName(m)
618 matches = r.directDeps[name]
619 }
620 })
621
622 return matches
623}
624
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100625func (r *rule) appliesToOsClass(osClass OsClass) bool {
626 if len(r.osClasses) == 0 {
627 return true
628 }
629
630 for _, c := range r.osClasses {
631 if c == osClass {
632 return true
633 }
634 }
635
636 return false
637}
638
Colin Crossfd4f7432019-03-05 15:06:16 -0800639func (r *rule) appliesToModuleType(moduleType string) bool {
640 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
641}
642
Cole Faust5b35cb92024-08-27 15:47:06 -0700643func (r *rule) appliesToProperties(ctx BottomUpMutatorContext, properties []interface{}) bool {
644 includeProps := hasAllProperties(ctx, properties, r.props)
645 excludeProps := hasAnyProperty(ctx, properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 return includeProps && !excludeProps
647}
648
Paul Duffinc8111702019-07-22 12:13:55 +0100649func StartsWith(prefix string) ValueMatcher {
650 return &startsWithMatcher{prefix}
651}
652
Anton Hansson45376402020-04-09 14:18:21 +0100653func Regexp(re string) ValueMatcher {
654 r, err := regexp.Compile(re)
655 if err != nil {
656 panic(err)
657 }
658 return &regexMatcher{r}
659}
660
Andrei Onea115e7e72020-06-05 21:14:03 +0100661func NotInList(allowed []string) ValueMatcher {
662 return &notInListMatcher{allowed}
663}
664
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665// assorted utils
666
667func cleanPaths(paths []string) []string {
668 res := make([]string, len(paths))
669 for i, v := range paths {
670 res[i] = filepath.Clean(v) + "/"
671 }
672 return res
673}
674
675func fieldNamesForProperties(propertyNames string) []string {
676 names := strings.Split(propertyNames, ".")
677 for i, v := range names {
678 names[i] = proptools.FieldNameForProperty(v)
679 }
680 return names
681}
682
Cole Faust5b35cb92024-08-27 15:47:06 -0700683func hasAnyProperty(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800684 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700685 if hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800686 return true
687 }
688 }
689 return false
690}
691
Cole Faust5b35cb92024-08-27 15:47:06 -0700692func hasAllProperties(ctx BottomUpMutatorContext, properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800693 for _, v := range props {
Cole Faust5b35cb92024-08-27 15:47:06 -0700694 if !hasProperty(ctx, properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800695 return false
696 }
697 }
698 return true
699}
700
Cole Faust5b35cb92024-08-27 15:47:06 -0700701func hasProperty(ctx BottomUpMutatorContext, properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800702 for _, propertyStruct := range properties {
703 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
704 for _, v := range prop.fields {
705 if !propertiesValue.IsValid() {
706 break
707 }
708 propertiesValue = propertiesValue.FieldByName(v)
709 }
710 if !propertiesValue.IsValid() {
711 continue
712 }
713
Paul Duffin73bf0542019-07-12 14:12:49 +0100714 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000715 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800716 }
717
Cole Faust5b35cb92024-08-27 15:47:06 -0700718 if matchValue(ctx, propertiesValue, check) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800719 return true
720 }
721 }
722 return false
723}
724
Cole Faust5b35cb92024-08-27 15:47:06 -0700725func matchValue(ctx BottomUpMutatorContext, value reflect.Value, check func(string) bool) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800726 if !value.IsValid() {
727 return false
728 }
729
730 if value.Kind() == reflect.Ptr {
731 if value.IsNil() {
732 return check("")
733 }
734 value = value.Elem()
735 }
736
Cole Faust5b35cb92024-08-27 15:47:06 -0700737 switch v := value.Interface().(type) {
738 case string:
739 return check(v)
740 case bool:
741 return check(strconv.FormatBool(v))
742 case int:
743 return check(strconv.FormatInt((int64)(v), 10))
744 case []string:
745 for _, v := range v {
746 if check(v) {
747 return true
748 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800749 }
Cole Faust5b35cb92024-08-27 15:47:06 -0700750 return false
751 case proptools.Configurable[string]:
752 return check(v.GetOrDefault(ctx, ""))
753 case proptools.Configurable[bool]:
754 return check(strconv.FormatBool(v.GetOrDefault(ctx, false)))
755 case proptools.Configurable[[]string]:
756 for _, v := range v.GetOrDefault(ctx, nil) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800757 if check(v) {
758 return true
759 }
760 }
761 return false
762 }
763
764 panic("Can't handle type: " + value.Kind().String())
765}
Paul Duffin115445b2019-08-07 15:31:07 +0100766
767var neverallowRulesKey = NewOnceKey("neverallowRules")
768
769func neverallowRules(config Config) []Rule {
770 return config.Once(neverallowRulesKey, func() interface{} {
771 // No test rules were set by setTestNeverallowRules, use the global rules
772 return neverallows
773 }).([]Rule)
774}
775
776// Overrides the default neverallow rules for the supplied config.
777//
778// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100779func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100780 config.Once(neverallowRulesKey, func() interface{} { return testRules })
781}
Paul Duffin45338f02021-03-30 23:07:52 +0100782
783// Prepares for a test by setting neverallow rules and enabling the mutator.
784//
785// If the supplied rules are nil then the default rules are used.
786func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
787 return GroupFixturePreparers(
788 FixtureModifyConfig(func(config Config) {
789 if testRules != nil {
790 setTestNeverallowRules(config, testRules)
791 }
792 }),
793 FixtureRegisterWithContext(func(ctx RegistrationContext) {
794 ctx.PostDepsMutators(registerNeverallowMutator)
795 }),
796 )
797}