blob: 1cdccc317a2aba5a8ba5cc1d10baf3505ed919c5 [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").
72 Because("setting bp2build_available in Android.bp is not " +
73 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000074}
75
Paul Duffinc8111702019-07-22 12:13:55 +010076func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000077 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010078 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000079 "art/libnativebridge",
80 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010081 "libcore",
82 "libnativehelper",
83 "external/apache-harmony",
84 "external/apache-xml",
85 "external/boringssl",
86 "external/bouncycastle",
87 "external/conscrypt",
88 "external/icu",
89 "external/okhttp",
90 "external/vixl",
91 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010092 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000093 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000094 "frameworks/av/apex",
95 "frameworks/av/tools",
96 "frameworks/native/cmds",
97 "system/apex",
98 "system/bpf",
99 "system/gatekeeper",
100 "system/hwservicemanager",
101 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000102 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000103 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000104 }
Paul Duffinc8111702019-07-22 12:13:55 +0100105
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000106 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
107
108 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100109 rule :=
110 NeverAllow().
111 WithMatcher("include_dirs", StartsWith(path+"/")).
112 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
113 " to use alternate mechanisms and so can no longer be used.")
114
115 rules = append(rules, rule)
116 }
117
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000118 for _, path := range noUseIncludeDir {
119 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
120 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
121 " to use alternate mechanisms and so can no longer be used.")
122 rules = append(rules, rule)
123 }
124
Paul Duffinc8111702019-07-22 12:13:55 +0100125 return rules
126}
127
Paul Duffin730f2a52019-06-27 14:08:51 +0100128func createTrebleRules() []Rule {
129 return []Rule{
130 NeverAllow().
131 In("vendor", "device").
132 With("vndk.enabled", "true").
133 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900134 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100135 Because("the VNDK can never contain a library that is device dependent."),
136 NeverAllow().
137 With("vndk.enabled", "true").
138 Without("vendor", "true").
139 Without("owner", "").
140 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800141
Neil Fullerdf5f3562018-10-21 17:19:10 +0100142 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100143 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800144 Without("name", "libhidlbase-combined-impl").
145 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 With("product_variables.enforce_vintf_manifest.cflags", "*").
147 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100148
149 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100150 NeverAllow().
151 Without("name", "libc_bionic_ndk").
152 With("product_variables.treble_linker_namespaces.cflags", "*").
153 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100154
155 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100156 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100157 }
158}
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700161 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700162 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700163 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800164 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000165 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800166 }
167
Paul Duffin730f2a52019-06-27 14:08:51 +0100168 return []Rule{
169 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700170 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100171 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700172 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800173 }
174}
175
Colin Crossc511bc52020-04-07 16:50:32 +0000176func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700177 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000178 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
179 // This sometimes works because the APEX modules that contain derive_sdk and
180 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
181 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100182 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700183 // These are for apps and shouldn't be used by non-SDK variant modules.
184 "prebuilts/ndk",
185 "tools/test/graphicsbenchmark/apps/sample_app",
186 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700187 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000188 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000189 }
190
Colin Cross440e0d02020-06-11 11:32:11 -0700191 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000192 // android_native_app_glue and libRSSupport use native_window.h but target old
193 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
194 // so they can't add libnativewindow to shared_libs to get the header directory
195 // for the platform variant. Allow them to use the platform variant
196 // property to set shared_libs.
197 "prebuilts/ndk",
198 "frameworks/rs",
199 }
200
201 return []Rule{
202 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700203 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000204 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700205 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000206 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700207 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000208 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700209 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000210 }
211}
212
David Srbeckye033cba2020-05-20 22:20:28 +0100213func createUncompressDexRules() []Rule {
214 return []Rule{
215 NeverAllow().
216 NotIn("art").
217 WithMatcher("uncompress_dex", isSetMatcherInstance).
218 Because("uncompress_dex is only allowed for certain jars for test in art."),
219 }
220}
221
Yifan Hong696ed4d2020-07-27 12:59:58 -0700222func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900223 allowlist := []string{
224 // libwifi_hal uses makefile_goal for its dependencies
225 "frameworks/opt/net/wifi/libwifi_hal",
226 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700227 return []Rule{
228 NeverAllow().
229 ModuleType("makefile_goal").
230 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900231 NotIn(allowlist...).
232 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700233 }
234}
235
Inseob Kim800d1142021-06-14 12:03:51 +0900236func createInitFirstStageRules() []Rule {
237 return []Rule{
238 NeverAllow().
239 Without("name", "init_first_stage").
240 With("install_in_root", "true").
241 Because("install_in_root is only for init_first_stage."),
242 }
243}
244
Jiyong Park3c306f32022-04-05 15:29:53 +0900245func createProhibitFrameworkAccessRules() []Rule {
246 return []Rule{
247 NeverAllow().
248 With("libs", "framework").
249 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
250 Because("framework can't be used when building against SDK"),
251 }
252}
253
Steven Moreland65b3fd92017-12-06 14:18:35 -0800254func neverallowMutator(ctx BottomUpMutatorContext) {
255 m, ok := ctx.Module().(Module)
256 if !ok {
257 return
258 }
259
260 dir := ctx.ModuleDir() + "/"
261 properties := m.GetProperties()
262
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100263 osClass := ctx.Module().Target().Os.Class
264
Paul Duffin115445b2019-08-07 15:31:07 +0100265 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100266 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800267 if !n.appliesToPath(dir) {
268 continue
269 }
270
Colin Crossfd4f7432019-03-05 15:06:16 -0800271 if !n.appliesToModuleType(ctx.ModuleType()) {
272 continue
273 }
274
Anton Hanssone1b18362021-12-23 15:05:38 +0000275 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800276 continue
277 }
278
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100279 if !n.appliesToOsClass(osClass) {
280 continue
281 }
282
Paul Duffin35781882019-07-25 15:41:09 +0100283 if !n.appliesToDirectDeps(ctx) {
284 continue
285 }
286
Steven Moreland65b3fd92017-12-06 14:18:35 -0800287 ctx.ModuleErrorf("violates " + n.String())
288 }
289}
290
Paul Duffin73bf0542019-07-12 14:12:49 +0100291type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000292 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100293 String() string
294}
295
296type equalMatcher struct {
297 expected string
298}
299
Anton Hanssone1b18362021-12-23 15:05:38 +0000300func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100301 return m.expected == value
302}
303
304func (m *equalMatcher) String() string {
305 return "=" + m.expected
306}
307
308type anyMatcher struct {
309}
310
Anton Hanssone1b18362021-12-23 15:05:38 +0000311func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100312 return true
313}
314
315func (m *anyMatcher) String() string {
316 return "=*"
317}
318
319var anyMatcherInstance = &anyMatcher{}
320
Paul Duffinc8111702019-07-22 12:13:55 +0100321type startsWithMatcher struct {
322 prefix string
323}
324
Anton Hanssone1b18362021-12-23 15:05:38 +0000325func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100326 return strings.HasPrefix(value, m.prefix)
327}
328
329func (m *startsWithMatcher) String() string {
330 return ".starts-with(" + m.prefix + ")"
331}
332
Anton Hansson45376402020-04-09 14:18:21 +0100333type regexMatcher struct {
334 re *regexp.Regexp
335}
336
Anton Hanssone1b18362021-12-23 15:05:38 +0000337func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100338 return m.re.MatchString(value)
339}
340
341func (m *regexMatcher) String() string {
342 return ".regexp(" + m.re.String() + ")"
343}
344
Andrei Onea115e7e72020-06-05 21:14:03 +0100345type notInListMatcher struct {
346 allowed []string
347}
348
Anton Hanssone1b18362021-12-23 15:05:38 +0000349func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100350 return !InList(value, m.allowed)
351}
352
353func (m *notInListMatcher) String() string {
354 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
355}
356
Colin Crossc511bc52020-04-07 16:50:32 +0000357type isSetMatcher struct{}
358
Anton Hanssone1b18362021-12-23 15:05:38 +0000359func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000360 return value != ""
361}
362
363func (m *isSetMatcher) String() string {
364 return ".is-set"
365}
366
367var isSetMatcherInstance = &isSetMatcher{}
368
Steven Moreland65b3fd92017-12-06 14:18:35 -0800369type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100370 fields []string // e.x.: Vndk.Enabled
371 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800372}
373
Liz Kammera3d79152021-10-28 18:14:04 -0400374func (r *ruleProperty) String() string {
375 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
376}
377
378type ruleProperties []ruleProperty
379
380func (r ruleProperties) String() string {
381 var s []string
382 for _, r := range r {
383 s = append(s, r.String())
384 }
385 return strings.Join(s, " ")
386}
387
Paul Duffin730f2a52019-06-27 14:08:51 +0100388// A NeverAllow rule.
389type Rule interface {
390 In(path ...string) Rule
391
392 NotIn(path ...string) Rule
393
Paul Duffin35781882019-07-25 15:41:09 +0100394 InDirectDeps(deps ...string) Rule
395
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100396 WithOsClass(osClasses ...OsClass) Rule
397
Paul Duffin730f2a52019-06-27 14:08:51 +0100398 ModuleType(types ...string) Rule
399
400 NotModuleType(types ...string) Rule
401
402 With(properties, value string) Rule
403
Paul Duffinc8111702019-07-22 12:13:55 +0100404 WithMatcher(properties string, matcher ValueMatcher) Rule
405
Paul Duffin730f2a52019-06-27 14:08:51 +0100406 Without(properties, value string) Rule
407
Paul Duffinc8111702019-07-22 12:13:55 +0100408 WithoutMatcher(properties string, matcher ValueMatcher) Rule
409
Paul Duffin730f2a52019-06-27 14:08:51 +0100410 Because(reason string) Rule
411}
412
Steven Moreland65b3fd92017-12-06 14:18:35 -0800413type rule struct {
414 // User string for why this is a thing.
415 reason string
416
417 paths []string
418 unlessPaths []string
419
Paul Duffin35781882019-07-25 15:41:09 +0100420 directDeps map[string]bool
421
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100422 osClasses []OsClass
423
Colin Crossfd4f7432019-03-05 15:06:16 -0800424 moduleTypes []string
425 unlessModuleTypes []string
426
Liz Kammera3d79152021-10-28 18:14:04 -0400427 props ruleProperties
428 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100429
430 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800431}
432
Paul Duffin730f2a52019-06-27 14:08:51 +0100433// Create a new NeverAllow rule.
434func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100435 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800436}
Colin Crossfd4f7432019-03-05 15:06:16 -0800437
Liz Kammera3d79152021-10-28 18:14:04 -0400438// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100439func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800440 r.paths = append(r.paths, cleanPaths(path)...)
441 return r
442}
Colin Crossfd4f7432019-03-05 15:06:16 -0800443
Liz Kammera3d79152021-10-28 18:14:04 -0400444// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100445func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800446 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
447 return r
448}
Colin Crossfd4f7432019-03-05 15:06:16 -0800449
Liz Kammera3d79152021-10-28 18:14:04 -0400450// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100451func (r *rule) InDirectDeps(deps ...string) Rule {
452 for _, d := range deps {
453 r.directDeps[d] = true
454 }
455 return r
456}
457
Liz Kammera3d79152021-10-28 18:14:04 -0400458// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100459func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
460 r.osClasses = append(r.osClasses, osClasses...)
461 return r
462}
463
Liz Kammera3d79152021-10-28 18:14:04 -0400464// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100465func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800466 r.moduleTypes = append(r.moduleTypes, types...)
467 return r
468}
469
Liz Kammera3d79152021-10-28 18:14:04 -0400470// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100471func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800472 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
473 return r
474}
475
Liz Kammera3d79152021-10-28 18:14:04 -0400476// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100477func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100478 return r.WithMatcher(properties, selectMatcher(value))
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100482func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800483 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100484 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100485 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800486 })
487 return r
488}
Colin Crossfd4f7432019-03-05 15:06:16 -0800489
Liz Kammera3d79152021-10-28 18:14:04 -0400490// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100491func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100492 return r.WithoutMatcher(properties, selectMatcher(value))
493}
494
Liz Kammera3d79152021-10-28 18:14:04 -0400495// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100496func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100498 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100499 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 })
501 return r
502}
Colin Crossfd4f7432019-03-05 15:06:16 -0800503
Paul Duffin73bf0542019-07-12 14:12:49 +0100504func selectMatcher(expected string) ValueMatcher {
505 if expected == "*" {
506 return anyMatcherInstance
507 }
508 return &equalMatcher{expected: expected}
509}
510
Liz Kammera3d79152021-10-28 18:14:04 -0400511// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100512func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 r.reason = reason
514 return r
515}
516
517func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400518 s := []string{"neverallow requirements. Not allowed:"}
519 if len(r.paths) > 0 {
520 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800521 }
Liz Kammera3d79152021-10-28 18:14:04 -0400522 if len(r.moduleTypes) > 0 {
523 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524 }
Liz Kammera3d79152021-10-28 18:14:04 -0400525 if len(r.props) > 0 {
526 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800527 }
Liz Kammera3d79152021-10-28 18:14:04 -0400528 if len(r.directDeps) > 0 {
529 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800530 }
Liz Kammera3d79152021-10-28 18:14:04 -0400531 if len(r.osClasses) > 0 {
532 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100533 }
Liz Kammera3d79152021-10-28 18:14:04 -0400534 if len(r.unlessPaths) > 0 {
535 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
536 }
537 if len(r.unlessModuleTypes) > 0 {
538 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
539 }
540 if len(r.unlessProps) > 0 {
541 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100542 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800543 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400544 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545 }
Liz Kammera3d79152021-10-28 18:14:04 -0400546 if len(s) == 1 {
547 s[0] = "neverallow requirements (empty)"
548 }
549 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800550}
551
552func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800553 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
554 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800555 return includePath && !excludePath
556}
557
Paul Duffin35781882019-07-25 15:41:09 +0100558func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
559 if len(r.directDeps) == 0 {
560 return true
561 }
562
563 matches := false
564 ctx.VisitDirectDeps(func(m Module) {
565 if !matches {
566 name := ctx.OtherModuleName(m)
567 matches = r.directDeps[name]
568 }
569 })
570
571 return matches
572}
573
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100574func (r *rule) appliesToOsClass(osClass OsClass) bool {
575 if len(r.osClasses) == 0 {
576 return true
577 }
578
579 for _, c := range r.osClasses {
580 if c == osClass {
581 return true
582 }
583 }
584
585 return false
586}
587
Colin Crossfd4f7432019-03-05 15:06:16 -0800588func (r *rule) appliesToModuleType(moduleType string) bool {
589 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
590}
591
Anton Hanssone1b18362021-12-23 15:05:38 +0000592func (r *rule) appliesToProperties(properties []interface{}) bool {
593 includeProps := hasAllProperties(properties, r.props)
594 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800595 return includeProps && !excludeProps
596}
597
Paul Duffinc8111702019-07-22 12:13:55 +0100598func StartsWith(prefix string) ValueMatcher {
599 return &startsWithMatcher{prefix}
600}
601
Anton Hansson45376402020-04-09 14:18:21 +0100602func Regexp(re string) ValueMatcher {
603 r, err := regexp.Compile(re)
604 if err != nil {
605 panic(err)
606 }
607 return &regexMatcher{r}
608}
609
Andrei Onea115e7e72020-06-05 21:14:03 +0100610func NotInList(allowed []string) ValueMatcher {
611 return &notInListMatcher{allowed}
612}
613
Steven Moreland65b3fd92017-12-06 14:18:35 -0800614// assorted utils
615
616func cleanPaths(paths []string) []string {
617 res := make([]string, len(paths))
618 for i, v := range paths {
619 res[i] = filepath.Clean(v) + "/"
620 }
621 return res
622}
623
624func fieldNamesForProperties(propertyNames string) []string {
625 names := strings.Split(propertyNames, ".")
626 for i, v := range names {
627 names[i] = proptools.FieldNameForProperty(v)
628 }
629 return names
630}
631
Anton Hanssone1b18362021-12-23 15:05:38 +0000632func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800633 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000634 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800635 return true
636 }
637 }
638 return false
639}
640
Anton Hanssone1b18362021-12-23 15:05:38 +0000641func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800642 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000643 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800644 return false
645 }
646 }
647 return true
648}
649
Anton Hanssone1b18362021-12-23 15:05:38 +0000650func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800651 for _, propertyStruct := range properties {
652 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
653 for _, v := range prop.fields {
654 if !propertiesValue.IsValid() {
655 break
656 }
657 propertiesValue = propertiesValue.FieldByName(v)
658 }
659 if !propertiesValue.IsValid() {
660 continue
661 }
662
Paul Duffin73bf0542019-07-12 14:12:49 +0100663 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000664 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800665 }
666
667 if matchValue(propertiesValue, check) {
668 return true
669 }
670 }
671 return false
672}
673
674func matchValue(value reflect.Value, check func(string) bool) bool {
675 if !value.IsValid() {
676 return false
677 }
678
679 if value.Kind() == reflect.Ptr {
680 if value.IsNil() {
681 return check("")
682 }
683 value = value.Elem()
684 }
685
686 switch value.Kind() {
687 case reflect.String:
688 return check(value.String())
689 case reflect.Bool:
690 return check(strconv.FormatBool(value.Bool()))
691 case reflect.Int:
692 return check(strconv.FormatInt(value.Int(), 10))
693 case reflect.Slice:
694 slice, ok := value.Interface().([]string)
695 if !ok {
696 panic("Can only handle slice of string")
697 }
698 for _, v := range slice {
699 if check(v) {
700 return true
701 }
702 }
703 return false
704 }
705
706 panic("Can't handle type: " + value.Kind().String())
707}
Paul Duffin115445b2019-08-07 15:31:07 +0100708
709var neverallowRulesKey = NewOnceKey("neverallowRules")
710
711func neverallowRules(config Config) []Rule {
712 return config.Once(neverallowRulesKey, func() interface{} {
713 // No test rules were set by setTestNeverallowRules, use the global rules
714 return neverallows
715 }).([]Rule)
716}
717
718// Overrides the default neverallow rules for the supplied config.
719//
720// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100721func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100722 config.Once(neverallowRulesKey, func() interface{} { return testRules })
723}
Paul Duffin45338f02021-03-30 23:07:52 +0100724
725// Prepares for a test by setting neverallow rules and enabling the mutator.
726//
727// If the supplied rules are nil then the default rules are used.
728func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
729 return GroupFixturePreparers(
730 FixtureModifyConfig(func(config Config) {
731 if testRules != nil {
732 setTestNeverallowRules(config, testRules)
733 }
734 }),
735 FixtureRegisterWithContext(func(ctx RegistrationContext) {
736 ctx.PostDepsMutators(registerNeverallowMutator)
737 }),
738 )
739}