blob: 293bac865dfbbb497ea4918916da56ff3a7895c2 [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())
Neil Fullerdf5f3562018-10-21 17:19:10 +010062}
Steven Moreland65b3fd92017-12-06 14:18:35 -080063
Paul Duffin730f2a52019-06-27 14:08:51 +010064// Add a NeverAllow rule to the set of rules to apply.
65func AddNeverAllowRules(rules ...Rule) {
66 neverallows = append(neverallows, rules...)
67}
68
Jingwen Chen1735b2e2022-10-10 14:30:03 +000069func createBp2BuildRule() Rule {
70 return NeverAllow().
71 With("bazel_module.bp2build_available", "true").
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000072 NotIn("soong_tests"). // only used in tests
Jingwen Chen1735b2e2022-10-10 14:30:03 +000073 Because("setting bp2build_available in Android.bp is not " +
74 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000075}
76
Sam Delmerico46d08b42022-11-15 15:51:04 -050077var (
78 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010079 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000080 "art/libnativebridge",
81 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010082 "libcore",
83 "libnativehelper",
84 "external/apache-harmony",
85 "external/apache-xml",
86 "external/boringssl",
87 "external/bouncycastle",
88 "external/conscrypt",
89 "external/icu",
90 "external/okhttp",
91 "external/vixl",
92 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010093 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050094 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000095 "frameworks/av/apex",
96 "frameworks/av/tools",
97 "frameworks/native/cmds",
98 "system/apex",
99 "system/bpf",
100 "system/gatekeeper",
101 "system/hwservicemanager",
102 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000103 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000104 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000105 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500106)
Paul Duffinc8111702019-07-22 12:13:55 +0100107
Sam Delmerico46d08b42022-11-15 15:51:04 -0500108func createIncludeDirsRules() []Rule {
109 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000110
Sam Delmerico46d08b42022-11-15 15:51:04 -0500111 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100112 rule :=
113 NeverAllow().
114 WithMatcher("include_dirs", StartsWith(path+"/")).
115 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
116 " to use alternate mechanisms and so can no longer be used.")
117
118 rules = append(rules, rule)
119 }
120
Sam Delmerico46d08b42022-11-15 15:51:04 -0500121 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000122 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
123 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
124 " to use alternate mechanisms and so can no longer be used.")
125 rules = append(rules, rule)
126 }
127
Paul Duffinc8111702019-07-22 12:13:55 +0100128 return rules
129}
130
Paul Duffin730f2a52019-06-27 14:08:51 +0100131func createTrebleRules() []Rule {
132 return []Rule{
133 NeverAllow().
134 In("vendor", "device").
135 With("vndk.enabled", "true").
136 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900137 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100138 Because("the VNDK can never contain a library that is device dependent."),
139 NeverAllow().
140 With("vndk.enabled", "true").
141 Without("vendor", "true").
142 Without("owner", "").
143 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800144
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800147 Without("name", "libhidlbase-combined-impl").
148 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100149 With("product_variables.enforce_vintf_manifest.cflags", "*").
150 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100151
152 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100153 NeverAllow().
154 Without("name", "libc_bionic_ndk").
155 With("product_variables.treble_linker_namespaces.cflags", "*").
156 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100157
158 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100160 }
161}
162
Paul Duffin730f2a52019-06-27 14:08:51 +0100163func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700164 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700165 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700166 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800167 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000168 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000169 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800170 }
171
Paul Duffin730f2a52019-06-27 14:08:51 +0100172 return []Rule{
173 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700174 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100175 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700176 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800177 }
178}
179
Colin Crossc511bc52020-04-07 16:50:32 +0000180func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700181 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000182 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
183 // This sometimes works because the APEX modules that contain derive_sdk and
184 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
185 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100186 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700187 // These are for apps and shouldn't be used by non-SDK variant modules.
188 "prebuilts/ndk",
189 "tools/test/graphicsbenchmark/apps/sample_app",
190 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700191 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000192 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000193 }
194
Colin Cross440e0d02020-06-11 11:32:11 -0700195 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000196 // android_native_app_glue and libRSSupport use native_window.h but target old
197 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
198 // so they can't add libnativewindow to shared_libs to get the header directory
199 // for the platform variant. Allow them to use the platform variant
200 // property to set shared_libs.
201 "prebuilts/ndk",
202 "frameworks/rs",
203 }
204
205 return []Rule{
206 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700207 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000208 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700209 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000210 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700211 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000212 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700213 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000214 }
215}
216
David Srbeckye033cba2020-05-20 22:20:28 +0100217func createUncompressDexRules() []Rule {
218 return []Rule{
219 NeverAllow().
220 NotIn("art").
221 WithMatcher("uncompress_dex", isSetMatcherInstance).
222 Because("uncompress_dex is only allowed for certain jars for test in art."),
223 }
224}
225
Yifan Hong696ed4d2020-07-27 12:59:58 -0700226func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900227 allowlist := []string{
228 // libwifi_hal uses makefile_goal for its dependencies
229 "frameworks/opt/net/wifi/libwifi_hal",
230 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700231 return []Rule{
232 NeverAllow().
233 ModuleType("makefile_goal").
234 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900235 NotIn(allowlist...).
236 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700237 }
238}
239
Inseob Kim800d1142021-06-14 12:03:51 +0900240func createInitFirstStageRules() []Rule {
241 return []Rule{
242 NeverAllow().
243 Without("name", "init_first_stage").
244 With("install_in_root", "true").
245 Because("install_in_root is only for init_first_stage."),
246 }
247}
248
Jiyong Park3c306f32022-04-05 15:29:53 +0900249func createProhibitFrameworkAccessRules() []Rule {
250 return []Rule{
251 NeverAllow().
252 With("libs", "framework").
253 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
254 Because("framework can't be used when building against SDK"),
255 }
256}
257
Steven Moreland65b3fd92017-12-06 14:18:35 -0800258func neverallowMutator(ctx BottomUpMutatorContext) {
259 m, ok := ctx.Module().(Module)
260 if !ok {
261 return
262 }
263
264 dir := ctx.ModuleDir() + "/"
265 properties := m.GetProperties()
266
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100267 osClass := ctx.Module().Target().Os.Class
268
Paul Duffin115445b2019-08-07 15:31:07 +0100269 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100270 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800271 if !n.appliesToPath(dir) {
272 continue
273 }
274
Colin Crossfd4f7432019-03-05 15:06:16 -0800275 if !n.appliesToModuleType(ctx.ModuleType()) {
276 continue
277 }
278
Anton Hanssone1b18362021-12-23 15:05:38 +0000279 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800280 continue
281 }
282
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100283 if !n.appliesToOsClass(osClass) {
284 continue
285 }
286
Paul Duffin35781882019-07-25 15:41:09 +0100287 if !n.appliesToDirectDeps(ctx) {
288 continue
289 }
290
Steven Moreland65b3fd92017-12-06 14:18:35 -0800291 ctx.ModuleErrorf("violates " + n.String())
292 }
293}
294
Paul Duffin73bf0542019-07-12 14:12:49 +0100295type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000296 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100297 String() string
298}
299
300type equalMatcher struct {
301 expected string
302}
303
Anton Hanssone1b18362021-12-23 15:05:38 +0000304func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100305 return m.expected == value
306}
307
308func (m *equalMatcher) String() string {
309 return "=" + m.expected
310}
311
312type anyMatcher struct {
313}
314
Anton Hanssone1b18362021-12-23 15:05:38 +0000315func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100316 return true
317}
318
319func (m *anyMatcher) String() string {
320 return "=*"
321}
322
323var anyMatcherInstance = &anyMatcher{}
324
Paul Duffinc8111702019-07-22 12:13:55 +0100325type startsWithMatcher struct {
326 prefix string
327}
328
Anton Hanssone1b18362021-12-23 15:05:38 +0000329func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100330 return strings.HasPrefix(value, m.prefix)
331}
332
333func (m *startsWithMatcher) String() string {
334 return ".starts-with(" + m.prefix + ")"
335}
336
Anton Hansson45376402020-04-09 14:18:21 +0100337type regexMatcher struct {
338 re *regexp.Regexp
339}
340
Anton Hanssone1b18362021-12-23 15:05:38 +0000341func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100342 return m.re.MatchString(value)
343}
344
345func (m *regexMatcher) String() string {
346 return ".regexp(" + m.re.String() + ")"
347}
348
Andrei Onea115e7e72020-06-05 21:14:03 +0100349type notInListMatcher struct {
350 allowed []string
351}
352
Anton Hanssone1b18362021-12-23 15:05:38 +0000353func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100354 return !InList(value, m.allowed)
355}
356
357func (m *notInListMatcher) String() string {
358 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
359}
360
Colin Crossc511bc52020-04-07 16:50:32 +0000361type isSetMatcher struct{}
362
Anton Hanssone1b18362021-12-23 15:05:38 +0000363func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000364 return value != ""
365}
366
367func (m *isSetMatcher) String() string {
368 return ".is-set"
369}
370
371var isSetMatcherInstance = &isSetMatcher{}
372
Steven Moreland65b3fd92017-12-06 14:18:35 -0800373type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100374 fields []string // e.x.: Vndk.Enabled
375 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800376}
377
Liz Kammera3d79152021-10-28 18:14:04 -0400378func (r *ruleProperty) String() string {
379 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
380}
381
382type ruleProperties []ruleProperty
383
384func (r ruleProperties) String() string {
385 var s []string
386 for _, r := range r {
387 s = append(s, r.String())
388 }
389 return strings.Join(s, " ")
390}
391
Paul Duffin730f2a52019-06-27 14:08:51 +0100392// A NeverAllow rule.
393type Rule interface {
394 In(path ...string) Rule
395
396 NotIn(path ...string) Rule
397
Paul Duffin35781882019-07-25 15:41:09 +0100398 InDirectDeps(deps ...string) Rule
399
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100400 WithOsClass(osClasses ...OsClass) Rule
401
Paul Duffin730f2a52019-06-27 14:08:51 +0100402 ModuleType(types ...string) Rule
403
404 NotModuleType(types ...string) Rule
405
406 With(properties, value string) Rule
407
Paul Duffinc8111702019-07-22 12:13:55 +0100408 WithMatcher(properties string, matcher ValueMatcher) Rule
409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410 Without(properties, value string) Rule
411
Paul Duffinc8111702019-07-22 12:13:55 +0100412 WithoutMatcher(properties string, matcher ValueMatcher) Rule
413
Paul Duffin730f2a52019-06-27 14:08:51 +0100414 Because(reason string) Rule
415}
416
Steven Moreland65b3fd92017-12-06 14:18:35 -0800417type rule struct {
418 // User string for why this is a thing.
419 reason string
420
421 paths []string
422 unlessPaths []string
423
Paul Duffin35781882019-07-25 15:41:09 +0100424 directDeps map[string]bool
425
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100426 osClasses []OsClass
427
Colin Crossfd4f7432019-03-05 15:06:16 -0800428 moduleTypes []string
429 unlessModuleTypes []string
430
Liz Kammera3d79152021-10-28 18:14:04 -0400431 props ruleProperties
432 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100433
434 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800435}
436
Paul Duffin730f2a52019-06-27 14:08:51 +0100437// Create a new NeverAllow rule.
438func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100439 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800440}
Colin Crossfd4f7432019-03-05 15:06:16 -0800441
Liz Kammera3d79152021-10-28 18:14:04 -0400442// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100443func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800444 r.paths = append(r.paths, cleanPaths(path)...)
445 return r
446}
Colin Crossfd4f7432019-03-05 15:06:16 -0800447
Liz Kammera3d79152021-10-28 18:14:04 -0400448// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100449func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800450 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
451 return r
452}
Colin Crossfd4f7432019-03-05 15:06:16 -0800453
Liz Kammera3d79152021-10-28 18:14:04 -0400454// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100455func (r *rule) InDirectDeps(deps ...string) Rule {
456 for _, d := range deps {
457 r.directDeps[d] = true
458 }
459 return r
460}
461
Liz Kammera3d79152021-10-28 18:14:04 -0400462// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100463func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
464 r.osClasses = append(r.osClasses, osClasses...)
465 return r
466}
467
Liz Kammera3d79152021-10-28 18:14:04 -0400468// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100469func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800470 r.moduleTypes = append(r.moduleTypes, types...)
471 return r
472}
473
Liz Kammera3d79152021-10-28 18:14:04 -0400474// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100475func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800476 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
477 return r
478}
479
Liz Kammera3d79152021-10-28 18:14:04 -0400480// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100481func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100482 return r.WithMatcher(properties, selectMatcher(value))
483}
484
Liz Kammera3d79152021-10-28 18:14:04 -0400485// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100486func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100488 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100489 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800490 })
491 return r
492}
Colin Crossfd4f7432019-03-05 15:06:16 -0800493
Liz Kammera3d79152021-10-28 18:14:04 -0400494// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100495func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100496 return r.WithoutMatcher(properties, selectMatcher(value))
497}
498
Liz Kammera3d79152021-10-28 18:14:04 -0400499// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100500func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800501 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100502 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100503 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800504 })
505 return r
506}
Colin Crossfd4f7432019-03-05 15:06:16 -0800507
Paul Duffin73bf0542019-07-12 14:12:49 +0100508func selectMatcher(expected string) ValueMatcher {
509 if expected == "*" {
510 return anyMatcherInstance
511 }
512 return &equalMatcher{expected: expected}
513}
514
Liz Kammera3d79152021-10-28 18:14:04 -0400515// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100516func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800517 r.reason = reason
518 return r
519}
520
521func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400522 s := []string{"neverallow requirements. Not allowed:"}
523 if len(r.paths) > 0 {
524 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800525 }
Liz Kammera3d79152021-10-28 18:14:04 -0400526 if len(r.moduleTypes) > 0 {
527 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800528 }
Liz Kammera3d79152021-10-28 18:14:04 -0400529 if len(r.props) > 0 {
530 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800531 }
Liz Kammera3d79152021-10-28 18:14:04 -0400532 if len(r.directDeps) > 0 {
533 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800534 }
Liz Kammera3d79152021-10-28 18:14:04 -0400535 if len(r.osClasses) > 0 {
536 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100537 }
Liz Kammera3d79152021-10-28 18:14:04 -0400538 if len(r.unlessPaths) > 0 {
539 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
540 }
541 if len(r.unlessModuleTypes) > 0 {
542 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
543 }
544 if len(r.unlessProps) > 0 {
545 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100546 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400548 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800549 }
Liz Kammera3d79152021-10-28 18:14:04 -0400550 if len(s) == 1 {
551 s[0] = "neverallow requirements (empty)"
552 }
553 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800554}
555
556func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800557 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
558 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800559 return includePath && !excludePath
560}
561
Paul Duffin35781882019-07-25 15:41:09 +0100562func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
563 if len(r.directDeps) == 0 {
564 return true
565 }
566
567 matches := false
568 ctx.VisitDirectDeps(func(m Module) {
569 if !matches {
570 name := ctx.OtherModuleName(m)
571 matches = r.directDeps[name]
572 }
573 })
574
575 return matches
576}
577
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100578func (r *rule) appliesToOsClass(osClass OsClass) bool {
579 if len(r.osClasses) == 0 {
580 return true
581 }
582
583 for _, c := range r.osClasses {
584 if c == osClass {
585 return true
586 }
587 }
588
589 return false
590}
591
Colin Crossfd4f7432019-03-05 15:06:16 -0800592func (r *rule) appliesToModuleType(moduleType string) bool {
593 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
594}
595
Anton Hanssone1b18362021-12-23 15:05:38 +0000596func (r *rule) appliesToProperties(properties []interface{}) bool {
597 includeProps := hasAllProperties(properties, r.props)
598 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800599 return includeProps && !excludeProps
600}
601
Paul Duffinc8111702019-07-22 12:13:55 +0100602func StartsWith(prefix string) ValueMatcher {
603 return &startsWithMatcher{prefix}
604}
605
Anton Hansson45376402020-04-09 14:18:21 +0100606func Regexp(re string) ValueMatcher {
607 r, err := regexp.Compile(re)
608 if err != nil {
609 panic(err)
610 }
611 return &regexMatcher{r}
612}
613
Andrei Onea115e7e72020-06-05 21:14:03 +0100614func NotInList(allowed []string) ValueMatcher {
615 return &notInListMatcher{allowed}
616}
617
Steven Moreland65b3fd92017-12-06 14:18:35 -0800618// assorted utils
619
620func cleanPaths(paths []string) []string {
621 res := make([]string, len(paths))
622 for i, v := range paths {
623 res[i] = filepath.Clean(v) + "/"
624 }
625 return res
626}
627
628func fieldNamesForProperties(propertyNames string) []string {
629 names := strings.Split(propertyNames, ".")
630 for i, v := range names {
631 names[i] = proptools.FieldNameForProperty(v)
632 }
633 return names
634}
635
Anton Hanssone1b18362021-12-23 15:05:38 +0000636func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800637 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000638 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800639 return true
640 }
641 }
642 return false
643}
644
Anton Hanssone1b18362021-12-23 15:05:38 +0000645func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000647 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 return false
649 }
650 }
651 return true
652}
653
Anton Hanssone1b18362021-12-23 15:05:38 +0000654func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800655 for _, propertyStruct := range properties {
656 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
657 for _, v := range prop.fields {
658 if !propertiesValue.IsValid() {
659 break
660 }
661 propertiesValue = propertiesValue.FieldByName(v)
662 }
663 if !propertiesValue.IsValid() {
664 continue
665 }
666
Paul Duffin73bf0542019-07-12 14:12:49 +0100667 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000668 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800669 }
670
671 if matchValue(propertiesValue, check) {
672 return true
673 }
674 }
675 return false
676}
677
678func matchValue(value reflect.Value, check func(string) bool) bool {
679 if !value.IsValid() {
680 return false
681 }
682
683 if value.Kind() == reflect.Ptr {
684 if value.IsNil() {
685 return check("")
686 }
687 value = value.Elem()
688 }
689
690 switch value.Kind() {
691 case reflect.String:
692 return check(value.String())
693 case reflect.Bool:
694 return check(strconv.FormatBool(value.Bool()))
695 case reflect.Int:
696 return check(strconv.FormatInt(value.Int(), 10))
697 case reflect.Slice:
698 slice, ok := value.Interface().([]string)
699 if !ok {
700 panic("Can only handle slice of string")
701 }
702 for _, v := range slice {
703 if check(v) {
704 return true
705 }
706 }
707 return false
708 }
709
710 panic("Can't handle type: " + value.Kind().String())
711}
Paul Duffin115445b2019-08-07 15:31:07 +0100712
713var neverallowRulesKey = NewOnceKey("neverallowRules")
714
715func neverallowRules(config Config) []Rule {
716 return config.Once(neverallowRulesKey, func() interface{} {
717 // No test rules were set by setTestNeverallowRules, use the global rules
718 return neverallows
719 }).([]Rule)
720}
721
722// Overrides the default neverallow rules for the supplied config.
723//
724// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100725func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100726 config.Once(neverallowRulesKey, func() interface{} { return testRules })
727}
Paul Duffin45338f02021-03-30 23:07:52 +0100728
729// Prepares for a test by setting neverallow rules and enabling the mutator.
730//
731// If the supplied rules are nil then the default rules are used.
732func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
733 return GroupFixturePreparers(
734 FixtureModifyConfig(func(config Config) {
735 if testRules != nil {
736 setTestNeverallowRules(config, testRules)
737 }
738 }),
739 FixtureRegisterWithContext(func(ctx RegistrationContext) {
740 ctx.PostDepsMutators(registerNeverallowMutator)
741 }),
742 )
743}