blob: 7f6999dfa845f8d68659d87c0d1e567068dfabea [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()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010064}
Steven Moreland65b3fd92017-12-06 14:18:35 -080065
Paul Duffin730f2a52019-06-27 14:08:51 +010066// Add a NeverAllow rule to the set of rules to apply.
67func AddNeverAllowRules(rules ...Rule) {
68 neverallows = append(neverallows, rules...)
69}
70
Sam Delmerico46d08b42022-11-15 15:51:04 -050071var (
72 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010073 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000074 "art/libnativebridge",
75 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010076 "libcore",
77 "libnativehelper",
78 "external/apache-harmony",
79 "external/apache-xml",
80 "external/boringssl",
81 "external/bouncycastle",
82 "external/conscrypt",
83 "external/icu",
84 "external/okhttp",
85 "external/vixl",
86 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010087 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050088 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000089 "frameworks/av/apex",
90 "frameworks/av/tools",
91 "frameworks/native/cmds",
92 "system/apex",
93 "system/bpf",
94 "system/gatekeeper",
95 "system/hwservicemanager",
96 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000097 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000098 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000099 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500100)
Paul Duffinc8111702019-07-22 12:13:55 +0100101
Sam Delmerico46d08b42022-11-15 15:51:04 -0500102func createIncludeDirsRules() []Rule {
103 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000104
Sam Delmerico46d08b42022-11-15 15:51:04 -0500105 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100106 rule :=
107 NeverAllow().
108 WithMatcher("include_dirs", StartsWith(path+"/")).
109 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
110 " to use alternate mechanisms and so can no longer be used.")
111
112 rules = append(rules, rule)
113 }
114
Sam Delmerico46d08b42022-11-15 15:51:04 -0500115 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000116 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
117 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
118 " to use alternate mechanisms and so can no longer be used.")
119 rules = append(rules, rule)
120 }
121
Paul Duffinc8111702019-07-22 12:13:55 +0100122 return rules
123}
124
Paul Duffin730f2a52019-06-27 14:08:51 +0100125func createTrebleRules() []Rule {
126 return []Rule{
127 NeverAllow().
128 In("vendor", "device").
129 With("vndk.enabled", "true").
130 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900131 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100132 Because("the VNDK can never contain a library that is device dependent."),
133 NeverAllow().
134 With("vndk.enabled", "true").
135 Without("vendor", "true").
136 Without("owner", "").
137 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800138
Neil Fullerdf5f3562018-10-21 17:19:10 +0100139 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100140 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800141 Without("name", "libhidlbase-combined-impl").
142 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100143 With("product_variables.enforce_vintf_manifest.cflags", "*").
144 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145
146 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 NeverAllow().
148 Without("name", "libc_bionic_ndk").
149 With("product_variables.treble_linker_namespaces.cflags", "*").
150 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100151
152 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100153 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100154 }
155}
156
Paul Duffin730f2a52019-06-27 14:08:51 +0100157func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700158 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700159 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700160 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400161 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800162 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000163 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000164 "frameworks/base/ravenwood",
165 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000166 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800167 }
168
Paul Duffin730f2a52019-06-27 14:08:51 +0100169 return []Rule{
170 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700171 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100172 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700173 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800174 }
175}
176
Colin Crossc511bc52020-04-07 16:50:32 +0000177func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700178 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000179 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
180 // This sometimes works because the APEX modules that contain derive_sdk and
181 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
182 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100183 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700184 // These are for apps and shouldn't be used by non-SDK variant modules.
185 "prebuilts/ndk",
186 "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
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000255func createJavaExcludeStaticLibsRule() Rule {
256 return NeverAllow().
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000257 NotIn("build/soong", "libcore", "frameworks/base/api").
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000258 ModuleType("java_library").
259 WithMatcher("exclude_static_libs", isSetMatcherInstance).
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000260 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 +0000261}
262
Mark Whitea15790a2023-08-22 21:28:11 +0000263func createProhibitHeaderOnlyRule() Rule {
264 return NeverAllow().
265 Without("name", "framework-minus-apex-headers").
266 With("headers_only", "true").
267 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
268}
269
Steven Moreland0db999c2024-09-03 22:06:24 +0000270func createLimitNdkExportRule() []Rule {
271 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."
272 // DO NOT ADD HERE - please consult danalbert@
273 // b/357711733
274 return []Rule{
275 NeverAllow().
276 NotIn("frameworks/native/libs/binder/ndk").
277 ModuleType("ndk_library").
278 WithMatcher("export_header_libs", isSetMatcherInstance).Because(reason),
279 NeverAllow().ModuleType("ndk_library").WithMatcher("export_generated_headers", isSetMatcherInstance).Because(reason),
280 NeverAllow().ModuleType("ndk_library").WithMatcher("export_include_dirs", isSetMatcherInstance).Because(reason),
281 NeverAllow().ModuleType("ndk_library").WithMatcher("export_shared_lib_headers", isSetMatcherInstance).Because(reason),
282 NeverAllow().ModuleType("ndk_library").WithMatcher("export_static_lib_headers", isSetMatcherInstance).Because(reason),
283 }
284}
285
Steven Moreland65b3fd92017-12-06 14:18:35 -0800286func neverallowMutator(ctx BottomUpMutatorContext) {
287 m, ok := ctx.Module().(Module)
288 if !ok {
289 return
290 }
291
292 dir := ctx.ModuleDir() + "/"
293 properties := m.GetProperties()
294
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100295 osClass := ctx.Module().Target().Os.Class
296
Paul Duffin115445b2019-08-07 15:31:07 +0100297 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100298 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800299 if !n.appliesToPath(dir) {
300 continue
301 }
302
Colin Crossfd4f7432019-03-05 15:06:16 -0800303 if !n.appliesToModuleType(ctx.ModuleType()) {
304 continue
305 }
306
Anton Hanssone1b18362021-12-23 15:05:38 +0000307 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800308 continue
309 }
310
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100311 if !n.appliesToOsClass(osClass) {
312 continue
313 }
314
Paul Duffin35781882019-07-25 15:41:09 +0100315 if !n.appliesToDirectDeps(ctx) {
316 continue
317 }
318
Steven Moreland65b3fd92017-12-06 14:18:35 -0800319 ctx.ModuleErrorf("violates " + n.String())
320 }
321}
322
Paul Duffin73bf0542019-07-12 14:12:49 +0100323type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000324 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100325 String() string
326}
327
328type equalMatcher struct {
329 expected string
330}
331
Anton Hanssone1b18362021-12-23 15:05:38 +0000332func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100333 return m.expected == value
334}
335
336func (m *equalMatcher) String() string {
337 return "=" + m.expected
338}
339
340type anyMatcher struct {
341}
342
Anton Hanssone1b18362021-12-23 15:05:38 +0000343func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100344 return true
345}
346
347func (m *anyMatcher) String() string {
348 return "=*"
349}
350
351var anyMatcherInstance = &anyMatcher{}
352
Paul Duffinc8111702019-07-22 12:13:55 +0100353type startsWithMatcher struct {
354 prefix string
355}
356
Anton Hanssone1b18362021-12-23 15:05:38 +0000357func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100358 return strings.HasPrefix(value, m.prefix)
359}
360
361func (m *startsWithMatcher) String() string {
362 return ".starts-with(" + m.prefix + ")"
363}
364
Anton Hansson45376402020-04-09 14:18:21 +0100365type regexMatcher struct {
366 re *regexp.Regexp
367}
368
Anton Hanssone1b18362021-12-23 15:05:38 +0000369func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100370 return m.re.MatchString(value)
371}
372
373func (m *regexMatcher) String() string {
374 return ".regexp(" + m.re.String() + ")"
375}
376
Andrei Onea115e7e72020-06-05 21:14:03 +0100377type notInListMatcher struct {
378 allowed []string
379}
380
Anton Hanssone1b18362021-12-23 15:05:38 +0000381func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100382 return !InList(value, m.allowed)
383}
384
385func (m *notInListMatcher) String() string {
386 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
387}
388
Colin Crossc511bc52020-04-07 16:50:32 +0000389type isSetMatcher struct{}
390
Anton Hanssone1b18362021-12-23 15:05:38 +0000391func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000392 return value != ""
393}
394
395func (m *isSetMatcher) String() string {
396 return ".is-set"
397}
398
399var isSetMatcherInstance = &isSetMatcher{}
400
Steven Moreland65b3fd92017-12-06 14:18:35 -0800401type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100402 fields []string // e.x.: Vndk.Enabled
403 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800404}
405
Liz Kammera3d79152021-10-28 18:14:04 -0400406func (r *ruleProperty) String() string {
407 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
408}
409
410type ruleProperties []ruleProperty
411
412func (r ruleProperties) String() string {
413 var s []string
414 for _, r := range r {
415 s = append(s, r.String())
416 }
417 return strings.Join(s, " ")
418}
419
Paul Duffin730f2a52019-06-27 14:08:51 +0100420// A NeverAllow rule.
421type Rule interface {
422 In(path ...string) Rule
423
424 NotIn(path ...string) Rule
425
Paul Duffin35781882019-07-25 15:41:09 +0100426 InDirectDeps(deps ...string) Rule
427
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100428 WithOsClass(osClasses ...OsClass) Rule
429
Paul Duffin730f2a52019-06-27 14:08:51 +0100430 ModuleType(types ...string) Rule
431
432 NotModuleType(types ...string) Rule
433
434 With(properties, value string) Rule
435
Paul Duffinc8111702019-07-22 12:13:55 +0100436 WithMatcher(properties string, matcher ValueMatcher) Rule
437
Paul Duffin730f2a52019-06-27 14:08:51 +0100438 Without(properties, value string) Rule
439
Paul Duffinc8111702019-07-22 12:13:55 +0100440 WithoutMatcher(properties string, matcher ValueMatcher) Rule
441
Paul Duffin730f2a52019-06-27 14:08:51 +0100442 Because(reason string) Rule
443}
444
Steven Moreland65b3fd92017-12-06 14:18:35 -0800445type rule struct {
446 // User string for why this is a thing.
447 reason string
448
449 paths []string
450 unlessPaths []string
451
Paul Duffin35781882019-07-25 15:41:09 +0100452 directDeps map[string]bool
453
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100454 osClasses []OsClass
455
Colin Crossfd4f7432019-03-05 15:06:16 -0800456 moduleTypes []string
457 unlessModuleTypes []string
458
Liz Kammera3d79152021-10-28 18:14:04 -0400459 props ruleProperties
460 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100461
462 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463}
464
Paul Duffin730f2a52019-06-27 14:08:51 +0100465// Create a new NeverAllow rule.
466func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100467 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800468}
Colin Crossfd4f7432019-03-05 15:06:16 -0800469
Liz Kammera3d79152021-10-28 18:14:04 -0400470// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100471func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800472 r.paths = append(r.paths, cleanPaths(path)...)
473 return r
474}
Colin Crossfd4f7432019-03-05 15:06:16 -0800475
Liz Kammera3d79152021-10-28 18:14:04 -0400476// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100477func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800478 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
479 return r
480}
Colin Crossfd4f7432019-03-05 15:06:16 -0800481
Liz Kammera3d79152021-10-28 18:14:04 -0400482// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100483func (r *rule) InDirectDeps(deps ...string) Rule {
484 for _, d := range deps {
485 r.directDeps[d] = true
486 }
487 return r
488}
489
Liz Kammera3d79152021-10-28 18:14:04 -0400490// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100491func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
492 r.osClasses = append(r.osClasses, osClasses...)
493 return r
494}
495
Liz Kammera3d79152021-10-28 18:14:04 -0400496// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100497func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800498 r.moduleTypes = append(r.moduleTypes, types...)
499 return r
500}
501
Liz Kammera3d79152021-10-28 18:14:04 -0400502// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100503func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800504 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
505 return r
506}
507
Liz Kammera3d79152021-10-28 18:14:04 -0400508// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100509func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100510 return r.WithMatcher(properties, selectMatcher(value))
511}
512
Liz Kammera3d79152021-10-28 18:14:04 -0400513// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100514func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800515 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100516 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100517 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800518 })
519 return r
520}
Colin Crossfd4f7432019-03-05 15:06:16 -0800521
Liz Kammera3d79152021-10-28 18:14:04 -0400522// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100523func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100524 return r.WithoutMatcher(properties, selectMatcher(value))
525}
526
Liz Kammera3d79152021-10-28 18:14:04 -0400527// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100528func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800529 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100530 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100531 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 })
533 return r
534}
Colin Crossfd4f7432019-03-05 15:06:16 -0800535
Paul Duffin73bf0542019-07-12 14:12:49 +0100536func selectMatcher(expected string) ValueMatcher {
537 if expected == "*" {
538 return anyMatcherInstance
539 }
540 return &equalMatcher{expected: expected}
541}
542
Liz Kammera3d79152021-10-28 18:14:04 -0400543// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100544func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545 r.reason = reason
546 return r
547}
548
549func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400550 s := []string{"neverallow requirements. Not allowed:"}
551 if len(r.paths) > 0 {
552 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800553 }
Liz Kammera3d79152021-10-28 18:14:04 -0400554 if len(r.moduleTypes) > 0 {
555 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800556 }
Liz Kammera3d79152021-10-28 18:14:04 -0400557 if len(r.props) > 0 {
558 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800559 }
Liz Kammera3d79152021-10-28 18:14:04 -0400560 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800561 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800562 }
Liz Kammera3d79152021-10-28 18:14:04 -0400563 if len(r.osClasses) > 0 {
564 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100565 }
Liz Kammera3d79152021-10-28 18:14:04 -0400566 if len(r.unlessPaths) > 0 {
567 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
568 }
569 if len(r.unlessModuleTypes) > 0 {
570 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
571 }
572 if len(r.unlessProps) > 0 {
573 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100574 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800575 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400576 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800577 }
Liz Kammera3d79152021-10-28 18:14:04 -0400578 if len(s) == 1 {
579 s[0] = "neverallow requirements (empty)"
580 }
581 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800582}
583
584func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800585 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
586 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800587 return includePath && !excludePath
588}
589
Paul Duffin35781882019-07-25 15:41:09 +0100590func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
591 if len(r.directDeps) == 0 {
592 return true
593 }
594
595 matches := false
596 ctx.VisitDirectDeps(func(m Module) {
597 if !matches {
598 name := ctx.OtherModuleName(m)
599 matches = r.directDeps[name]
600 }
601 })
602
603 return matches
604}
605
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100606func (r *rule) appliesToOsClass(osClass OsClass) bool {
607 if len(r.osClasses) == 0 {
608 return true
609 }
610
611 for _, c := range r.osClasses {
612 if c == osClass {
613 return true
614 }
615 }
616
617 return false
618}
619
Colin Crossfd4f7432019-03-05 15:06:16 -0800620func (r *rule) appliesToModuleType(moduleType string) bool {
621 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
622}
623
Anton Hanssone1b18362021-12-23 15:05:38 +0000624func (r *rule) appliesToProperties(properties []interface{}) bool {
625 includeProps := hasAllProperties(properties, r.props)
626 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800627 return includeProps && !excludeProps
628}
629
Paul Duffinc8111702019-07-22 12:13:55 +0100630func StartsWith(prefix string) ValueMatcher {
631 return &startsWithMatcher{prefix}
632}
633
Anton Hansson45376402020-04-09 14:18:21 +0100634func Regexp(re string) ValueMatcher {
635 r, err := regexp.Compile(re)
636 if err != nil {
637 panic(err)
638 }
639 return &regexMatcher{r}
640}
641
Andrei Onea115e7e72020-06-05 21:14:03 +0100642func NotInList(allowed []string) ValueMatcher {
643 return &notInListMatcher{allowed}
644}
645
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646// assorted utils
647
648func cleanPaths(paths []string) []string {
649 res := make([]string, len(paths))
650 for i, v := range paths {
651 res[i] = filepath.Clean(v) + "/"
652 }
653 return res
654}
655
656func fieldNamesForProperties(propertyNames string) []string {
657 names := strings.Split(propertyNames, ".")
658 for i, v := range names {
659 names[i] = proptools.FieldNameForProperty(v)
660 }
661 return names
662}
663
Anton Hanssone1b18362021-12-23 15:05:38 +0000664func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000666 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800667 return true
668 }
669 }
670 return false
671}
672
Anton Hanssone1b18362021-12-23 15:05:38 +0000673func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800674 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000675 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800676 return false
677 }
678 }
679 return true
680}
681
Anton Hanssone1b18362021-12-23 15:05:38 +0000682func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800683 for _, propertyStruct := range properties {
684 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
685 for _, v := range prop.fields {
686 if !propertiesValue.IsValid() {
687 break
688 }
689 propertiesValue = propertiesValue.FieldByName(v)
690 }
691 if !propertiesValue.IsValid() {
692 continue
693 }
694
Paul Duffin73bf0542019-07-12 14:12:49 +0100695 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000696 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800697 }
698
699 if matchValue(propertiesValue, check) {
700 return true
701 }
702 }
703 return false
704}
705
706func matchValue(value reflect.Value, check func(string) bool) bool {
707 if !value.IsValid() {
708 return false
709 }
710
711 if value.Kind() == reflect.Ptr {
712 if value.IsNil() {
713 return check("")
714 }
715 value = value.Elem()
716 }
717
718 switch value.Kind() {
719 case reflect.String:
720 return check(value.String())
721 case reflect.Bool:
722 return check(strconv.FormatBool(value.Bool()))
723 case reflect.Int:
724 return check(strconv.FormatInt(value.Int(), 10))
725 case reflect.Slice:
726 slice, ok := value.Interface().([]string)
727 if !ok {
728 panic("Can only handle slice of string")
729 }
730 for _, v := range slice {
731 if check(v) {
732 return true
733 }
734 }
735 return false
736 }
737
738 panic("Can't handle type: " + value.Kind().String())
739}
Paul Duffin115445b2019-08-07 15:31:07 +0100740
741var neverallowRulesKey = NewOnceKey("neverallowRules")
742
743func neverallowRules(config Config) []Rule {
744 return config.Once(neverallowRulesKey, func() interface{} {
745 // No test rules were set by setTestNeverallowRules, use the global rules
746 return neverallows
747 }).([]Rule)
748}
749
750// Overrides the default neverallow rules for the supplied config.
751//
752// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100753func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100754 config.Once(neverallowRulesKey, func() interface{} { return testRules })
755}
Paul Duffin45338f02021-03-30 23:07:52 +0100756
757// Prepares for a test by setting neverallow rules and enabling the mutator.
758//
759// If the supplied rules are nil then the default rules are used.
760func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
761 return GroupFixturePreparers(
762 FixtureModifyConfig(func(config Config) {
763 if testRules != nil {
764 setTestNeverallowRules(config, testRules)
765 }
766 }),
767 FixtureRegisterWithContext(func(ctx RegistrationContext) {
768 ctx.PostDepsMutators(registerNeverallowMutator)
769 }),
770 )
771}