blob: f721b945c1217cdeba38e0e3c126270fd7cbb169 [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()...)
Jingwen Chen1735b2e2022-10-10 14:30:03 +000060 AddNeverAllowRules(createBp2BuildRule())
Alan Stokes73feba32022-11-14 12:21:24 +000061 AddNeverAllowRules(createCcStubsRule())
Jihoon Kang381c2fa2023-06-01 22:17:32 +000062 AddNeverAllowRules(createJavaExcludeStaticLibsRule())
Mark Whitea15790a2023-08-22 21:28:11 +000063 AddNeverAllowRules(createProhibitHeaderOnlyRule())
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
Jingwen Chen1735b2e2022-10-10 14:30:03 +000071func createBp2BuildRule() Rule {
72 return NeverAllow().
73 With("bazel_module.bp2build_available", "true").
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000074 NotIn("soong_tests"). // only used in tests
Jingwen Chen1735b2e2022-10-10 14:30:03 +000075 Because("setting bp2build_available in Android.bp is not " +
76 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000077}
78
Sam Delmerico46d08b42022-11-15 15:51:04 -050079var (
80 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010081 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000082 "art/libnativebridge",
83 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010084 "libcore",
85 "libnativehelper",
86 "external/apache-harmony",
87 "external/apache-xml",
88 "external/boringssl",
89 "external/bouncycastle",
90 "external/conscrypt",
91 "external/icu",
92 "external/okhttp",
93 "external/vixl",
94 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010095 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050096 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000097 "frameworks/av/apex",
98 "frameworks/av/tools",
99 "frameworks/native/cmds",
100 "system/apex",
101 "system/bpf",
102 "system/gatekeeper",
103 "system/hwservicemanager",
104 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000105 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000106 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000107 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500108)
Paul Duffinc8111702019-07-22 12:13:55 +0100109
Sam Delmerico46d08b42022-11-15 15:51:04 -0500110func createIncludeDirsRules() []Rule {
111 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000112
Sam Delmerico46d08b42022-11-15 15:51:04 -0500113 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100114 rule :=
115 NeverAllow().
116 WithMatcher("include_dirs", StartsWith(path+"/")).
117 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
118 " to use alternate mechanisms and so can no longer be used.")
119
120 rules = append(rules, rule)
121 }
122
Sam Delmerico46d08b42022-11-15 15:51:04 -0500123 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000124 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
125 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
126 " to use alternate mechanisms and so can no longer be used.")
127 rules = append(rules, rule)
128 }
129
Paul Duffinc8111702019-07-22 12:13:55 +0100130 return rules
131}
132
Paul Duffin730f2a52019-06-27 14:08:51 +0100133func createTrebleRules() []Rule {
134 return []Rule{
135 NeverAllow().
136 In("vendor", "device").
137 With("vndk.enabled", "true").
138 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900139 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100140 Because("the VNDK can never contain a library that is device dependent."),
141 NeverAllow().
142 With("vndk.enabled", "true").
143 Without("vendor", "true").
144 Without("owner", "").
145 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800146
Neil Fullerdf5f3562018-10-21 17:19:10 +0100147 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100148 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800149 Without("name", "libhidlbase-combined-impl").
150 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100151 With("product_variables.enforce_vintf_manifest.cflags", "*").
152 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100153
154 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100155 NeverAllow().
156 Without("name", "libc_bionic_ndk").
157 With("product_variables.treble_linker_namespaces.cflags", "*").
158 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100159
160 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100161 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100162 }
163}
164
Paul Duffin730f2a52019-06-27 14:08:51 +0100165func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700166 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700167 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700168 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400169 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800170 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000171 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000172 "frameworks/base/ravenwood",
173 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000174 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800175 }
176
Paul Duffin730f2a52019-06-27 14:08:51 +0100177 return []Rule{
178 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700179 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100180 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700181 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800182 }
183}
184
Colin Crossc511bc52020-04-07 16:50:32 +0000185func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700186 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000187 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
188 // This sometimes works because the APEX modules that contain derive_sdk and
189 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
190 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100191 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700192 // These are for apps and shouldn't be used by non-SDK variant modules.
193 "prebuilts/ndk",
194 "tools/test/graphicsbenchmark/apps/sample_app",
195 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700196 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000197 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000198 }
199
Colin Cross440e0d02020-06-11 11:32:11 -0700200 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000201 // android_native_app_glue and libRSSupport use native_window.h but target old
202 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
203 // so they can't add libnativewindow to shared_libs to get the header directory
204 // for the platform variant. Allow them to use the platform variant
205 // property to set shared_libs.
206 "prebuilts/ndk",
207 "frameworks/rs",
208 }
209
210 return []Rule{
211 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700212 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000213 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700214 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000215 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700216 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000217 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700218 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000219 }
220}
221
Alan Stokes73feba32022-11-14 12:21:24 +0000222func createCcStubsRule() Rule {
223 ccStubsImplementationInstallableProjectsAllowedList := []string{
224 "packages/modules/Virtualization/vm_payload",
225 }
226
227 return NeverAllow().
228 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
229 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
230 Because("implementation_installable can only be used in allowed projects.")
231}
232
David Srbeckye033cba2020-05-20 22:20:28 +0100233func createUncompressDexRules() []Rule {
234 return []Rule{
235 NeverAllow().
236 NotIn("art").
237 WithMatcher("uncompress_dex", isSetMatcherInstance).
238 Because("uncompress_dex is only allowed for certain jars for test in art."),
239 }
240}
241
Inseob Kim800d1142021-06-14 12:03:51 +0900242func createInitFirstStageRules() []Rule {
243 return []Rule{
244 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100245 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900246 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100247 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900248 With("install_in_root", "true").
249 Because("install_in_root is only for init_first_stage."),
250 }
251}
252
Jiyong Park3c306f32022-04-05 15:29:53 +0900253func createProhibitFrameworkAccessRules() []Rule {
254 return []Rule{
255 NeverAllow().
256 With("libs", "framework").
257 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
258 Because("framework can't be used when building against SDK"),
259 }
260}
261
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000262func createJavaExcludeStaticLibsRule() Rule {
263 return NeverAllow().
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000264 NotIn("build/soong", "libcore", "frameworks/base/api").
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000265 ModuleType("java_library").
266 WithMatcher("exclude_static_libs", isSetMatcherInstance).
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000267 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 +0000268}
269
Mark Whitea15790a2023-08-22 21:28:11 +0000270func createProhibitHeaderOnlyRule() Rule {
271 return NeverAllow().
272 Without("name", "framework-minus-apex-headers").
273 With("headers_only", "true").
274 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
275}
276
Steven Moreland65b3fd92017-12-06 14:18:35 -0800277func neverallowMutator(ctx BottomUpMutatorContext) {
278 m, ok := ctx.Module().(Module)
279 if !ok {
280 return
281 }
282
283 dir := ctx.ModuleDir() + "/"
284 properties := m.GetProperties()
285
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100286 osClass := ctx.Module().Target().Os.Class
287
Paul Duffin115445b2019-08-07 15:31:07 +0100288 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100289 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800290 if !n.appliesToPath(dir) {
291 continue
292 }
293
Colin Crossfd4f7432019-03-05 15:06:16 -0800294 if !n.appliesToModuleType(ctx.ModuleType()) {
295 continue
296 }
297
Anton Hanssone1b18362021-12-23 15:05:38 +0000298 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800299 continue
300 }
301
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100302 if !n.appliesToOsClass(osClass) {
303 continue
304 }
305
Paul Duffin35781882019-07-25 15:41:09 +0100306 if !n.appliesToDirectDeps(ctx) {
307 continue
308 }
309
Steven Moreland65b3fd92017-12-06 14:18:35 -0800310 ctx.ModuleErrorf("violates " + n.String())
311 }
312}
313
Paul Duffin73bf0542019-07-12 14:12:49 +0100314type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000315 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100316 String() string
317}
318
319type equalMatcher struct {
320 expected string
321}
322
Anton Hanssone1b18362021-12-23 15:05:38 +0000323func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100324 return m.expected == value
325}
326
327func (m *equalMatcher) String() string {
328 return "=" + m.expected
329}
330
331type anyMatcher struct {
332}
333
Anton Hanssone1b18362021-12-23 15:05:38 +0000334func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100335 return true
336}
337
338func (m *anyMatcher) String() string {
339 return "=*"
340}
341
342var anyMatcherInstance = &anyMatcher{}
343
Paul Duffinc8111702019-07-22 12:13:55 +0100344type startsWithMatcher struct {
345 prefix string
346}
347
Anton Hanssone1b18362021-12-23 15:05:38 +0000348func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100349 return strings.HasPrefix(value, m.prefix)
350}
351
352func (m *startsWithMatcher) String() string {
353 return ".starts-with(" + m.prefix + ")"
354}
355
Anton Hansson45376402020-04-09 14:18:21 +0100356type regexMatcher struct {
357 re *regexp.Regexp
358}
359
Anton Hanssone1b18362021-12-23 15:05:38 +0000360func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100361 return m.re.MatchString(value)
362}
363
364func (m *regexMatcher) String() string {
365 return ".regexp(" + m.re.String() + ")"
366}
367
Andrei Onea115e7e72020-06-05 21:14:03 +0100368type notInListMatcher struct {
369 allowed []string
370}
371
Anton Hanssone1b18362021-12-23 15:05:38 +0000372func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100373 return !InList(value, m.allowed)
374}
375
376func (m *notInListMatcher) String() string {
377 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
378}
379
Colin Crossc511bc52020-04-07 16:50:32 +0000380type isSetMatcher struct{}
381
Anton Hanssone1b18362021-12-23 15:05:38 +0000382func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000383 return value != ""
384}
385
386func (m *isSetMatcher) String() string {
387 return ".is-set"
388}
389
390var isSetMatcherInstance = &isSetMatcher{}
391
Steven Moreland65b3fd92017-12-06 14:18:35 -0800392type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100393 fields []string // e.x.: Vndk.Enabled
394 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800395}
396
Liz Kammera3d79152021-10-28 18:14:04 -0400397func (r *ruleProperty) String() string {
398 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
399}
400
401type ruleProperties []ruleProperty
402
403func (r ruleProperties) String() string {
404 var s []string
405 for _, r := range r {
406 s = append(s, r.String())
407 }
408 return strings.Join(s, " ")
409}
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411// A NeverAllow rule.
412type Rule interface {
413 In(path ...string) Rule
414
415 NotIn(path ...string) Rule
416
Paul Duffin35781882019-07-25 15:41:09 +0100417 InDirectDeps(deps ...string) Rule
418
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100419 WithOsClass(osClasses ...OsClass) Rule
420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421 ModuleType(types ...string) Rule
422
423 NotModuleType(types ...string) Rule
424
425 With(properties, value string) Rule
426
Paul Duffinc8111702019-07-22 12:13:55 +0100427 WithMatcher(properties string, matcher ValueMatcher) Rule
428
Paul Duffin730f2a52019-06-27 14:08:51 +0100429 Without(properties, value string) Rule
430
Paul Duffinc8111702019-07-22 12:13:55 +0100431 WithoutMatcher(properties string, matcher ValueMatcher) Rule
432
Paul Duffin730f2a52019-06-27 14:08:51 +0100433 Because(reason string) Rule
434}
435
Steven Moreland65b3fd92017-12-06 14:18:35 -0800436type rule struct {
437 // User string for why this is a thing.
438 reason string
439
440 paths []string
441 unlessPaths []string
442
Paul Duffin35781882019-07-25 15:41:09 +0100443 directDeps map[string]bool
444
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100445 osClasses []OsClass
446
Colin Crossfd4f7432019-03-05 15:06:16 -0800447 moduleTypes []string
448 unlessModuleTypes []string
449
Liz Kammera3d79152021-10-28 18:14:04 -0400450 props ruleProperties
451 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100452
453 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800454}
455
Paul Duffin730f2a52019-06-27 14:08:51 +0100456// Create a new NeverAllow rule.
457func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100458 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459}
Colin Crossfd4f7432019-03-05 15:06:16 -0800460
Liz Kammera3d79152021-10-28 18:14:04 -0400461// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100462func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463 r.paths = append(r.paths, cleanPaths(path)...)
464 return r
465}
Colin Crossfd4f7432019-03-05 15:06:16 -0800466
Liz Kammera3d79152021-10-28 18:14:04 -0400467// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100468func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800469 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
470 return r
471}
Colin Crossfd4f7432019-03-05 15:06:16 -0800472
Liz Kammera3d79152021-10-28 18:14:04 -0400473// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100474func (r *rule) InDirectDeps(deps ...string) Rule {
475 for _, d := range deps {
476 r.directDeps[d] = true
477 }
478 return r
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100482func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
483 r.osClasses = append(r.osClasses, osClasses...)
484 return r
485}
486
Liz Kammera3d79152021-10-28 18:14:04 -0400487// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100488func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800489 r.moduleTypes = append(r.moduleTypes, types...)
490 return r
491}
492
Liz Kammera3d79152021-10-28 18:14:04 -0400493// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100494func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800495 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
496 return r
497}
498
Liz Kammera3d79152021-10-28 18:14:04 -0400499// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100500func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100501 return r.WithMatcher(properties, selectMatcher(value))
502}
503
Liz Kammera3d79152021-10-28 18:14:04 -0400504// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100505func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800506 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100507 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100508 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800509 })
510 return r
511}
Colin Crossfd4f7432019-03-05 15:06:16 -0800512
Liz Kammera3d79152021-10-28 18:14:04 -0400513// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100514func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100515 return r.WithoutMatcher(properties, selectMatcher(value))
516}
517
Liz Kammera3d79152021-10-28 18:14:04 -0400518// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100519func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800520 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100521 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100522 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800523 })
524 return r
525}
Colin Crossfd4f7432019-03-05 15:06:16 -0800526
Paul Duffin73bf0542019-07-12 14:12:49 +0100527func selectMatcher(expected string) ValueMatcher {
528 if expected == "*" {
529 return anyMatcherInstance
530 }
531 return &equalMatcher{expected: expected}
532}
533
Liz Kammera3d79152021-10-28 18:14:04 -0400534// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100535func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800536 r.reason = reason
537 return r
538}
539
540func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400541 s := []string{"neverallow requirements. Not allowed:"}
542 if len(r.paths) > 0 {
543 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800544 }
Liz Kammera3d79152021-10-28 18:14:04 -0400545 if len(r.moduleTypes) > 0 {
546 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 }
Liz Kammera3d79152021-10-28 18:14:04 -0400548 if len(r.props) > 0 {
549 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800550 }
Liz Kammera3d79152021-10-28 18:14:04 -0400551 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800552 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800553 }
Liz Kammera3d79152021-10-28 18:14:04 -0400554 if len(r.osClasses) > 0 {
555 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100556 }
Liz Kammera3d79152021-10-28 18:14:04 -0400557 if len(r.unlessPaths) > 0 {
558 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
559 }
560 if len(r.unlessModuleTypes) > 0 {
561 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
562 }
563 if len(r.unlessProps) > 0 {
564 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100565 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400567 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800568 }
Liz Kammera3d79152021-10-28 18:14:04 -0400569 if len(s) == 1 {
570 s[0] = "neverallow requirements (empty)"
571 }
572 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800573}
574
575func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800576 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
577 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800578 return includePath && !excludePath
579}
580
Paul Duffin35781882019-07-25 15:41:09 +0100581func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
582 if len(r.directDeps) == 0 {
583 return true
584 }
585
586 matches := false
587 ctx.VisitDirectDeps(func(m Module) {
588 if !matches {
589 name := ctx.OtherModuleName(m)
590 matches = r.directDeps[name]
591 }
592 })
593
594 return matches
595}
596
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100597func (r *rule) appliesToOsClass(osClass OsClass) bool {
598 if len(r.osClasses) == 0 {
599 return true
600 }
601
602 for _, c := range r.osClasses {
603 if c == osClass {
604 return true
605 }
606 }
607
608 return false
609}
610
Colin Crossfd4f7432019-03-05 15:06:16 -0800611func (r *rule) appliesToModuleType(moduleType string) bool {
612 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
613}
614
Anton Hanssone1b18362021-12-23 15:05:38 +0000615func (r *rule) appliesToProperties(properties []interface{}) bool {
616 includeProps := hasAllProperties(properties, r.props)
617 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800618 return includeProps && !excludeProps
619}
620
Paul Duffinc8111702019-07-22 12:13:55 +0100621func StartsWith(prefix string) ValueMatcher {
622 return &startsWithMatcher{prefix}
623}
624
Anton Hansson45376402020-04-09 14:18:21 +0100625func Regexp(re string) ValueMatcher {
626 r, err := regexp.Compile(re)
627 if err != nil {
628 panic(err)
629 }
630 return &regexMatcher{r}
631}
632
Andrei Onea115e7e72020-06-05 21:14:03 +0100633func NotInList(allowed []string) ValueMatcher {
634 return &notInListMatcher{allowed}
635}
636
Steven Moreland65b3fd92017-12-06 14:18:35 -0800637// assorted utils
638
639func cleanPaths(paths []string) []string {
640 res := make([]string, len(paths))
641 for i, v := range paths {
642 res[i] = filepath.Clean(v) + "/"
643 }
644 return res
645}
646
647func fieldNamesForProperties(propertyNames string) []string {
648 names := strings.Split(propertyNames, ".")
649 for i, v := range names {
650 names[i] = proptools.FieldNameForProperty(v)
651 }
652 return names
653}
654
Anton Hanssone1b18362021-12-23 15:05:38 +0000655func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800656 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000657 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800658 return true
659 }
660 }
661 return false
662}
663
Anton Hanssone1b18362021-12-23 15:05:38 +0000664func hasAllProperties(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 false
668 }
669 }
670 return true
671}
672
Anton Hanssone1b18362021-12-23 15:05:38 +0000673func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800674 for _, propertyStruct := range properties {
675 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
676 for _, v := range prop.fields {
677 if !propertiesValue.IsValid() {
678 break
679 }
680 propertiesValue = propertiesValue.FieldByName(v)
681 }
682 if !propertiesValue.IsValid() {
683 continue
684 }
685
Paul Duffin73bf0542019-07-12 14:12:49 +0100686 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000687 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800688 }
689
690 if matchValue(propertiesValue, check) {
691 return true
692 }
693 }
694 return false
695}
696
697func matchValue(value reflect.Value, check func(string) bool) bool {
698 if !value.IsValid() {
699 return false
700 }
701
702 if value.Kind() == reflect.Ptr {
703 if value.IsNil() {
704 return check("")
705 }
706 value = value.Elem()
707 }
708
709 switch value.Kind() {
710 case reflect.String:
711 return check(value.String())
712 case reflect.Bool:
713 return check(strconv.FormatBool(value.Bool()))
714 case reflect.Int:
715 return check(strconv.FormatInt(value.Int(), 10))
716 case reflect.Slice:
717 slice, ok := value.Interface().([]string)
718 if !ok {
719 panic("Can only handle slice of string")
720 }
721 for _, v := range slice {
722 if check(v) {
723 return true
724 }
725 }
726 return false
727 }
728
729 panic("Can't handle type: " + value.Kind().String())
730}
Paul Duffin115445b2019-08-07 15:31:07 +0100731
732var neverallowRulesKey = NewOnceKey("neverallowRules")
733
734func neverallowRules(config Config) []Rule {
735 return config.Once(neverallowRulesKey, func() interface{} {
736 // No test rules were set by setTestNeverallowRules, use the global rules
737 return neverallows
738 }).([]Rule)
739}
740
741// Overrides the default neverallow rules for the supplied config.
742//
743// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100744func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100745 config.Once(neverallowRulesKey, func() interface{} { return testRules })
746}
Paul Duffin45338f02021-03-30 23:07:52 +0100747
748// Prepares for a test by setting neverallow rules and enabling the mutator.
749//
750// If the supplied rules are nil then the default rules are used.
751func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
752 return GroupFixturePreparers(
753 FixtureModifyConfig(func(config Config) {
754 if testRules != nil {
755 setTestNeverallowRules(config, testRules)
756 }
757 }),
758 FixtureRegisterWithContext(func(ctx RegistrationContext) {
759 ctx.PostDepsMutators(registerNeverallowMutator)
760 }),
761 )
762}