blob: e3bdd63b2b89969ea41de7cace3d140fb8c1274e [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()...)
Neil Fullerdf5f3562018-10-21 17:19:10 +010061}
Steven Moreland65b3fd92017-12-06 14:18:35 -080062
Paul Duffin730f2a52019-06-27 14:08:51 +010063// Add a NeverAllow rule to the set of rules to apply.
64func AddNeverAllowRules(rules ...Rule) {
65 neverallows = append(neverallows, rules...)
66}
67
Paul Duffinc8111702019-07-22 12:13:55 +010068func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000069 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010070 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000071 "art/libnativebridge",
72 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010073 "libcore",
74 "libnativehelper",
75 "external/apache-harmony",
76 "external/apache-xml",
77 "external/boringssl",
78 "external/bouncycastle",
79 "external/conscrypt",
80 "external/icu",
81 "external/okhttp",
82 "external/vixl",
83 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010084 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000085 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000086 "frameworks/av/apex",
87 "frameworks/av/tools",
88 "frameworks/native/cmds",
89 "system/apex",
90 "system/bpf",
91 "system/gatekeeper",
92 "system/hwservicemanager",
93 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000094 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000095 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 }
Paul Duffinc8111702019-07-22 12:13:55 +010097
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
99
100 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100101 rule :=
102 NeverAllow().
103 WithMatcher("include_dirs", StartsWith(path+"/")).
104 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
105 " to use alternate mechanisms and so can no longer be used.")
106
107 rules = append(rules, rule)
108 }
109
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000110 for _, path := range noUseIncludeDir {
111 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
112 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
113 " to use alternate mechanisms and so can no longer be used.")
114 rules = append(rules, rule)
115 }
116
Paul Duffinc8111702019-07-22 12:13:55 +0100117 return rules
118}
119
Paul Duffin730f2a52019-06-27 14:08:51 +0100120func createTrebleRules() []Rule {
121 return []Rule{
122 NeverAllow().
123 In("vendor", "device").
124 With("vndk.enabled", "true").
125 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900126 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100127 Because("the VNDK can never contain a library that is device dependent."),
128 NeverAllow().
129 With("vndk.enabled", "true").
130 Without("vendor", "true").
131 Without("owner", "").
132 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800133
Neil Fullerdf5f3562018-10-21 17:19:10 +0100134 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100135 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800136 Without("name", "libhidlbase-combined-impl").
137 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100138 With("product_variables.enforce_vintf_manifest.cflags", "*").
139 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100140
141 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100142 NeverAllow().
143 Without("name", "libc_bionic_ndk").
144 With("product_variables.treble_linker_namespaces.cflags", "*").
145 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146
147 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100148 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100149 }
150}
151
Paul Duffin730f2a52019-06-27 14:08:51 +0100152func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700153 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700154 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700155 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400156 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800157 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000158 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800159 }
160
Paul Duffin730f2a52019-06-27 14:08:51 +0100161 return []Rule{
162 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700163 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100164 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700165 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800166 }
167}
168
Colin Crossc511bc52020-04-07 16:50:32 +0000169func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700170 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000171 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
172 // This sometimes works because the APEX modules that contain derive_sdk and
173 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
174 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100175 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700176 // These are for apps and shouldn't be used by non-SDK variant modules.
177 "prebuilts/ndk",
178 "tools/test/graphicsbenchmark/apps/sample_app",
179 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700180 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000181 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000182 }
183
Colin Cross440e0d02020-06-11 11:32:11 -0700184 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000185 // android_native_app_glue and libRSSupport use native_window.h but target old
186 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
187 // so they can't add libnativewindow to shared_libs to get the header directory
188 // for the platform variant. Allow them to use the platform variant
189 // property to set shared_libs.
190 "prebuilts/ndk",
191 "frameworks/rs",
192 }
193
194 return []Rule{
195 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700196 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000197 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700198 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000199 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700200 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000201 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700202 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000203 }
204}
205
David Srbeckye033cba2020-05-20 22:20:28 +0100206func createUncompressDexRules() []Rule {
207 return []Rule{
208 NeverAllow().
209 NotIn("art").
210 WithMatcher("uncompress_dex", isSetMatcherInstance).
211 Because("uncompress_dex is only allowed for certain jars for test in art."),
212 }
213}
214
Yifan Hong696ed4d2020-07-27 12:59:58 -0700215func createMakefileGoalRules() []Rule {
216 return []Rule{
217 NeverAllow().
218 ModuleType("makefile_goal").
219 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Inseob Kima9078742021-12-29 08:59:00 +0000220 Because("Only boot images may be imported as a makefile goal."),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700221 }
222}
223
Inseob Kim800d1142021-06-14 12:03:51 +0900224func createInitFirstStageRules() []Rule {
225 return []Rule{
226 NeverAllow().
227 Without("name", "init_first_stage").
228 With("install_in_root", "true").
229 Because("install_in_root is only for init_first_stage."),
230 }
231}
232
Jiyong Park3c306f32022-04-05 15:29:53 +0900233func createProhibitFrameworkAccessRules() []Rule {
234 return []Rule{
235 NeverAllow().
236 With("libs", "framework").
237 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
238 Because("framework can't be used when building against SDK"),
239 }
240}
241
Steven Moreland65b3fd92017-12-06 14:18:35 -0800242func neverallowMutator(ctx BottomUpMutatorContext) {
243 m, ok := ctx.Module().(Module)
244 if !ok {
245 return
246 }
247
248 dir := ctx.ModuleDir() + "/"
249 properties := m.GetProperties()
250
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100251 osClass := ctx.Module().Target().Os.Class
252
Paul Duffin115445b2019-08-07 15:31:07 +0100253 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100254 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800255 if !n.appliesToPath(dir) {
256 continue
257 }
258
Colin Crossfd4f7432019-03-05 15:06:16 -0800259 if !n.appliesToModuleType(ctx.ModuleType()) {
260 continue
261 }
262
Anton Hanssone1b18362021-12-23 15:05:38 +0000263 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800264 continue
265 }
266
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100267 if !n.appliesToOsClass(osClass) {
268 continue
269 }
270
Paul Duffin35781882019-07-25 15:41:09 +0100271 if !n.appliesToDirectDeps(ctx) {
272 continue
273 }
274
Steven Moreland65b3fd92017-12-06 14:18:35 -0800275 ctx.ModuleErrorf("violates " + n.String())
276 }
277}
278
Paul Duffin73bf0542019-07-12 14:12:49 +0100279type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000280 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100281 String() string
282}
283
284type equalMatcher struct {
285 expected string
286}
287
Anton Hanssone1b18362021-12-23 15:05:38 +0000288func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100289 return m.expected == value
290}
291
292func (m *equalMatcher) String() string {
293 return "=" + m.expected
294}
295
296type anyMatcher struct {
297}
298
Anton Hanssone1b18362021-12-23 15:05:38 +0000299func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100300 return true
301}
302
303func (m *anyMatcher) String() string {
304 return "=*"
305}
306
307var anyMatcherInstance = &anyMatcher{}
308
Paul Duffinc8111702019-07-22 12:13:55 +0100309type startsWithMatcher struct {
310 prefix string
311}
312
Anton Hanssone1b18362021-12-23 15:05:38 +0000313func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100314 return strings.HasPrefix(value, m.prefix)
315}
316
317func (m *startsWithMatcher) String() string {
318 return ".starts-with(" + m.prefix + ")"
319}
320
Anton Hansson45376402020-04-09 14:18:21 +0100321type regexMatcher struct {
322 re *regexp.Regexp
323}
324
Anton Hanssone1b18362021-12-23 15:05:38 +0000325func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100326 return m.re.MatchString(value)
327}
328
329func (m *regexMatcher) String() string {
330 return ".regexp(" + m.re.String() + ")"
331}
332
Andrei Onea115e7e72020-06-05 21:14:03 +0100333type notInListMatcher struct {
334 allowed []string
335}
336
Anton Hanssone1b18362021-12-23 15:05:38 +0000337func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100338 return !InList(value, m.allowed)
339}
340
341func (m *notInListMatcher) String() string {
342 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
343}
344
Colin Crossc511bc52020-04-07 16:50:32 +0000345type isSetMatcher struct{}
346
Anton Hanssone1b18362021-12-23 15:05:38 +0000347func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000348 return value != ""
349}
350
351func (m *isSetMatcher) String() string {
352 return ".is-set"
353}
354
355var isSetMatcherInstance = &isSetMatcher{}
356
Steven Moreland65b3fd92017-12-06 14:18:35 -0800357type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100358 fields []string // e.x.: Vndk.Enabled
359 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800360}
361
Liz Kammera3d79152021-10-28 18:14:04 -0400362func (r *ruleProperty) String() string {
363 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
364}
365
366type ruleProperties []ruleProperty
367
368func (r ruleProperties) String() string {
369 var s []string
370 for _, r := range r {
371 s = append(s, r.String())
372 }
373 return strings.Join(s, " ")
374}
375
Paul Duffin730f2a52019-06-27 14:08:51 +0100376// A NeverAllow rule.
377type Rule interface {
378 In(path ...string) Rule
379
380 NotIn(path ...string) Rule
381
Paul Duffin35781882019-07-25 15:41:09 +0100382 InDirectDeps(deps ...string) Rule
383
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100384 WithOsClass(osClasses ...OsClass) Rule
385
Paul Duffin730f2a52019-06-27 14:08:51 +0100386 ModuleType(types ...string) Rule
387
388 NotModuleType(types ...string) Rule
389
390 With(properties, value string) Rule
391
Paul Duffinc8111702019-07-22 12:13:55 +0100392 WithMatcher(properties string, matcher ValueMatcher) Rule
393
Paul Duffin730f2a52019-06-27 14:08:51 +0100394 Without(properties, value string) Rule
395
Paul Duffinc8111702019-07-22 12:13:55 +0100396 WithoutMatcher(properties string, matcher ValueMatcher) Rule
397
Paul Duffin730f2a52019-06-27 14:08:51 +0100398 Because(reason string) Rule
399}
400
Steven Moreland65b3fd92017-12-06 14:18:35 -0800401type rule struct {
402 // User string for why this is a thing.
403 reason string
404
405 paths []string
406 unlessPaths []string
407
Paul Duffin35781882019-07-25 15:41:09 +0100408 directDeps map[string]bool
409
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100410 osClasses []OsClass
411
Colin Crossfd4f7432019-03-05 15:06:16 -0800412 moduleTypes []string
413 unlessModuleTypes []string
414
Liz Kammera3d79152021-10-28 18:14:04 -0400415 props ruleProperties
416 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100417
418 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800419}
420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421// Create a new NeverAllow rule.
422func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100423 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800424}
Colin Crossfd4f7432019-03-05 15:06:16 -0800425
Liz Kammera3d79152021-10-28 18:14:04 -0400426// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100427func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428 r.paths = append(r.paths, cleanPaths(path)...)
429 return r
430}
Colin Crossfd4f7432019-03-05 15:06:16 -0800431
Liz Kammera3d79152021-10-28 18:14:04 -0400432// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100433func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800434 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
435 return r
436}
Colin Crossfd4f7432019-03-05 15:06:16 -0800437
Liz Kammera3d79152021-10-28 18:14:04 -0400438// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100439func (r *rule) InDirectDeps(deps ...string) Rule {
440 for _, d := range deps {
441 r.directDeps[d] = true
442 }
443 return r
444}
445
Liz Kammera3d79152021-10-28 18:14:04 -0400446// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100447func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
448 r.osClasses = append(r.osClasses, osClasses...)
449 return r
450}
451
Liz Kammera3d79152021-10-28 18:14:04 -0400452// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100453func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800454 r.moduleTypes = append(r.moduleTypes, types...)
455 return r
456}
457
Liz Kammera3d79152021-10-28 18:14:04 -0400458// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100459func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800460 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
461 return r
462}
463
Liz Kammera3d79152021-10-28 18:14:04 -0400464// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100465func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100466 return r.WithMatcher(properties, selectMatcher(value))
467}
468
Liz Kammera3d79152021-10-28 18:14:04 -0400469// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100470func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800471 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100472 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100473 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800474 })
475 return r
476}
Colin Crossfd4f7432019-03-05 15:06:16 -0800477
Liz Kammera3d79152021-10-28 18:14:04 -0400478// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100479func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100480 return r.WithoutMatcher(properties, selectMatcher(value))
481}
482
Liz Kammera3d79152021-10-28 18:14:04 -0400483// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100484func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800485 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100486 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100487 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800488 })
489 return r
490}
Colin Crossfd4f7432019-03-05 15:06:16 -0800491
Paul Duffin73bf0542019-07-12 14:12:49 +0100492func selectMatcher(expected string) ValueMatcher {
493 if expected == "*" {
494 return anyMatcherInstance
495 }
496 return &equalMatcher{expected: expected}
497}
498
Liz Kammera3d79152021-10-28 18:14:04 -0400499// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100500func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800501 r.reason = reason
502 return r
503}
504
505func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400506 s := []string{"neverallow requirements. Not allowed:"}
507 if len(r.paths) > 0 {
508 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800509 }
Liz Kammera3d79152021-10-28 18:14:04 -0400510 if len(r.moduleTypes) > 0 {
511 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800512 }
Liz Kammera3d79152021-10-28 18:14:04 -0400513 if len(r.props) > 0 {
514 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800515 }
Liz Kammera3d79152021-10-28 18:14:04 -0400516 if len(r.directDeps) > 0 {
517 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800518 }
Liz Kammera3d79152021-10-28 18:14:04 -0400519 if len(r.osClasses) > 0 {
520 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100521 }
Liz Kammera3d79152021-10-28 18:14:04 -0400522 if len(r.unlessPaths) > 0 {
523 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
524 }
525 if len(r.unlessModuleTypes) > 0 {
526 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
527 }
528 if len(r.unlessProps) > 0 {
529 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100530 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800531 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400532 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800533 }
Liz Kammera3d79152021-10-28 18:14:04 -0400534 if len(s) == 1 {
535 s[0] = "neverallow requirements (empty)"
536 }
537 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800538}
539
540func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800541 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
542 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800543 return includePath && !excludePath
544}
545
Paul Duffin35781882019-07-25 15:41:09 +0100546func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
547 if len(r.directDeps) == 0 {
548 return true
549 }
550
551 matches := false
552 ctx.VisitDirectDeps(func(m Module) {
553 if !matches {
554 name := ctx.OtherModuleName(m)
555 matches = r.directDeps[name]
556 }
557 })
558
559 return matches
560}
561
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100562func (r *rule) appliesToOsClass(osClass OsClass) bool {
563 if len(r.osClasses) == 0 {
564 return true
565 }
566
567 for _, c := range r.osClasses {
568 if c == osClass {
569 return true
570 }
571 }
572
573 return false
574}
575
Colin Crossfd4f7432019-03-05 15:06:16 -0800576func (r *rule) appliesToModuleType(moduleType string) bool {
577 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
578}
579
Anton Hanssone1b18362021-12-23 15:05:38 +0000580func (r *rule) appliesToProperties(properties []interface{}) bool {
581 includeProps := hasAllProperties(properties, r.props)
582 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800583 return includeProps && !excludeProps
584}
585
Paul Duffinc8111702019-07-22 12:13:55 +0100586func StartsWith(prefix string) ValueMatcher {
587 return &startsWithMatcher{prefix}
588}
589
Anton Hansson45376402020-04-09 14:18:21 +0100590func Regexp(re string) ValueMatcher {
591 r, err := regexp.Compile(re)
592 if err != nil {
593 panic(err)
594 }
595 return &regexMatcher{r}
596}
597
Andrei Onea115e7e72020-06-05 21:14:03 +0100598func NotInList(allowed []string) ValueMatcher {
599 return &notInListMatcher{allowed}
600}
601
Steven Moreland65b3fd92017-12-06 14:18:35 -0800602// assorted utils
603
604func cleanPaths(paths []string) []string {
605 res := make([]string, len(paths))
606 for i, v := range paths {
607 res[i] = filepath.Clean(v) + "/"
608 }
609 return res
610}
611
612func fieldNamesForProperties(propertyNames string) []string {
613 names := strings.Split(propertyNames, ".")
614 for i, v := range names {
615 names[i] = proptools.FieldNameForProperty(v)
616 }
617 return names
618}
619
Anton Hanssone1b18362021-12-23 15:05:38 +0000620func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800621 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000622 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800623 return true
624 }
625 }
626 return false
627}
628
Anton Hanssone1b18362021-12-23 15:05:38 +0000629func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800630 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000631 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800632 return false
633 }
634 }
635 return true
636}
637
Anton Hanssone1b18362021-12-23 15:05:38 +0000638func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800639 for _, propertyStruct := range properties {
640 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
641 for _, v := range prop.fields {
642 if !propertiesValue.IsValid() {
643 break
644 }
645 propertiesValue = propertiesValue.FieldByName(v)
646 }
647 if !propertiesValue.IsValid() {
648 continue
649 }
650
Paul Duffin73bf0542019-07-12 14:12:49 +0100651 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000652 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653 }
654
655 if matchValue(propertiesValue, check) {
656 return true
657 }
658 }
659 return false
660}
661
662func matchValue(value reflect.Value, check func(string) bool) bool {
663 if !value.IsValid() {
664 return false
665 }
666
667 if value.Kind() == reflect.Ptr {
668 if value.IsNil() {
669 return check("")
670 }
671 value = value.Elem()
672 }
673
674 switch value.Kind() {
675 case reflect.String:
676 return check(value.String())
677 case reflect.Bool:
678 return check(strconv.FormatBool(value.Bool()))
679 case reflect.Int:
680 return check(strconv.FormatInt(value.Int(), 10))
681 case reflect.Slice:
682 slice, ok := value.Interface().([]string)
683 if !ok {
684 panic("Can only handle slice of string")
685 }
686 for _, v := range slice {
687 if check(v) {
688 return true
689 }
690 }
691 return false
692 }
693
694 panic("Can't handle type: " + value.Kind().String())
695}
Paul Duffin115445b2019-08-07 15:31:07 +0100696
697var neverallowRulesKey = NewOnceKey("neverallowRules")
698
699func neverallowRules(config Config) []Rule {
700 return config.Once(neverallowRulesKey, func() interface{} {
701 // No test rules were set by setTestNeverallowRules, use the global rules
702 return neverallows
703 }).([]Rule)
704}
705
706// Overrides the default neverallow rules for the supplied config.
707//
708// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100709func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100710 config.Once(neverallowRulesKey, func() interface{} { return testRules })
711}
Paul Duffin45338f02021-03-30 23:07:52 +0100712
713// Prepares for a test by setting neverallow rules and enabling the mutator.
714//
715// If the supplied rules are nil then the default rules are used.
716func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
717 return GroupFixturePreparers(
718 FixtureModifyConfig(func(config Config) {
719 if testRules != nil {
720 setTestNeverallowRules(config, testRules)
721 }
722 }),
723 FixtureRegisterWithContext(func(ctx RegistrationContext) {
724 ctx.PostDepsMutators(registerNeverallowMutator)
725 }),
726 )
727}