blob: ba5385cd28d825787c026694fec955dd4fd5f899 [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()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070058 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090059 AddNeverAllowRules(createInitFirstStageRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090060 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Jingwen Chen1735b2e2022-10-10 14:30:03 +000061 AddNeverAllowRules(createBp2BuildRule())
Alan Stokes73feba32022-11-14 12:21:24 +000062 AddNeverAllowRules(createCcStubsRule())
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",
Colin Crossfd4f7432019-03-05 15:06:16 -0800168 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000169 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000170 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800171 }
172
Paul Duffin730f2a52019-06-27 14:08:51 +0100173 return []Rule{
174 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700175 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100176 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700177 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800178 }
179}
180
Colin Crossc511bc52020-04-07 16:50:32 +0000181func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700182 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
184 // This sometimes works because the APEX modules that contain derive_sdk and
185 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
186 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100187 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700188 // These are for apps and shouldn't be used by non-SDK variant modules.
189 "prebuilts/ndk",
190 "tools/test/graphicsbenchmark/apps/sample_app",
191 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700192 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000193 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000194 }
195
Colin Cross440e0d02020-06-11 11:32:11 -0700196 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000197 // android_native_app_glue and libRSSupport use native_window.h but target old
198 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
199 // so they can't add libnativewindow to shared_libs to get the header directory
200 // for the platform variant. Allow them to use the platform variant
201 // property to set shared_libs.
202 "prebuilts/ndk",
203 "frameworks/rs",
204 }
205
206 return []Rule{
207 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700208 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000209 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700210 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000211 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700212 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000213 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700214 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000215 }
216}
217
Alan Stokes73feba32022-11-14 12:21:24 +0000218func createCcStubsRule() Rule {
219 ccStubsImplementationInstallableProjectsAllowedList := []string{
220 "packages/modules/Virtualization/vm_payload",
221 }
222
223 return NeverAllow().
224 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
225 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
226 Because("implementation_installable can only be used in allowed projects.")
227}
228
David Srbeckye033cba2020-05-20 22:20:28 +0100229func createUncompressDexRules() []Rule {
230 return []Rule{
231 NeverAllow().
232 NotIn("art").
233 WithMatcher("uncompress_dex", isSetMatcherInstance).
234 Because("uncompress_dex is only allowed for certain jars for test in art."),
235 }
236}
237
Yifan Hong696ed4d2020-07-27 12:59:58 -0700238func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900239 allowlist := []string{
240 // libwifi_hal uses makefile_goal for its dependencies
241 "frameworks/opt/net/wifi/libwifi_hal",
242 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700243 return []Rule{
244 NeverAllow().
245 ModuleType("makefile_goal").
246 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900247 NotIn(allowlist...).
248 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700249 }
250}
251
Inseob Kim800d1142021-06-14 12:03:51 +0900252func createInitFirstStageRules() []Rule {
253 return []Rule{
254 NeverAllow().
255 Without("name", "init_first_stage").
256 With("install_in_root", "true").
257 Because("install_in_root is only for init_first_stage."),
258 }
259}
260
Jiyong Park3c306f32022-04-05 15:29:53 +0900261func createProhibitFrameworkAccessRules() []Rule {
262 return []Rule{
263 NeverAllow().
264 With("libs", "framework").
265 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
266 Because("framework can't be used when building against SDK"),
267 }
268}
269
Steven Moreland65b3fd92017-12-06 14:18:35 -0800270func neverallowMutator(ctx BottomUpMutatorContext) {
271 m, ok := ctx.Module().(Module)
272 if !ok {
273 return
274 }
275
276 dir := ctx.ModuleDir() + "/"
277 properties := m.GetProperties()
278
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100279 osClass := ctx.Module().Target().Os.Class
280
Paul Duffin115445b2019-08-07 15:31:07 +0100281 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100282 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800283 if !n.appliesToPath(dir) {
284 continue
285 }
286
Colin Crossfd4f7432019-03-05 15:06:16 -0800287 if !n.appliesToModuleType(ctx.ModuleType()) {
288 continue
289 }
290
Anton Hanssone1b18362021-12-23 15:05:38 +0000291 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800292 continue
293 }
294
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100295 if !n.appliesToOsClass(osClass) {
296 continue
297 }
298
Paul Duffin35781882019-07-25 15:41:09 +0100299 if !n.appliesToDirectDeps(ctx) {
300 continue
301 }
302
Steven Moreland65b3fd92017-12-06 14:18:35 -0800303 ctx.ModuleErrorf("violates " + n.String())
304 }
305}
306
Paul Duffin73bf0542019-07-12 14:12:49 +0100307type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000308 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100309 String() string
310}
311
312type equalMatcher struct {
313 expected string
314}
315
Anton Hanssone1b18362021-12-23 15:05:38 +0000316func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100317 return m.expected == value
318}
319
320func (m *equalMatcher) String() string {
321 return "=" + m.expected
322}
323
324type anyMatcher struct {
325}
326
Anton Hanssone1b18362021-12-23 15:05:38 +0000327func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100328 return true
329}
330
331func (m *anyMatcher) String() string {
332 return "=*"
333}
334
335var anyMatcherInstance = &anyMatcher{}
336
Paul Duffinc8111702019-07-22 12:13:55 +0100337type startsWithMatcher struct {
338 prefix string
339}
340
Anton Hanssone1b18362021-12-23 15:05:38 +0000341func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100342 return strings.HasPrefix(value, m.prefix)
343}
344
345func (m *startsWithMatcher) String() string {
346 return ".starts-with(" + m.prefix + ")"
347}
348
Anton Hansson45376402020-04-09 14:18:21 +0100349type regexMatcher struct {
350 re *regexp.Regexp
351}
352
Anton Hanssone1b18362021-12-23 15:05:38 +0000353func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100354 return m.re.MatchString(value)
355}
356
357func (m *regexMatcher) String() string {
358 return ".regexp(" + m.re.String() + ")"
359}
360
Andrei Onea115e7e72020-06-05 21:14:03 +0100361type notInListMatcher struct {
362 allowed []string
363}
364
Anton Hanssone1b18362021-12-23 15:05:38 +0000365func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100366 return !InList(value, m.allowed)
367}
368
369func (m *notInListMatcher) String() string {
370 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
371}
372
Colin Crossc511bc52020-04-07 16:50:32 +0000373type isSetMatcher struct{}
374
Anton Hanssone1b18362021-12-23 15:05:38 +0000375func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000376 return value != ""
377}
378
379func (m *isSetMatcher) String() string {
380 return ".is-set"
381}
382
383var isSetMatcherInstance = &isSetMatcher{}
384
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100386 fields []string // e.x.: Vndk.Enabled
387 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800388}
389
Liz Kammera3d79152021-10-28 18:14:04 -0400390func (r *ruleProperty) String() string {
391 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
392}
393
394type ruleProperties []ruleProperty
395
396func (r ruleProperties) String() string {
397 var s []string
398 for _, r := range r {
399 s = append(s, r.String())
400 }
401 return strings.Join(s, " ")
402}
403
Paul Duffin730f2a52019-06-27 14:08:51 +0100404// A NeverAllow rule.
405type Rule interface {
406 In(path ...string) Rule
407
408 NotIn(path ...string) Rule
409
Paul Duffin35781882019-07-25 15:41:09 +0100410 InDirectDeps(deps ...string) Rule
411
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100412 WithOsClass(osClasses ...OsClass) Rule
413
Paul Duffin730f2a52019-06-27 14:08:51 +0100414 ModuleType(types ...string) Rule
415
416 NotModuleType(types ...string) Rule
417
418 With(properties, value string) Rule
419
Paul Duffinc8111702019-07-22 12:13:55 +0100420 WithMatcher(properties string, matcher ValueMatcher) Rule
421
Paul Duffin730f2a52019-06-27 14:08:51 +0100422 Without(properties, value string) Rule
423
Paul Duffinc8111702019-07-22 12:13:55 +0100424 WithoutMatcher(properties string, matcher ValueMatcher) Rule
425
Paul Duffin730f2a52019-06-27 14:08:51 +0100426 Because(reason string) Rule
427}
428
Steven Moreland65b3fd92017-12-06 14:18:35 -0800429type rule struct {
430 // User string for why this is a thing.
431 reason string
432
433 paths []string
434 unlessPaths []string
435
Paul Duffin35781882019-07-25 15:41:09 +0100436 directDeps map[string]bool
437
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100438 osClasses []OsClass
439
Colin Crossfd4f7432019-03-05 15:06:16 -0800440 moduleTypes []string
441 unlessModuleTypes []string
442
Liz Kammera3d79152021-10-28 18:14:04 -0400443 props ruleProperties
444 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100445
446 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447}
448
Paul Duffin730f2a52019-06-27 14:08:51 +0100449// Create a new NeverAllow rule.
450func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100451 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800452}
Colin Crossfd4f7432019-03-05 15:06:16 -0800453
Liz Kammera3d79152021-10-28 18:14:04 -0400454// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100455func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800456 r.paths = append(r.paths, cleanPaths(path)...)
457 return r
458}
Colin Crossfd4f7432019-03-05 15:06:16 -0800459
Liz Kammera3d79152021-10-28 18:14:04 -0400460// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100461func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800462 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
463 return r
464}
Colin Crossfd4f7432019-03-05 15:06:16 -0800465
Liz Kammera3d79152021-10-28 18:14:04 -0400466// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100467func (r *rule) InDirectDeps(deps ...string) Rule {
468 for _, d := range deps {
469 r.directDeps[d] = true
470 }
471 return r
472}
473
Liz Kammera3d79152021-10-28 18:14:04 -0400474// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100475func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
476 r.osClasses = append(r.osClasses, osClasses...)
477 return r
478}
479
Liz Kammera3d79152021-10-28 18:14:04 -0400480// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100481func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800482 r.moduleTypes = append(r.moduleTypes, types...)
483 return r
484}
485
Liz Kammera3d79152021-10-28 18:14:04 -0400486// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100487func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800488 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
489 return r
490}
491
Liz Kammera3d79152021-10-28 18:14:04 -0400492// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100493func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100494 return r.WithMatcher(properties, selectMatcher(value))
495}
496
Liz Kammera3d79152021-10-28 18:14:04 -0400497// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100498func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800499 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100500 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100501 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800502 })
503 return r
504}
Colin Crossfd4f7432019-03-05 15:06:16 -0800505
Liz Kammera3d79152021-10-28 18:14:04 -0400506// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100507func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100508 return r.WithoutMatcher(properties, selectMatcher(value))
509}
510
Liz Kammera3d79152021-10-28 18:14:04 -0400511// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100512func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100514 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100515 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800516 })
517 return r
518}
Colin Crossfd4f7432019-03-05 15:06:16 -0800519
Paul Duffin73bf0542019-07-12 14:12:49 +0100520func selectMatcher(expected string) ValueMatcher {
521 if expected == "*" {
522 return anyMatcherInstance
523 }
524 return &equalMatcher{expected: expected}
525}
526
Liz Kammera3d79152021-10-28 18:14:04 -0400527// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100528func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800529 r.reason = reason
530 return r
531}
532
533func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400534 s := []string{"neverallow requirements. Not allowed:"}
535 if len(r.paths) > 0 {
536 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 }
Liz Kammera3d79152021-10-28 18:14:04 -0400538 if len(r.moduleTypes) > 0 {
539 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800540 }
Liz Kammera3d79152021-10-28 18:14:04 -0400541 if len(r.props) > 0 {
542 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800543 }
Liz Kammera3d79152021-10-28 18:14:04 -0400544 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800545 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800546 }
Liz Kammera3d79152021-10-28 18:14:04 -0400547 if len(r.osClasses) > 0 {
548 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100549 }
Liz Kammera3d79152021-10-28 18:14:04 -0400550 if len(r.unlessPaths) > 0 {
551 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
552 }
553 if len(r.unlessModuleTypes) > 0 {
554 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
555 }
556 if len(r.unlessProps) > 0 {
557 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100558 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800559 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400560 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800561 }
Liz Kammera3d79152021-10-28 18:14:04 -0400562 if len(s) == 1 {
563 s[0] = "neverallow requirements (empty)"
564 }
565 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566}
567
568func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800569 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
570 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800571 return includePath && !excludePath
572}
573
Paul Duffin35781882019-07-25 15:41:09 +0100574func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
575 if len(r.directDeps) == 0 {
576 return true
577 }
578
579 matches := false
580 ctx.VisitDirectDeps(func(m Module) {
581 if !matches {
582 name := ctx.OtherModuleName(m)
583 matches = r.directDeps[name]
584 }
585 })
586
587 return matches
588}
589
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100590func (r *rule) appliesToOsClass(osClass OsClass) bool {
591 if len(r.osClasses) == 0 {
592 return true
593 }
594
595 for _, c := range r.osClasses {
596 if c == osClass {
597 return true
598 }
599 }
600
601 return false
602}
603
Colin Crossfd4f7432019-03-05 15:06:16 -0800604func (r *rule) appliesToModuleType(moduleType string) bool {
605 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
606}
607
Anton Hanssone1b18362021-12-23 15:05:38 +0000608func (r *rule) appliesToProperties(properties []interface{}) bool {
609 includeProps := hasAllProperties(properties, r.props)
610 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800611 return includeProps && !excludeProps
612}
613
Paul Duffinc8111702019-07-22 12:13:55 +0100614func StartsWith(prefix string) ValueMatcher {
615 return &startsWithMatcher{prefix}
616}
617
Anton Hansson45376402020-04-09 14:18:21 +0100618func Regexp(re string) ValueMatcher {
619 r, err := regexp.Compile(re)
620 if err != nil {
621 panic(err)
622 }
623 return &regexMatcher{r}
624}
625
Andrei Onea115e7e72020-06-05 21:14:03 +0100626func NotInList(allowed []string) ValueMatcher {
627 return &notInListMatcher{allowed}
628}
629
Steven Moreland65b3fd92017-12-06 14:18:35 -0800630// assorted utils
631
632func cleanPaths(paths []string) []string {
633 res := make([]string, len(paths))
634 for i, v := range paths {
635 res[i] = filepath.Clean(v) + "/"
636 }
637 return res
638}
639
640func fieldNamesForProperties(propertyNames string) []string {
641 names := strings.Split(propertyNames, ".")
642 for i, v := range names {
643 names[i] = proptools.FieldNameForProperty(v)
644 }
645 return names
646}
647
Anton Hanssone1b18362021-12-23 15:05:38 +0000648func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800649 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000650 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800651 return true
652 }
653 }
654 return false
655}
656
Anton Hanssone1b18362021-12-23 15:05:38 +0000657func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800658 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000659 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800660 return false
661 }
662 }
663 return true
664}
665
Anton Hanssone1b18362021-12-23 15:05:38 +0000666func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800667 for _, propertyStruct := range properties {
668 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
669 for _, v := range prop.fields {
670 if !propertiesValue.IsValid() {
671 break
672 }
673 propertiesValue = propertiesValue.FieldByName(v)
674 }
675 if !propertiesValue.IsValid() {
676 continue
677 }
678
Paul Duffin73bf0542019-07-12 14:12:49 +0100679 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000680 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800681 }
682
683 if matchValue(propertiesValue, check) {
684 return true
685 }
686 }
687 return false
688}
689
690func matchValue(value reflect.Value, check func(string) bool) bool {
691 if !value.IsValid() {
692 return false
693 }
694
695 if value.Kind() == reflect.Ptr {
696 if value.IsNil() {
697 return check("")
698 }
699 value = value.Elem()
700 }
701
702 switch value.Kind() {
703 case reflect.String:
704 return check(value.String())
705 case reflect.Bool:
706 return check(strconv.FormatBool(value.Bool()))
707 case reflect.Int:
708 return check(strconv.FormatInt(value.Int(), 10))
709 case reflect.Slice:
710 slice, ok := value.Interface().([]string)
711 if !ok {
712 panic("Can only handle slice of string")
713 }
714 for _, v := range slice {
715 if check(v) {
716 return true
717 }
718 }
719 return false
720 }
721
722 panic("Can't handle type: " + value.Kind().String())
723}
Paul Duffin115445b2019-08-07 15:31:07 +0100724
725var neverallowRulesKey = NewOnceKey("neverallowRules")
726
727func neverallowRules(config Config) []Rule {
728 return config.Once(neverallowRulesKey, func() interface{} {
729 // No test rules were set by setTestNeverallowRules, use the global rules
730 return neverallows
731 }).([]Rule)
732}
733
734// Overrides the default neverallow rules for the supplied config.
735//
736// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100737func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100738 config.Once(neverallowRulesKey, func() interface{} { return testRules })
739}
Paul Duffin45338f02021-03-30 23:07:52 +0100740
741// Prepares for a test by setting neverallow rules and enabling the mutator.
742//
743// If the supplied rules are nil then the default rules are used.
744func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
745 return GroupFixturePreparers(
746 FixtureModifyConfig(func(config Config) {
747 if testRules != nil {
748 setTestNeverallowRules(config, testRules)
749 }
750 }),
751 FixtureRegisterWithContext(func(ctx RegistrationContext) {
752 ctx.PostDepsMutators(registerNeverallowMutator)
753 }),
754 )
755}