blob: 00078a025f6c0cf1505962cdf57922c5a12019ec [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",
Colin Crossfd4f7432019-03-05 15:06:16 -0800156 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000157 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800158 }
159
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 return []Rule{
161 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700162 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100163 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700164 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800165 }
166}
167
Colin Crossc511bc52020-04-07 16:50:32 +0000168func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700169 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000170 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
171 // This sometimes works because the APEX modules that contain derive_sdk and
172 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
173 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100174 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700175 // These are for apps and shouldn't be used by non-SDK variant modules.
176 "prebuilts/ndk",
177 "tools/test/graphicsbenchmark/apps/sample_app",
178 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700179 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000180 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000181 }
182
Colin Cross440e0d02020-06-11 11:32:11 -0700183 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000184 // android_native_app_glue and libRSSupport use native_window.h but target old
185 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
186 // so they can't add libnativewindow to shared_libs to get the header directory
187 // for the platform variant. Allow them to use the platform variant
188 // property to set shared_libs.
189 "prebuilts/ndk",
190 "frameworks/rs",
191 }
192
193 return []Rule{
194 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700195 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000196 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700197 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000198 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700199 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000200 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700201 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000202 }
203}
204
David Srbeckye033cba2020-05-20 22:20:28 +0100205func createUncompressDexRules() []Rule {
206 return []Rule{
207 NeverAllow().
208 NotIn("art").
209 WithMatcher("uncompress_dex", isSetMatcherInstance).
210 Because("uncompress_dex is only allowed for certain jars for test in art."),
211 }
212}
213
Yifan Hong696ed4d2020-07-27 12:59:58 -0700214func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900215 allowlist := []string{
216 // libwifi_hal uses makefile_goal for its dependencies
217 "frameworks/opt/net/wifi/libwifi_hal",
218 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700219 return []Rule{
220 NeverAllow().
221 ModuleType("makefile_goal").
222 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900223 NotIn(allowlist...).
224 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700225 }
226}
227
Inseob Kim800d1142021-06-14 12:03:51 +0900228func createInitFirstStageRules() []Rule {
229 return []Rule{
230 NeverAllow().
231 Without("name", "init_first_stage").
232 With("install_in_root", "true").
233 Because("install_in_root is only for init_first_stage."),
234 }
235}
236
Jiyong Park3c306f32022-04-05 15:29:53 +0900237func createProhibitFrameworkAccessRules() []Rule {
238 return []Rule{
239 NeverAllow().
240 With("libs", "framework").
241 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
242 Because("framework can't be used when building against SDK"),
243 }
244}
245
Steven Moreland65b3fd92017-12-06 14:18:35 -0800246func neverallowMutator(ctx BottomUpMutatorContext) {
247 m, ok := ctx.Module().(Module)
248 if !ok {
249 return
250 }
251
252 dir := ctx.ModuleDir() + "/"
253 properties := m.GetProperties()
254
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100255 osClass := ctx.Module().Target().Os.Class
256
Paul Duffin115445b2019-08-07 15:31:07 +0100257 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100258 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800259 if !n.appliesToPath(dir) {
260 continue
261 }
262
Colin Crossfd4f7432019-03-05 15:06:16 -0800263 if !n.appliesToModuleType(ctx.ModuleType()) {
264 continue
265 }
266
Anton Hanssone1b18362021-12-23 15:05:38 +0000267 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800268 continue
269 }
270
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100271 if !n.appliesToOsClass(osClass) {
272 continue
273 }
274
Paul Duffin35781882019-07-25 15:41:09 +0100275 if !n.appliesToDirectDeps(ctx) {
276 continue
277 }
278
Steven Moreland65b3fd92017-12-06 14:18:35 -0800279 ctx.ModuleErrorf("violates " + n.String())
280 }
281}
282
Paul Duffin73bf0542019-07-12 14:12:49 +0100283type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000284 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100285 String() string
286}
287
288type equalMatcher struct {
289 expected string
290}
291
Anton Hanssone1b18362021-12-23 15:05:38 +0000292func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100293 return m.expected == value
294}
295
296func (m *equalMatcher) String() string {
297 return "=" + m.expected
298}
299
300type anyMatcher struct {
301}
302
Anton Hanssone1b18362021-12-23 15:05:38 +0000303func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100304 return true
305}
306
307func (m *anyMatcher) String() string {
308 return "=*"
309}
310
311var anyMatcherInstance = &anyMatcher{}
312
Paul Duffinc8111702019-07-22 12:13:55 +0100313type startsWithMatcher struct {
314 prefix string
315}
316
Anton Hanssone1b18362021-12-23 15:05:38 +0000317func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100318 return strings.HasPrefix(value, m.prefix)
319}
320
321func (m *startsWithMatcher) String() string {
322 return ".starts-with(" + m.prefix + ")"
323}
324
Anton Hansson45376402020-04-09 14:18:21 +0100325type regexMatcher struct {
326 re *regexp.Regexp
327}
328
Anton Hanssone1b18362021-12-23 15:05:38 +0000329func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100330 return m.re.MatchString(value)
331}
332
333func (m *regexMatcher) String() string {
334 return ".regexp(" + m.re.String() + ")"
335}
336
Andrei Onea115e7e72020-06-05 21:14:03 +0100337type notInListMatcher struct {
338 allowed []string
339}
340
Anton Hanssone1b18362021-12-23 15:05:38 +0000341func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100342 return !InList(value, m.allowed)
343}
344
345func (m *notInListMatcher) String() string {
346 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
347}
348
Colin Crossc511bc52020-04-07 16:50:32 +0000349type isSetMatcher struct{}
350
Anton Hanssone1b18362021-12-23 15:05:38 +0000351func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000352 return value != ""
353}
354
355func (m *isSetMatcher) String() string {
356 return ".is-set"
357}
358
359var isSetMatcherInstance = &isSetMatcher{}
360
Steven Moreland65b3fd92017-12-06 14:18:35 -0800361type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100362 fields []string // e.x.: Vndk.Enabled
363 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800364}
365
Liz Kammera3d79152021-10-28 18:14:04 -0400366func (r *ruleProperty) String() string {
367 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
368}
369
370type ruleProperties []ruleProperty
371
372func (r ruleProperties) String() string {
373 var s []string
374 for _, r := range r {
375 s = append(s, r.String())
376 }
377 return strings.Join(s, " ")
378}
379
Paul Duffin730f2a52019-06-27 14:08:51 +0100380// A NeverAllow rule.
381type Rule interface {
382 In(path ...string) Rule
383
384 NotIn(path ...string) Rule
385
Paul Duffin35781882019-07-25 15:41:09 +0100386 InDirectDeps(deps ...string) Rule
387
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100388 WithOsClass(osClasses ...OsClass) Rule
389
Paul Duffin730f2a52019-06-27 14:08:51 +0100390 ModuleType(types ...string) Rule
391
392 NotModuleType(types ...string) Rule
393
394 With(properties, value string) Rule
395
Paul Duffinc8111702019-07-22 12:13:55 +0100396 WithMatcher(properties string, matcher ValueMatcher) Rule
397
Paul Duffin730f2a52019-06-27 14:08:51 +0100398 Without(properties, value string) Rule
399
Paul Duffinc8111702019-07-22 12:13:55 +0100400 WithoutMatcher(properties string, matcher ValueMatcher) Rule
401
Paul Duffin730f2a52019-06-27 14:08:51 +0100402 Because(reason string) Rule
403}
404
Steven Moreland65b3fd92017-12-06 14:18:35 -0800405type rule struct {
406 // User string for why this is a thing.
407 reason string
408
409 paths []string
410 unlessPaths []string
411
Paul Duffin35781882019-07-25 15:41:09 +0100412 directDeps map[string]bool
413
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100414 osClasses []OsClass
415
Colin Crossfd4f7432019-03-05 15:06:16 -0800416 moduleTypes []string
417 unlessModuleTypes []string
418
Liz Kammera3d79152021-10-28 18:14:04 -0400419 props ruleProperties
420 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100421
422 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800423}
424
Paul Duffin730f2a52019-06-27 14:08:51 +0100425// Create a new NeverAllow rule.
426func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100427 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428}
Colin Crossfd4f7432019-03-05 15:06:16 -0800429
Liz Kammera3d79152021-10-28 18:14:04 -0400430// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100431func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800432 r.paths = append(r.paths, cleanPaths(path)...)
433 return r
434}
Colin Crossfd4f7432019-03-05 15:06:16 -0800435
Liz Kammera3d79152021-10-28 18:14:04 -0400436// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100437func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800438 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
439 return r
440}
Colin Crossfd4f7432019-03-05 15:06:16 -0800441
Liz Kammera3d79152021-10-28 18:14:04 -0400442// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100443func (r *rule) InDirectDeps(deps ...string) Rule {
444 for _, d := range deps {
445 r.directDeps[d] = true
446 }
447 return r
448}
449
Liz Kammera3d79152021-10-28 18:14:04 -0400450// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100451func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
452 r.osClasses = append(r.osClasses, osClasses...)
453 return r
454}
455
Liz Kammera3d79152021-10-28 18:14:04 -0400456// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100457func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800458 r.moduleTypes = append(r.moduleTypes, types...)
459 return r
460}
461
Liz Kammera3d79152021-10-28 18:14:04 -0400462// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100463func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800464 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
465 return r
466}
467
Liz Kammera3d79152021-10-28 18:14:04 -0400468// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100469func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100470 return r.WithMatcher(properties, selectMatcher(value))
471}
472
Liz Kammera3d79152021-10-28 18:14:04 -0400473// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100474func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800475 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100476 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100477 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800478 })
479 return r
480}
Colin Crossfd4f7432019-03-05 15:06:16 -0800481
Liz Kammera3d79152021-10-28 18:14:04 -0400482// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100483func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100484 return r.WithoutMatcher(properties, selectMatcher(value))
485}
486
Liz Kammera3d79152021-10-28 18:14:04 -0400487// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100488func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800489 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100490 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100491 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800492 })
493 return r
494}
Colin Crossfd4f7432019-03-05 15:06:16 -0800495
Paul Duffin73bf0542019-07-12 14:12:49 +0100496func selectMatcher(expected string) ValueMatcher {
497 if expected == "*" {
498 return anyMatcherInstance
499 }
500 return &equalMatcher{expected: expected}
501}
502
Liz Kammera3d79152021-10-28 18:14:04 -0400503// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100504func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800505 r.reason = reason
506 return r
507}
508
509func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400510 s := []string{"neverallow requirements. Not allowed:"}
511 if len(r.paths) > 0 {
512 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 }
Liz Kammera3d79152021-10-28 18:14:04 -0400514 if len(r.moduleTypes) > 0 {
515 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800516 }
Liz Kammera3d79152021-10-28 18:14:04 -0400517 if len(r.props) > 0 {
518 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800519 }
Liz Kammera3d79152021-10-28 18:14:04 -0400520 if len(r.directDeps) > 0 {
521 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800522 }
Liz Kammera3d79152021-10-28 18:14:04 -0400523 if len(r.osClasses) > 0 {
524 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100525 }
Liz Kammera3d79152021-10-28 18:14:04 -0400526 if len(r.unlessPaths) > 0 {
527 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
528 }
529 if len(r.unlessModuleTypes) > 0 {
530 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
531 }
532 if len(r.unlessProps) > 0 {
533 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100534 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800535 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400536 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 }
Liz Kammera3d79152021-10-28 18:14:04 -0400538 if len(s) == 1 {
539 s[0] = "neverallow requirements (empty)"
540 }
541 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800542}
543
544func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800545 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
546 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 return includePath && !excludePath
548}
549
Paul Duffin35781882019-07-25 15:41:09 +0100550func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
551 if len(r.directDeps) == 0 {
552 return true
553 }
554
555 matches := false
556 ctx.VisitDirectDeps(func(m Module) {
557 if !matches {
558 name := ctx.OtherModuleName(m)
559 matches = r.directDeps[name]
560 }
561 })
562
563 return matches
564}
565
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100566func (r *rule) appliesToOsClass(osClass OsClass) bool {
567 if len(r.osClasses) == 0 {
568 return true
569 }
570
571 for _, c := range r.osClasses {
572 if c == osClass {
573 return true
574 }
575 }
576
577 return false
578}
579
Colin Crossfd4f7432019-03-05 15:06:16 -0800580func (r *rule) appliesToModuleType(moduleType string) bool {
581 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
582}
583
Anton Hanssone1b18362021-12-23 15:05:38 +0000584func (r *rule) appliesToProperties(properties []interface{}) bool {
585 includeProps := hasAllProperties(properties, r.props)
586 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800587 return includeProps && !excludeProps
588}
589
Paul Duffinc8111702019-07-22 12:13:55 +0100590func StartsWith(prefix string) ValueMatcher {
591 return &startsWithMatcher{prefix}
592}
593
Anton Hansson45376402020-04-09 14:18:21 +0100594func Regexp(re string) ValueMatcher {
595 r, err := regexp.Compile(re)
596 if err != nil {
597 panic(err)
598 }
599 return &regexMatcher{r}
600}
601
Andrei Onea115e7e72020-06-05 21:14:03 +0100602func NotInList(allowed []string) ValueMatcher {
603 return &notInListMatcher{allowed}
604}
605
Steven Moreland65b3fd92017-12-06 14:18:35 -0800606// assorted utils
607
608func cleanPaths(paths []string) []string {
609 res := make([]string, len(paths))
610 for i, v := range paths {
611 res[i] = filepath.Clean(v) + "/"
612 }
613 return res
614}
615
616func fieldNamesForProperties(propertyNames string) []string {
617 names := strings.Split(propertyNames, ".")
618 for i, v := range names {
619 names[i] = proptools.FieldNameForProperty(v)
620 }
621 return names
622}
623
Anton Hanssone1b18362021-12-23 15:05:38 +0000624func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800625 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000626 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800627 return true
628 }
629 }
630 return false
631}
632
Anton Hanssone1b18362021-12-23 15:05:38 +0000633func hasAllProperties(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 false
637 }
638 }
639 return true
640}
641
Anton Hanssone1b18362021-12-23 15:05:38 +0000642func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800643 for _, propertyStruct := range properties {
644 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
645 for _, v := range prop.fields {
646 if !propertiesValue.IsValid() {
647 break
648 }
649 propertiesValue = propertiesValue.FieldByName(v)
650 }
651 if !propertiesValue.IsValid() {
652 continue
653 }
654
Paul Duffin73bf0542019-07-12 14:12:49 +0100655 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000656 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800657 }
658
659 if matchValue(propertiesValue, check) {
660 return true
661 }
662 }
663 return false
664}
665
666func matchValue(value reflect.Value, check func(string) bool) bool {
667 if !value.IsValid() {
668 return false
669 }
670
671 if value.Kind() == reflect.Ptr {
672 if value.IsNil() {
673 return check("")
674 }
675 value = value.Elem()
676 }
677
678 switch value.Kind() {
679 case reflect.String:
680 return check(value.String())
681 case reflect.Bool:
682 return check(strconv.FormatBool(value.Bool()))
683 case reflect.Int:
684 return check(strconv.FormatInt(value.Int(), 10))
685 case reflect.Slice:
686 slice, ok := value.Interface().([]string)
687 if !ok {
688 panic("Can only handle slice of string")
689 }
690 for _, v := range slice {
691 if check(v) {
692 return true
693 }
694 }
695 return false
696 }
697
698 panic("Can't handle type: " + value.Kind().String())
699}
Paul Duffin115445b2019-08-07 15:31:07 +0100700
701var neverallowRulesKey = NewOnceKey("neverallowRules")
702
703func neverallowRules(config Config) []Rule {
704 return config.Once(neverallowRulesKey, func() interface{} {
705 // No test rules were set by setTestNeverallowRules, use the global rules
706 return neverallows
707 }).([]Rule)
708}
709
710// Overrides the default neverallow rules for the supplied config.
711//
712// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100713func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100714 config.Once(neverallowRulesKey, func() interface{} { return testRules })
715}
Paul Duffin45338f02021-03-30 23:07:52 +0100716
717// Prepares for a test by setting neverallow rules and enabling the mutator.
718//
719// If the supplied rules are nil then the default rules are used.
720func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
721 return GroupFixturePreparers(
722 FixtureModifyConfig(func(config Config) {
723 if testRules != nil {
724 setTestNeverallowRules(config, testRules)
725 }
726 }),
727 FixtureRegisterWithContext(func(ctx RegistrationContext) {
728 ctx.PostDepsMutators(registerNeverallowMutator)
729 }),
730 )
731}