blob: f2e8c85348c0a9374d2055f088a2105a4e9754c8 [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())
Neil Fullerdf5f3562018-10-21 17:19:10 +010063}
Steven Moreland65b3fd92017-12-06 14:18:35 -080064
Paul Duffin730f2a52019-06-27 14:08:51 +010065// Add a NeverAllow rule to the set of rules to apply.
66func AddNeverAllowRules(rules ...Rule) {
67 neverallows = append(neverallows, rules...)
68}
69
Jingwen Chen1735b2e2022-10-10 14:30:03 +000070func createBp2BuildRule() Rule {
71 return NeverAllow().
72 With("bazel_module.bp2build_available", "true").
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000073 NotIn("soong_tests"). // only used in tests
Jingwen Chen1735b2e2022-10-10 14:30:03 +000074 Because("setting bp2build_available in Android.bp is not " +
75 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000076}
77
Sam Delmerico46d08b42022-11-15 15:51:04 -050078var (
79 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010080 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000081 "art/libnativebridge",
82 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010083 "libcore",
84 "libnativehelper",
85 "external/apache-harmony",
86 "external/apache-xml",
87 "external/boringssl",
88 "external/bouncycastle",
89 "external/conscrypt",
90 "external/icu",
91 "external/okhttp",
92 "external/vixl",
93 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010094 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050095 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000096 "frameworks/av/apex",
97 "frameworks/av/tools",
98 "frameworks/native/cmds",
99 "system/apex",
100 "system/bpf",
101 "system/gatekeeper",
102 "system/hwservicemanager",
103 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000104 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000105 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000106 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500107)
Paul Duffinc8111702019-07-22 12:13:55 +0100108
Sam Delmerico46d08b42022-11-15 15:51:04 -0500109func createIncludeDirsRules() []Rule {
110 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000111
Sam Delmerico46d08b42022-11-15 15:51:04 -0500112 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100113 rule :=
114 NeverAllow().
115 WithMatcher("include_dirs", StartsWith(path+"/")).
116 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
117 " to use alternate mechanisms and so can no longer be used.")
118
119 rules = append(rules, rule)
120 }
121
Sam Delmerico46d08b42022-11-15 15:51:04 -0500122 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000123 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
124 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
125 " to use alternate mechanisms and so can no longer be used.")
126 rules = append(rules, rule)
127 }
128
Paul Duffinc8111702019-07-22 12:13:55 +0100129 return rules
130}
131
Paul Duffin730f2a52019-06-27 14:08:51 +0100132func createTrebleRules() []Rule {
133 return []Rule{
134 NeverAllow().
135 In("vendor", "device").
136 With("vndk.enabled", "true").
137 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900138 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100139 Because("the VNDK can never contain a library that is device dependent."),
140 NeverAllow().
141 With("vndk.enabled", "true").
142 Without("vendor", "true").
143 Without("owner", "").
144 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800145
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800148 Without("name", "libhidlbase-combined-impl").
149 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100150 With("product_variables.enforce_vintf_manifest.cflags", "*").
151 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100152
153 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100154 NeverAllow().
155 Without("name", "libc_bionic_ndk").
156 With("product_variables.treble_linker_namespaces.cflags", "*").
157 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100158
159 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100161 }
162}
163
Paul Duffin730f2a52019-06-27 14:08:51 +0100164func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700165 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700166 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700167 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400168 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800169 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000170 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000171 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800172 }
173
Paul Duffin730f2a52019-06-27 14:08:51 +0100174 return []Rule{
175 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700176 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100177 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700178 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800179 }
180}
181
Colin Crossc511bc52020-04-07 16:50:32 +0000182func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700183 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000184 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
185 // This sometimes works because the APEX modules that contain derive_sdk and
186 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
187 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100188 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700189 // These are for apps and shouldn't be used by non-SDK variant modules.
190 "prebuilts/ndk",
191 "tools/test/graphicsbenchmark/apps/sample_app",
192 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700193 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000194 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000195 }
196
Colin Cross440e0d02020-06-11 11:32:11 -0700197 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000198 // android_native_app_glue and libRSSupport use native_window.h but target old
199 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
200 // so they can't add libnativewindow to shared_libs to get the header directory
201 // for the platform variant. Allow them to use the platform variant
202 // property to set shared_libs.
203 "prebuilts/ndk",
204 "frameworks/rs",
205 }
206
207 return []Rule{
208 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700209 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000210 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700211 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000212 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700213 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000214 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700215 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000216 }
217}
218
Alan Stokes73feba32022-11-14 12:21:24 +0000219func createCcStubsRule() Rule {
220 ccStubsImplementationInstallableProjectsAllowedList := []string{
221 "packages/modules/Virtualization/vm_payload",
222 }
223
224 return NeverAllow().
225 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
226 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
227 Because("implementation_installable can only be used in allowed projects.")
228}
229
David Srbeckye033cba2020-05-20 22:20:28 +0100230func createUncompressDexRules() []Rule {
231 return []Rule{
232 NeverAllow().
233 NotIn("art").
234 WithMatcher("uncompress_dex", isSetMatcherInstance).
235 Because("uncompress_dex is only allowed for certain jars for test in art."),
236 }
237}
238
Inseob Kim800d1142021-06-14 12:03:51 +0900239func createInitFirstStageRules() []Rule {
240 return []Rule{
241 NeverAllow().
242 Without("name", "init_first_stage").
243 With("install_in_root", "true").
244 Because("install_in_root is only for init_first_stage."),
245 }
246}
247
Jiyong Park3c306f32022-04-05 15:29:53 +0900248func createProhibitFrameworkAccessRules() []Rule {
249 return []Rule{
250 NeverAllow().
251 With("libs", "framework").
252 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
253 Because("framework can't be used when building against SDK"),
254 }
255}
256
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000257func createJavaExcludeStaticLibsRule() Rule {
258 return NeverAllow().
259 NotIn("build/soong").
260 ModuleType("java_library").
261 WithMatcher("exclude_static_libs", isSetMatcherInstance).
262 Because("exclude_static_libs property is only allowed for java modules defined in build/soong")
263}
264
Steven Moreland65b3fd92017-12-06 14:18:35 -0800265func neverallowMutator(ctx BottomUpMutatorContext) {
266 m, ok := ctx.Module().(Module)
267 if !ok {
268 return
269 }
270
271 dir := ctx.ModuleDir() + "/"
272 properties := m.GetProperties()
273
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100274 osClass := ctx.Module().Target().Os.Class
275
Paul Duffin115445b2019-08-07 15:31:07 +0100276 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100277 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800278 if !n.appliesToPath(dir) {
279 continue
280 }
281
Colin Crossfd4f7432019-03-05 15:06:16 -0800282 if !n.appliesToModuleType(ctx.ModuleType()) {
283 continue
284 }
285
Anton Hanssone1b18362021-12-23 15:05:38 +0000286 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800287 continue
288 }
289
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100290 if !n.appliesToOsClass(osClass) {
291 continue
292 }
293
Paul Duffin35781882019-07-25 15:41:09 +0100294 if !n.appliesToDirectDeps(ctx) {
295 continue
296 }
297
Steven Moreland65b3fd92017-12-06 14:18:35 -0800298 ctx.ModuleErrorf("violates " + n.String())
299 }
300}
301
Paul Duffin73bf0542019-07-12 14:12:49 +0100302type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000303 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100304 String() string
305}
306
307type equalMatcher struct {
308 expected string
309}
310
Anton Hanssone1b18362021-12-23 15:05:38 +0000311func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100312 return m.expected == value
313}
314
315func (m *equalMatcher) String() string {
316 return "=" + m.expected
317}
318
319type anyMatcher struct {
320}
321
Anton Hanssone1b18362021-12-23 15:05:38 +0000322func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100323 return true
324}
325
326func (m *anyMatcher) String() string {
327 return "=*"
328}
329
330var anyMatcherInstance = &anyMatcher{}
331
Paul Duffinc8111702019-07-22 12:13:55 +0100332type startsWithMatcher struct {
333 prefix string
334}
335
Anton Hanssone1b18362021-12-23 15:05:38 +0000336func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100337 return strings.HasPrefix(value, m.prefix)
338}
339
340func (m *startsWithMatcher) String() string {
341 return ".starts-with(" + m.prefix + ")"
342}
343
Anton Hansson45376402020-04-09 14:18:21 +0100344type regexMatcher struct {
345 re *regexp.Regexp
346}
347
Anton Hanssone1b18362021-12-23 15:05:38 +0000348func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100349 return m.re.MatchString(value)
350}
351
352func (m *regexMatcher) String() string {
353 return ".regexp(" + m.re.String() + ")"
354}
355
Andrei Onea115e7e72020-06-05 21:14:03 +0100356type notInListMatcher struct {
357 allowed []string
358}
359
Anton Hanssone1b18362021-12-23 15:05:38 +0000360func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100361 return !InList(value, m.allowed)
362}
363
364func (m *notInListMatcher) String() string {
365 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
366}
367
Colin Crossc511bc52020-04-07 16:50:32 +0000368type isSetMatcher struct{}
369
Anton Hanssone1b18362021-12-23 15:05:38 +0000370func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000371 return value != ""
372}
373
374func (m *isSetMatcher) String() string {
375 return ".is-set"
376}
377
378var isSetMatcherInstance = &isSetMatcher{}
379
Steven Moreland65b3fd92017-12-06 14:18:35 -0800380type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100381 fields []string // e.x.: Vndk.Enabled
382 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800383}
384
Liz Kammera3d79152021-10-28 18:14:04 -0400385func (r *ruleProperty) String() string {
386 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
387}
388
389type ruleProperties []ruleProperty
390
391func (r ruleProperties) String() string {
392 var s []string
393 for _, r := range r {
394 s = append(s, r.String())
395 }
396 return strings.Join(s, " ")
397}
398
Paul Duffin730f2a52019-06-27 14:08:51 +0100399// A NeverAllow rule.
400type Rule interface {
401 In(path ...string) Rule
402
403 NotIn(path ...string) Rule
404
Paul Duffin35781882019-07-25 15:41:09 +0100405 InDirectDeps(deps ...string) Rule
406
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100407 WithOsClass(osClasses ...OsClass) Rule
408
Paul Duffin730f2a52019-06-27 14:08:51 +0100409 ModuleType(types ...string) Rule
410
411 NotModuleType(types ...string) Rule
412
413 With(properties, value string) Rule
414
Paul Duffinc8111702019-07-22 12:13:55 +0100415 WithMatcher(properties string, matcher ValueMatcher) Rule
416
Paul Duffin730f2a52019-06-27 14:08:51 +0100417 Without(properties, value string) Rule
418
Paul Duffinc8111702019-07-22 12:13:55 +0100419 WithoutMatcher(properties string, matcher ValueMatcher) Rule
420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421 Because(reason string) Rule
422}
423
Steven Moreland65b3fd92017-12-06 14:18:35 -0800424type rule struct {
425 // User string for why this is a thing.
426 reason string
427
428 paths []string
429 unlessPaths []string
430
Paul Duffin35781882019-07-25 15:41:09 +0100431 directDeps map[string]bool
432
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100433 osClasses []OsClass
434
Colin Crossfd4f7432019-03-05 15:06:16 -0800435 moduleTypes []string
436 unlessModuleTypes []string
437
Liz Kammera3d79152021-10-28 18:14:04 -0400438 props ruleProperties
439 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100440
441 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800442}
443
Paul Duffin730f2a52019-06-27 14:08:51 +0100444// Create a new NeverAllow rule.
445func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100446 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447}
Colin Crossfd4f7432019-03-05 15:06:16 -0800448
Liz Kammera3d79152021-10-28 18:14:04 -0400449// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100450func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800451 r.paths = append(r.paths, cleanPaths(path)...)
452 return r
453}
Colin Crossfd4f7432019-03-05 15:06:16 -0800454
Liz Kammera3d79152021-10-28 18:14:04 -0400455// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100456func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
458 return r
459}
Colin Crossfd4f7432019-03-05 15:06:16 -0800460
Liz Kammera3d79152021-10-28 18:14:04 -0400461// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100462func (r *rule) InDirectDeps(deps ...string) Rule {
463 for _, d := range deps {
464 r.directDeps[d] = true
465 }
466 return r
467}
468
Liz Kammera3d79152021-10-28 18:14:04 -0400469// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100470func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
471 r.osClasses = append(r.osClasses, osClasses...)
472 return r
473}
474
Liz Kammera3d79152021-10-28 18:14:04 -0400475// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100476func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800477 r.moduleTypes = append(r.moduleTypes, types...)
478 return r
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100482func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800483 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
484 return r
485}
486
Liz Kammera3d79152021-10-28 18:14:04 -0400487// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100488func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100489 return r.WithMatcher(properties, selectMatcher(value))
490}
491
Liz Kammera3d79152021-10-28 18:14:04 -0400492// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100493func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800494 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100495 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100496 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 })
498 return r
499}
Colin Crossfd4f7432019-03-05 15:06:16 -0800500
Liz Kammera3d79152021-10-28 18:14:04 -0400501// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100502func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100503 return r.WithoutMatcher(properties, selectMatcher(value))
504}
505
Liz Kammera3d79152021-10-28 18:14:04 -0400506// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100507func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800508 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100509 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100510 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800511 })
512 return r
513}
Colin Crossfd4f7432019-03-05 15:06:16 -0800514
Paul Duffin73bf0542019-07-12 14:12:49 +0100515func selectMatcher(expected string) ValueMatcher {
516 if expected == "*" {
517 return anyMatcherInstance
518 }
519 return &equalMatcher{expected: expected}
520}
521
Liz Kammera3d79152021-10-28 18:14:04 -0400522// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100523func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524 r.reason = reason
525 return r
526}
527
528func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400529 s := []string{"neverallow requirements. Not allowed:"}
530 if len(r.paths) > 0 {
531 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 }
Liz Kammera3d79152021-10-28 18:14:04 -0400533 if len(r.moduleTypes) > 0 {
534 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800535 }
Liz Kammera3d79152021-10-28 18:14:04 -0400536 if len(r.props) > 0 {
537 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800538 }
Liz Kammera3d79152021-10-28 18:14:04 -0400539 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800540 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800541 }
Liz Kammera3d79152021-10-28 18:14:04 -0400542 if len(r.osClasses) > 0 {
543 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100544 }
Liz Kammera3d79152021-10-28 18:14:04 -0400545 if len(r.unlessPaths) > 0 {
546 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
547 }
548 if len(r.unlessModuleTypes) > 0 {
549 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
550 }
551 if len(r.unlessProps) > 0 {
552 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100553 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800554 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400555 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800556 }
Liz Kammera3d79152021-10-28 18:14:04 -0400557 if len(s) == 1 {
558 s[0] = "neverallow requirements (empty)"
559 }
560 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800561}
562
563func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800564 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
565 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566 return includePath && !excludePath
567}
568
Paul Duffin35781882019-07-25 15:41:09 +0100569func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
570 if len(r.directDeps) == 0 {
571 return true
572 }
573
574 matches := false
575 ctx.VisitDirectDeps(func(m Module) {
576 if !matches {
577 name := ctx.OtherModuleName(m)
578 matches = r.directDeps[name]
579 }
580 })
581
582 return matches
583}
584
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100585func (r *rule) appliesToOsClass(osClass OsClass) bool {
586 if len(r.osClasses) == 0 {
587 return true
588 }
589
590 for _, c := range r.osClasses {
591 if c == osClass {
592 return true
593 }
594 }
595
596 return false
597}
598
Colin Crossfd4f7432019-03-05 15:06:16 -0800599func (r *rule) appliesToModuleType(moduleType string) bool {
600 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
601}
602
Anton Hanssone1b18362021-12-23 15:05:38 +0000603func (r *rule) appliesToProperties(properties []interface{}) bool {
604 includeProps := hasAllProperties(properties, r.props)
605 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800606 return includeProps && !excludeProps
607}
608
Paul Duffinc8111702019-07-22 12:13:55 +0100609func StartsWith(prefix string) ValueMatcher {
610 return &startsWithMatcher{prefix}
611}
612
Anton Hansson45376402020-04-09 14:18:21 +0100613func Regexp(re string) ValueMatcher {
614 r, err := regexp.Compile(re)
615 if err != nil {
616 panic(err)
617 }
618 return &regexMatcher{r}
619}
620
Andrei Onea115e7e72020-06-05 21:14:03 +0100621func NotInList(allowed []string) ValueMatcher {
622 return &notInListMatcher{allowed}
623}
624
Steven Moreland65b3fd92017-12-06 14:18:35 -0800625// assorted utils
626
627func cleanPaths(paths []string) []string {
628 res := make([]string, len(paths))
629 for i, v := range paths {
630 res[i] = filepath.Clean(v) + "/"
631 }
632 return res
633}
634
635func fieldNamesForProperties(propertyNames string) []string {
636 names := strings.Split(propertyNames, ".")
637 for i, v := range names {
638 names[i] = proptools.FieldNameForProperty(v)
639 }
640 return names
641}
642
Anton Hanssone1b18362021-12-23 15:05:38 +0000643func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800644 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000645 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 return true
647 }
648 }
649 return false
650}
651
Anton Hanssone1b18362021-12-23 15:05:38 +0000652func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000654 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800655 return false
656 }
657 }
658 return true
659}
660
Anton Hanssone1b18362021-12-23 15:05:38 +0000661func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800662 for _, propertyStruct := range properties {
663 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
664 for _, v := range prop.fields {
665 if !propertiesValue.IsValid() {
666 break
667 }
668 propertiesValue = propertiesValue.FieldByName(v)
669 }
670 if !propertiesValue.IsValid() {
671 continue
672 }
673
Paul Duffin73bf0542019-07-12 14:12:49 +0100674 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000675 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800676 }
677
678 if matchValue(propertiesValue, check) {
679 return true
680 }
681 }
682 return false
683}
684
685func matchValue(value reflect.Value, check func(string) bool) bool {
686 if !value.IsValid() {
687 return false
688 }
689
690 if value.Kind() == reflect.Ptr {
691 if value.IsNil() {
692 return check("")
693 }
694 value = value.Elem()
695 }
696
697 switch value.Kind() {
698 case reflect.String:
699 return check(value.String())
700 case reflect.Bool:
701 return check(strconv.FormatBool(value.Bool()))
702 case reflect.Int:
703 return check(strconv.FormatInt(value.Int(), 10))
704 case reflect.Slice:
705 slice, ok := value.Interface().([]string)
706 if !ok {
707 panic("Can only handle slice of string")
708 }
709 for _, v := range slice {
710 if check(v) {
711 return true
712 }
713 }
714 return false
715 }
716
717 panic("Can't handle type: " + value.Kind().String())
718}
Paul Duffin115445b2019-08-07 15:31:07 +0100719
720var neverallowRulesKey = NewOnceKey("neverallowRules")
721
722func neverallowRules(config Config) []Rule {
723 return config.Once(neverallowRulesKey, func() interface{} {
724 // No test rules were set by setTestNeverallowRules, use the global rules
725 return neverallows
726 }).([]Rule)
727}
728
729// Overrides the default neverallow rules for the supplied config.
730//
731// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100732func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100733 config.Once(neverallowRulesKey, func() interface{} { return testRules })
734}
Paul Duffin45338f02021-03-30 23:07:52 +0100735
736// Prepares for a test by setting neverallow rules and enabling the mutator.
737//
738// If the supplied rules are nil then the default rules are used.
739func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
740 return GroupFixturePreparers(
741 FixtureModifyConfig(func(config Config) {
742 if testRules != nil {
743 setTestNeverallowRules(config, testRules)
744 }
745 }),
746 FixtureRegisterWithContext(func(ctx RegistrationContext) {
747 ctx.PostDepsMutators(registerNeverallowMutator)
748 }),
749 )
750}