blob: 2be6a74f5a17f041d1e087a80185c160648f19d4 [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",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000172 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800173 }
174
Paul Duffin730f2a52019-06-27 14:08:51 +0100175 return []Rule{
176 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700177 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100178 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700179 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800180 }
181}
182
Colin Crossc511bc52020-04-07 16:50:32 +0000183func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700184 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000185 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
186 // This sometimes works because the APEX modules that contain derive_sdk and
187 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
188 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100189 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700190 // These are for apps and shouldn't be used by non-SDK variant modules.
191 "prebuilts/ndk",
192 "tools/test/graphicsbenchmark/apps/sample_app",
193 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700194 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000195 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000196 }
197
Colin Cross440e0d02020-06-11 11:32:11 -0700198 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000199 // android_native_app_glue and libRSSupport use native_window.h but target old
200 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
201 // so they can't add libnativewindow to shared_libs to get the header directory
202 // for the platform variant. Allow them to use the platform variant
203 // property to set shared_libs.
204 "prebuilts/ndk",
205 "frameworks/rs",
206 }
207
208 return []Rule{
209 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700210 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000211 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700212 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000213 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700214 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000215 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700216 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000217 }
218}
219
Alan Stokes73feba32022-11-14 12:21:24 +0000220func createCcStubsRule() Rule {
221 ccStubsImplementationInstallableProjectsAllowedList := []string{
222 "packages/modules/Virtualization/vm_payload",
223 }
224
225 return NeverAllow().
226 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
227 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
228 Because("implementation_installable can only be used in allowed projects.")
229}
230
David Srbeckye033cba2020-05-20 22:20:28 +0100231func createUncompressDexRules() []Rule {
232 return []Rule{
233 NeverAllow().
234 NotIn("art").
235 WithMatcher("uncompress_dex", isSetMatcherInstance).
236 Because("uncompress_dex is only allowed for certain jars for test in art."),
237 }
238}
239
Inseob Kim800d1142021-06-14 12:03:51 +0900240func createInitFirstStageRules() []Rule {
241 return []Rule{
242 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100243 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900244 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100245 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900246 With("install_in_root", "true").
247 Because("install_in_root is only for init_first_stage."),
248 }
249}
250
Jiyong Park3c306f32022-04-05 15:29:53 +0900251func createProhibitFrameworkAccessRules() []Rule {
252 return []Rule{
253 NeverAllow().
254 With("libs", "framework").
255 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
256 Because("framework can't be used when building against SDK"),
257 }
258}
259
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000260func createJavaExcludeStaticLibsRule() Rule {
261 return NeverAllow().
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000262 NotIn("build/soong", "libcore", "frameworks/base/api").
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000263 ModuleType("java_library").
264 WithMatcher("exclude_static_libs", isSetMatcherInstance).
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000265 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 +0000266}
267
Mark Whitea15790a2023-08-22 21:28:11 +0000268func createProhibitHeaderOnlyRule() Rule {
269 return NeverAllow().
270 Without("name", "framework-minus-apex-headers").
271 With("headers_only", "true").
272 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
273}
274
Steven Moreland65b3fd92017-12-06 14:18:35 -0800275func neverallowMutator(ctx BottomUpMutatorContext) {
276 m, ok := ctx.Module().(Module)
277 if !ok {
278 return
279 }
280
281 dir := ctx.ModuleDir() + "/"
282 properties := m.GetProperties()
283
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100284 osClass := ctx.Module().Target().Os.Class
285
Paul Duffin115445b2019-08-07 15:31:07 +0100286 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100287 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800288 if !n.appliesToPath(dir) {
289 continue
290 }
291
Colin Crossfd4f7432019-03-05 15:06:16 -0800292 if !n.appliesToModuleType(ctx.ModuleType()) {
293 continue
294 }
295
Anton Hanssone1b18362021-12-23 15:05:38 +0000296 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800297 continue
298 }
299
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100300 if !n.appliesToOsClass(osClass) {
301 continue
302 }
303
Paul Duffin35781882019-07-25 15:41:09 +0100304 if !n.appliesToDirectDeps(ctx) {
305 continue
306 }
307
Steven Moreland65b3fd92017-12-06 14:18:35 -0800308 ctx.ModuleErrorf("violates " + n.String())
309 }
310}
311
Paul Duffin73bf0542019-07-12 14:12:49 +0100312type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000313 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100314 String() string
315}
316
317type equalMatcher struct {
318 expected string
319}
320
Anton Hanssone1b18362021-12-23 15:05:38 +0000321func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100322 return m.expected == value
323}
324
325func (m *equalMatcher) String() string {
326 return "=" + m.expected
327}
328
329type anyMatcher struct {
330}
331
Anton Hanssone1b18362021-12-23 15:05:38 +0000332func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100333 return true
334}
335
336func (m *anyMatcher) String() string {
337 return "=*"
338}
339
340var anyMatcherInstance = &anyMatcher{}
341
Paul Duffinc8111702019-07-22 12:13:55 +0100342type startsWithMatcher struct {
343 prefix string
344}
345
Anton Hanssone1b18362021-12-23 15:05:38 +0000346func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100347 return strings.HasPrefix(value, m.prefix)
348}
349
350func (m *startsWithMatcher) String() string {
351 return ".starts-with(" + m.prefix + ")"
352}
353
Anton Hansson45376402020-04-09 14:18:21 +0100354type regexMatcher struct {
355 re *regexp.Regexp
356}
357
Anton Hanssone1b18362021-12-23 15:05:38 +0000358func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100359 return m.re.MatchString(value)
360}
361
362func (m *regexMatcher) String() string {
363 return ".regexp(" + m.re.String() + ")"
364}
365
Andrei Onea115e7e72020-06-05 21:14:03 +0100366type notInListMatcher struct {
367 allowed []string
368}
369
Anton Hanssone1b18362021-12-23 15:05:38 +0000370func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100371 return !InList(value, m.allowed)
372}
373
374func (m *notInListMatcher) String() string {
375 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
376}
377
Colin Crossc511bc52020-04-07 16:50:32 +0000378type isSetMatcher struct{}
379
Anton Hanssone1b18362021-12-23 15:05:38 +0000380func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000381 return value != ""
382}
383
384func (m *isSetMatcher) String() string {
385 return ".is-set"
386}
387
388var isSetMatcherInstance = &isSetMatcher{}
389
Steven Moreland65b3fd92017-12-06 14:18:35 -0800390type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100391 fields []string // e.x.: Vndk.Enabled
392 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800393}
394
Liz Kammera3d79152021-10-28 18:14:04 -0400395func (r *ruleProperty) String() string {
396 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
397}
398
399type ruleProperties []ruleProperty
400
401func (r ruleProperties) String() string {
402 var s []string
403 for _, r := range r {
404 s = append(s, r.String())
405 }
406 return strings.Join(s, " ")
407}
408
Paul Duffin730f2a52019-06-27 14:08:51 +0100409// A NeverAllow rule.
410type Rule interface {
411 In(path ...string) Rule
412
413 NotIn(path ...string) Rule
414
Paul Duffin35781882019-07-25 15:41:09 +0100415 InDirectDeps(deps ...string) Rule
416
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100417 WithOsClass(osClasses ...OsClass) Rule
418
Paul Duffin730f2a52019-06-27 14:08:51 +0100419 ModuleType(types ...string) Rule
420
421 NotModuleType(types ...string) Rule
422
423 With(properties, value string) Rule
424
Paul Duffinc8111702019-07-22 12:13:55 +0100425 WithMatcher(properties string, matcher ValueMatcher) Rule
426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427 Without(properties, value string) Rule
428
Paul Duffinc8111702019-07-22 12:13:55 +0100429 WithoutMatcher(properties string, matcher ValueMatcher) Rule
430
Paul Duffin730f2a52019-06-27 14:08:51 +0100431 Because(reason string) Rule
432}
433
Steven Moreland65b3fd92017-12-06 14:18:35 -0800434type rule struct {
435 // User string for why this is a thing.
436 reason string
437
438 paths []string
439 unlessPaths []string
440
Paul Duffin35781882019-07-25 15:41:09 +0100441 directDeps map[string]bool
442
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100443 osClasses []OsClass
444
Colin Crossfd4f7432019-03-05 15:06:16 -0800445 moduleTypes []string
446 unlessModuleTypes []string
447
Liz Kammera3d79152021-10-28 18:14:04 -0400448 props ruleProperties
449 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100450
451 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800452}
453
Paul Duffin730f2a52019-06-27 14:08:51 +0100454// Create a new NeverAllow rule.
455func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100456 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457}
Colin Crossfd4f7432019-03-05 15:06:16 -0800458
Liz Kammera3d79152021-10-28 18:14:04 -0400459// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100460func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800461 r.paths = append(r.paths, cleanPaths(path)...)
462 return r
463}
Colin Crossfd4f7432019-03-05 15:06:16 -0800464
Liz Kammera3d79152021-10-28 18:14:04 -0400465// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100466func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800467 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
468 return r
469}
Colin Crossfd4f7432019-03-05 15:06:16 -0800470
Liz Kammera3d79152021-10-28 18:14:04 -0400471// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100472func (r *rule) InDirectDeps(deps ...string) Rule {
473 for _, d := range deps {
474 r.directDeps[d] = true
475 }
476 return r
477}
478
Liz Kammera3d79152021-10-28 18:14:04 -0400479// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100480func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
481 r.osClasses = append(r.osClasses, osClasses...)
482 return r
483}
484
Liz Kammera3d79152021-10-28 18:14:04 -0400485// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100486func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800487 r.moduleTypes = append(r.moduleTypes, types...)
488 return r
489}
490
Liz Kammera3d79152021-10-28 18:14:04 -0400491// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100492func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800493 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
494 return r
495}
496
Liz Kammera3d79152021-10-28 18:14:04 -0400497// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100498func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100499 return r.WithMatcher(properties, selectMatcher(value))
500}
501
Liz Kammera3d79152021-10-28 18:14:04 -0400502// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100503func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800504 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100505 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100506 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800507 })
508 return r
509}
Colin Crossfd4f7432019-03-05 15:06:16 -0800510
Liz Kammera3d79152021-10-28 18:14:04 -0400511// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100512func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100513 return r.WithoutMatcher(properties, selectMatcher(value))
514}
515
Liz Kammera3d79152021-10-28 18:14:04 -0400516// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100517func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800518 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100519 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100520 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800521 })
522 return r
523}
Colin Crossfd4f7432019-03-05 15:06:16 -0800524
Paul Duffin73bf0542019-07-12 14:12:49 +0100525func selectMatcher(expected string) ValueMatcher {
526 if expected == "*" {
527 return anyMatcherInstance
528 }
529 return &equalMatcher{expected: expected}
530}
531
Liz Kammera3d79152021-10-28 18:14:04 -0400532// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100533func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800534 r.reason = reason
535 return r
536}
537
538func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400539 s := []string{"neverallow requirements. Not allowed:"}
540 if len(r.paths) > 0 {
541 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542 }
Liz Kammera3d79152021-10-28 18:14:04 -0400543 if len(r.moduleTypes) > 0 {
544 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545 }
Liz Kammera3d79152021-10-28 18:14:04 -0400546 if len(r.props) > 0 {
547 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800548 }
Liz Kammera3d79152021-10-28 18:14:04 -0400549 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800550 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800551 }
Liz Kammera3d79152021-10-28 18:14:04 -0400552 if len(r.osClasses) > 0 {
553 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100554 }
Liz Kammera3d79152021-10-28 18:14:04 -0400555 if len(r.unlessPaths) > 0 {
556 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
557 }
558 if len(r.unlessModuleTypes) > 0 {
559 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
560 }
561 if len(r.unlessProps) > 0 {
562 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100563 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800564 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400565 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566 }
Liz Kammera3d79152021-10-28 18:14:04 -0400567 if len(s) == 1 {
568 s[0] = "neverallow requirements (empty)"
569 }
570 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800571}
572
573func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800574 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
575 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800576 return includePath && !excludePath
577}
578
Paul Duffin35781882019-07-25 15:41:09 +0100579func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
580 if len(r.directDeps) == 0 {
581 return true
582 }
583
584 matches := false
585 ctx.VisitDirectDeps(func(m Module) {
586 if !matches {
587 name := ctx.OtherModuleName(m)
588 matches = r.directDeps[name]
589 }
590 })
591
592 return matches
593}
594
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100595func (r *rule) appliesToOsClass(osClass OsClass) bool {
596 if len(r.osClasses) == 0 {
597 return true
598 }
599
600 for _, c := range r.osClasses {
601 if c == osClass {
602 return true
603 }
604 }
605
606 return false
607}
608
Colin Crossfd4f7432019-03-05 15:06:16 -0800609func (r *rule) appliesToModuleType(moduleType string) bool {
610 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
611}
612
Anton Hanssone1b18362021-12-23 15:05:38 +0000613func (r *rule) appliesToProperties(properties []interface{}) bool {
614 includeProps := hasAllProperties(properties, r.props)
615 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800616 return includeProps && !excludeProps
617}
618
Paul Duffinc8111702019-07-22 12:13:55 +0100619func StartsWith(prefix string) ValueMatcher {
620 return &startsWithMatcher{prefix}
621}
622
Anton Hansson45376402020-04-09 14:18:21 +0100623func Regexp(re string) ValueMatcher {
624 r, err := regexp.Compile(re)
625 if err != nil {
626 panic(err)
627 }
628 return &regexMatcher{r}
629}
630
Andrei Onea115e7e72020-06-05 21:14:03 +0100631func NotInList(allowed []string) ValueMatcher {
632 return &notInListMatcher{allowed}
633}
634
Steven Moreland65b3fd92017-12-06 14:18:35 -0800635// assorted utils
636
637func cleanPaths(paths []string) []string {
638 res := make([]string, len(paths))
639 for i, v := range paths {
640 res[i] = filepath.Clean(v) + "/"
641 }
642 return res
643}
644
645func fieldNamesForProperties(propertyNames string) []string {
646 names := strings.Split(propertyNames, ".")
647 for i, v := range names {
648 names[i] = proptools.FieldNameForProperty(v)
649 }
650 return names
651}
652
Anton Hanssone1b18362021-12-23 15:05:38 +0000653func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800654 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000655 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800656 return true
657 }
658 }
659 return false
660}
661
Anton Hanssone1b18362021-12-23 15:05:38 +0000662func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800663 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000664 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665 return false
666 }
667 }
668 return true
669}
670
Anton Hanssone1b18362021-12-23 15:05:38 +0000671func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800672 for _, propertyStruct := range properties {
673 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
674 for _, v := range prop.fields {
675 if !propertiesValue.IsValid() {
676 break
677 }
678 propertiesValue = propertiesValue.FieldByName(v)
679 }
680 if !propertiesValue.IsValid() {
681 continue
682 }
683
Paul Duffin73bf0542019-07-12 14:12:49 +0100684 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000685 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800686 }
687
688 if matchValue(propertiesValue, check) {
689 return true
690 }
691 }
692 return false
693}
694
695func matchValue(value reflect.Value, check func(string) bool) bool {
696 if !value.IsValid() {
697 return false
698 }
699
700 if value.Kind() == reflect.Ptr {
701 if value.IsNil() {
702 return check("")
703 }
704 value = value.Elem()
705 }
706
707 switch value.Kind() {
708 case reflect.String:
709 return check(value.String())
710 case reflect.Bool:
711 return check(strconv.FormatBool(value.Bool()))
712 case reflect.Int:
713 return check(strconv.FormatInt(value.Int(), 10))
714 case reflect.Slice:
715 slice, ok := value.Interface().([]string)
716 if !ok {
717 panic("Can only handle slice of string")
718 }
719 for _, v := range slice {
720 if check(v) {
721 return true
722 }
723 }
724 return false
725 }
726
727 panic("Can't handle type: " + value.Kind().String())
728}
Paul Duffin115445b2019-08-07 15:31:07 +0100729
730var neverallowRulesKey = NewOnceKey("neverallowRules")
731
732func neverallowRules(config Config) []Rule {
733 return config.Once(neverallowRulesKey, func() interface{} {
734 // No test rules were set by setTestNeverallowRules, use the global rules
735 return neverallows
736 }).([]Rule)
737}
738
739// Overrides the default neverallow rules for the supplied config.
740//
741// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100742func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100743 config.Once(neverallowRulesKey, func() interface{} { return testRules })
744}
Paul Duffin45338f02021-03-30 23:07:52 +0100745
746// Prepares for a test by setting neverallow rules and enabling the mutator.
747//
748// If the supplied rules are nil then the default rules are used.
749func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
750 return GroupFixturePreparers(
751 FixtureModifyConfig(func(config Config) {
752 if testRules != nil {
753 setTestNeverallowRules(config, testRules)
754 }
755 }),
756 FixtureRegisterWithContext(func(ctx RegistrationContext) {
757 ctx.PostDepsMutators(registerNeverallowMutator)
758 }),
759 )
760}