blob: cf149b29da8ecbcd085987413ffcf9a655505fcd [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",
Rex Hoffman54641d22022-08-25 17:29:50 +0000165 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000166 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800167 }
168
Paul Duffin730f2a52019-06-27 14:08:51 +0100169 return []Rule{
170 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700171 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100172 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700173 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800174 }
175}
176
Colin Crossc511bc52020-04-07 16:50:32 +0000177func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700178 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000179 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
180 // This sometimes works because the APEX modules that contain derive_sdk and
181 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
182 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100183 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700184 // These are for apps and shouldn't be used by non-SDK variant modules.
185 "prebuilts/ndk",
186 "tools/test/graphicsbenchmark/apps/sample_app",
187 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700188 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000189 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000190 }
191
Colin Cross440e0d02020-06-11 11:32:11 -0700192 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000193 // android_native_app_glue and libRSSupport use native_window.h but target old
194 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
195 // so they can't add libnativewindow to shared_libs to get the header directory
196 // for the platform variant. Allow them to use the platform variant
197 // property to set shared_libs.
198 "prebuilts/ndk",
199 "frameworks/rs",
200 }
201
202 return []Rule{
203 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700204 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000205 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700206 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000207 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700208 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000209 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700210 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000211 }
212}
213
David Srbeckye033cba2020-05-20 22:20:28 +0100214func createUncompressDexRules() []Rule {
215 return []Rule{
216 NeverAllow().
217 NotIn("art").
218 WithMatcher("uncompress_dex", isSetMatcherInstance).
219 Because("uncompress_dex is only allowed for certain jars for test in art."),
220 }
221}
222
Yifan Hong696ed4d2020-07-27 12:59:58 -0700223func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900224 allowlist := []string{
225 // libwifi_hal uses makefile_goal for its dependencies
226 "frameworks/opt/net/wifi/libwifi_hal",
227 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700228 return []Rule{
229 NeverAllow().
230 ModuleType("makefile_goal").
231 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900232 NotIn(allowlist...).
233 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700234 }
235}
236
Inseob Kim800d1142021-06-14 12:03:51 +0900237func createInitFirstStageRules() []Rule {
238 return []Rule{
239 NeverAllow().
240 Without("name", "init_first_stage").
241 With("install_in_root", "true").
242 Because("install_in_root is only for init_first_stage."),
243 }
244}
245
Jiyong Park3c306f32022-04-05 15:29:53 +0900246func createProhibitFrameworkAccessRules() []Rule {
247 return []Rule{
248 NeverAllow().
249 With("libs", "framework").
250 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
251 Because("framework can't be used when building against SDK"),
252 }
253}
254
Steven Moreland65b3fd92017-12-06 14:18:35 -0800255func neverallowMutator(ctx BottomUpMutatorContext) {
256 m, ok := ctx.Module().(Module)
257 if !ok {
258 return
259 }
260
261 dir := ctx.ModuleDir() + "/"
262 properties := m.GetProperties()
263
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100264 osClass := ctx.Module().Target().Os.Class
265
Paul Duffin115445b2019-08-07 15:31:07 +0100266 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100267 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800268 if !n.appliesToPath(dir) {
269 continue
270 }
271
Colin Crossfd4f7432019-03-05 15:06:16 -0800272 if !n.appliesToModuleType(ctx.ModuleType()) {
273 continue
274 }
275
Anton Hanssone1b18362021-12-23 15:05:38 +0000276 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800277 continue
278 }
279
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100280 if !n.appliesToOsClass(osClass) {
281 continue
282 }
283
Paul Duffin35781882019-07-25 15:41:09 +0100284 if !n.appliesToDirectDeps(ctx) {
285 continue
286 }
287
Steven Moreland65b3fd92017-12-06 14:18:35 -0800288 ctx.ModuleErrorf("violates " + n.String())
289 }
290}
291
Paul Duffin73bf0542019-07-12 14:12:49 +0100292type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000293 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100294 String() string
295}
296
297type equalMatcher struct {
298 expected string
299}
300
Anton Hanssone1b18362021-12-23 15:05:38 +0000301func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100302 return m.expected == value
303}
304
305func (m *equalMatcher) String() string {
306 return "=" + m.expected
307}
308
309type anyMatcher struct {
310}
311
Anton Hanssone1b18362021-12-23 15:05:38 +0000312func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100313 return true
314}
315
316func (m *anyMatcher) String() string {
317 return "=*"
318}
319
320var anyMatcherInstance = &anyMatcher{}
321
Paul Duffinc8111702019-07-22 12:13:55 +0100322type startsWithMatcher struct {
323 prefix string
324}
325
Anton Hanssone1b18362021-12-23 15:05:38 +0000326func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100327 return strings.HasPrefix(value, m.prefix)
328}
329
330func (m *startsWithMatcher) String() string {
331 return ".starts-with(" + m.prefix + ")"
332}
333
Anton Hansson45376402020-04-09 14:18:21 +0100334type regexMatcher struct {
335 re *regexp.Regexp
336}
337
Anton Hanssone1b18362021-12-23 15:05:38 +0000338func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100339 return m.re.MatchString(value)
340}
341
342func (m *regexMatcher) String() string {
343 return ".regexp(" + m.re.String() + ")"
344}
345
Andrei Onea115e7e72020-06-05 21:14:03 +0100346type notInListMatcher struct {
347 allowed []string
348}
349
Anton Hanssone1b18362021-12-23 15:05:38 +0000350func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100351 return !InList(value, m.allowed)
352}
353
354func (m *notInListMatcher) String() string {
355 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
356}
357
Colin Crossc511bc52020-04-07 16:50:32 +0000358type isSetMatcher struct{}
359
Anton Hanssone1b18362021-12-23 15:05:38 +0000360func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000361 return value != ""
362}
363
364func (m *isSetMatcher) String() string {
365 return ".is-set"
366}
367
368var isSetMatcherInstance = &isSetMatcher{}
369
Steven Moreland65b3fd92017-12-06 14:18:35 -0800370type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100371 fields []string // e.x.: Vndk.Enabled
372 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800373}
374
Liz Kammera3d79152021-10-28 18:14:04 -0400375func (r *ruleProperty) String() string {
376 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
377}
378
379type ruleProperties []ruleProperty
380
381func (r ruleProperties) String() string {
382 var s []string
383 for _, r := range r {
384 s = append(s, r.String())
385 }
386 return strings.Join(s, " ")
387}
388
Paul Duffin730f2a52019-06-27 14:08:51 +0100389// A NeverAllow rule.
390type Rule interface {
391 In(path ...string) Rule
392
393 NotIn(path ...string) Rule
394
Paul Duffin35781882019-07-25 15:41:09 +0100395 InDirectDeps(deps ...string) Rule
396
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100397 WithOsClass(osClasses ...OsClass) Rule
398
Paul Duffin730f2a52019-06-27 14:08:51 +0100399 ModuleType(types ...string) Rule
400
401 NotModuleType(types ...string) Rule
402
403 With(properties, value string) Rule
404
Paul Duffinc8111702019-07-22 12:13:55 +0100405 WithMatcher(properties string, matcher ValueMatcher) Rule
406
Paul Duffin730f2a52019-06-27 14:08:51 +0100407 Without(properties, value string) Rule
408
Paul Duffinc8111702019-07-22 12:13:55 +0100409 WithoutMatcher(properties string, matcher ValueMatcher) Rule
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411 Because(reason string) Rule
412}
413
Steven Moreland65b3fd92017-12-06 14:18:35 -0800414type rule struct {
415 // User string for why this is a thing.
416 reason string
417
418 paths []string
419 unlessPaths []string
420
Paul Duffin35781882019-07-25 15:41:09 +0100421 directDeps map[string]bool
422
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100423 osClasses []OsClass
424
Colin Crossfd4f7432019-03-05 15:06:16 -0800425 moduleTypes []string
426 unlessModuleTypes []string
427
Liz Kammera3d79152021-10-28 18:14:04 -0400428 props ruleProperties
429 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100430
431 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800432}
433
Paul Duffin730f2a52019-06-27 14:08:51 +0100434// Create a new NeverAllow rule.
435func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100436 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800437}
Colin Crossfd4f7432019-03-05 15:06:16 -0800438
Liz Kammera3d79152021-10-28 18:14:04 -0400439// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100440func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800441 r.paths = append(r.paths, cleanPaths(path)...)
442 return r
443}
Colin Crossfd4f7432019-03-05 15:06:16 -0800444
Liz Kammera3d79152021-10-28 18:14:04 -0400445// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100446func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
448 return r
449}
Colin Crossfd4f7432019-03-05 15:06:16 -0800450
Liz Kammera3d79152021-10-28 18:14:04 -0400451// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100452func (r *rule) InDirectDeps(deps ...string) Rule {
453 for _, d := range deps {
454 r.directDeps[d] = true
455 }
456 return r
457}
458
Liz Kammera3d79152021-10-28 18:14:04 -0400459// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100460func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
461 r.osClasses = append(r.osClasses, osClasses...)
462 return r
463}
464
Liz Kammera3d79152021-10-28 18:14:04 -0400465// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100466func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800467 r.moduleTypes = append(r.moduleTypes, types...)
468 return r
469}
470
Liz Kammera3d79152021-10-28 18:14:04 -0400471// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100472func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800473 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
474 return r
475}
476
Liz Kammera3d79152021-10-28 18:14:04 -0400477// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100478func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100479 return r.WithMatcher(properties, selectMatcher(value))
480}
481
Liz Kammera3d79152021-10-28 18:14:04 -0400482// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100483func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800484 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100485 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100486 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800487 })
488 return r
489}
Colin Crossfd4f7432019-03-05 15:06:16 -0800490
Liz Kammera3d79152021-10-28 18:14:04 -0400491// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100492func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100493 return r.WithoutMatcher(properties, selectMatcher(value))
494}
495
Liz Kammera3d79152021-10-28 18:14:04 -0400496// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100497func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800498 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100499 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100500 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800501 })
502 return r
503}
Colin Crossfd4f7432019-03-05 15:06:16 -0800504
Paul Duffin73bf0542019-07-12 14:12:49 +0100505func selectMatcher(expected string) ValueMatcher {
506 if expected == "*" {
507 return anyMatcherInstance
508 }
509 return &equalMatcher{expected: expected}
510}
511
Liz Kammera3d79152021-10-28 18:14:04 -0400512// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100513func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800514 r.reason = reason
515 return r
516}
517
518func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400519 s := []string{"neverallow requirements. Not allowed:"}
520 if len(r.paths) > 0 {
521 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800522 }
Liz Kammera3d79152021-10-28 18:14:04 -0400523 if len(r.moduleTypes) > 0 {
524 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800525 }
Liz Kammera3d79152021-10-28 18:14:04 -0400526 if len(r.props) > 0 {
527 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800528 }
Liz Kammera3d79152021-10-28 18:14:04 -0400529 if len(r.directDeps) > 0 {
530 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800531 }
Liz Kammera3d79152021-10-28 18:14:04 -0400532 if len(r.osClasses) > 0 {
533 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100534 }
Liz Kammera3d79152021-10-28 18:14:04 -0400535 if len(r.unlessPaths) > 0 {
536 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
537 }
538 if len(r.unlessModuleTypes) > 0 {
539 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
540 }
541 if len(r.unlessProps) > 0 {
542 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100543 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800544 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400545 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800546 }
Liz Kammera3d79152021-10-28 18:14:04 -0400547 if len(s) == 1 {
548 s[0] = "neverallow requirements (empty)"
549 }
550 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800551}
552
553func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800554 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
555 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800556 return includePath && !excludePath
557}
558
Paul Duffin35781882019-07-25 15:41:09 +0100559func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
560 if len(r.directDeps) == 0 {
561 return true
562 }
563
564 matches := false
565 ctx.VisitDirectDeps(func(m Module) {
566 if !matches {
567 name := ctx.OtherModuleName(m)
568 matches = r.directDeps[name]
569 }
570 })
571
572 return matches
573}
574
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100575func (r *rule) appliesToOsClass(osClass OsClass) bool {
576 if len(r.osClasses) == 0 {
577 return true
578 }
579
580 for _, c := range r.osClasses {
581 if c == osClass {
582 return true
583 }
584 }
585
586 return false
587}
588
Colin Crossfd4f7432019-03-05 15:06:16 -0800589func (r *rule) appliesToModuleType(moduleType string) bool {
590 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
591}
592
Anton Hanssone1b18362021-12-23 15:05:38 +0000593func (r *rule) appliesToProperties(properties []interface{}) bool {
594 includeProps := hasAllProperties(properties, r.props)
595 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800596 return includeProps && !excludeProps
597}
598
Paul Duffinc8111702019-07-22 12:13:55 +0100599func StartsWith(prefix string) ValueMatcher {
600 return &startsWithMatcher{prefix}
601}
602
Anton Hansson45376402020-04-09 14:18:21 +0100603func Regexp(re string) ValueMatcher {
604 r, err := regexp.Compile(re)
605 if err != nil {
606 panic(err)
607 }
608 return &regexMatcher{r}
609}
610
Andrei Onea115e7e72020-06-05 21:14:03 +0100611func NotInList(allowed []string) ValueMatcher {
612 return &notInListMatcher{allowed}
613}
614
Steven Moreland65b3fd92017-12-06 14:18:35 -0800615// assorted utils
616
617func cleanPaths(paths []string) []string {
618 res := make([]string, len(paths))
619 for i, v := range paths {
620 res[i] = filepath.Clean(v) + "/"
621 }
622 return res
623}
624
625func fieldNamesForProperties(propertyNames string) []string {
626 names := strings.Split(propertyNames, ".")
627 for i, v := range names {
628 names[i] = proptools.FieldNameForProperty(v)
629 }
630 return names
631}
632
Anton Hanssone1b18362021-12-23 15:05:38 +0000633func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800634 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000635 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800636 return true
637 }
638 }
639 return false
640}
641
Anton Hanssone1b18362021-12-23 15:05:38 +0000642func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800643 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000644 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800645 return false
646 }
647 }
648 return true
649}
650
Anton Hanssone1b18362021-12-23 15:05:38 +0000651func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800652 for _, propertyStruct := range properties {
653 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
654 for _, v := range prop.fields {
655 if !propertiesValue.IsValid() {
656 break
657 }
658 propertiesValue = propertiesValue.FieldByName(v)
659 }
660 if !propertiesValue.IsValid() {
661 continue
662 }
663
Paul Duffin73bf0542019-07-12 14:12:49 +0100664 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000665 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800666 }
667
668 if matchValue(propertiesValue, check) {
669 return true
670 }
671 }
672 return false
673}
674
675func matchValue(value reflect.Value, check func(string) bool) bool {
676 if !value.IsValid() {
677 return false
678 }
679
680 if value.Kind() == reflect.Ptr {
681 if value.IsNil() {
682 return check("")
683 }
684 value = value.Elem()
685 }
686
687 switch value.Kind() {
688 case reflect.String:
689 return check(value.String())
690 case reflect.Bool:
691 return check(strconv.FormatBool(value.Bool()))
692 case reflect.Int:
693 return check(strconv.FormatInt(value.Int(), 10))
694 case reflect.Slice:
695 slice, ok := value.Interface().([]string)
696 if !ok {
697 panic("Can only handle slice of string")
698 }
699 for _, v := range slice {
700 if check(v) {
701 return true
702 }
703 }
704 return false
705 }
706
707 panic("Can't handle type: " + value.Kind().String())
708}
Paul Duffin115445b2019-08-07 15:31:07 +0100709
710var neverallowRulesKey = NewOnceKey("neverallowRules")
711
712func neverallowRules(config Config) []Rule {
713 return config.Once(neverallowRulesKey, func() interface{} {
714 // No test rules were set by setTestNeverallowRules, use the global rules
715 return neverallows
716 }).([]Rule)
717}
718
719// Overrides the default neverallow rules for the supplied config.
720//
721// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100722func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100723 config.Once(neverallowRulesKey, func() interface{} { return testRules })
724}
Paul Duffin45338f02021-03-30 23:07:52 +0100725
726// Prepares for a test by setting neverallow rules and enabling the mutator.
727//
728// If the supplied rules are nil then the default rules are used.
729func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
730 return GroupFixturePreparers(
731 FixtureModifyConfig(func(config Config) {
732 if testRules != nil {
733 setTestNeverallowRules(config, testRules)
734 }
735 }),
736 FixtureRegisterWithContext(func(ctx RegistrationContext) {
737 ctx.PostDepsMutators(registerNeverallowMutator)
738 }),
739 )
740}