blob: 6a839d401df9cd4b2730bcf71f7a0bb7e25aae56 [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())
Alan Stokes73feba32022-11-14 12:21:24 +000062 AddNeverAllowRules(createCcStubsRule())
Neil Fullerdf5f3562018-10-21 17:19:10 +010063}
Steven Moreland65b3fd92017-12-06 14:18:35 -080064
Paul Duffin730f2a52019-06-27 14:08:51 +010065// Add a NeverAllow rule to the set of rules to apply.
66func AddNeverAllowRules(rules ...Rule) {
67 neverallows = append(neverallows, rules...)
68}
69
Jingwen Chen1735b2e2022-10-10 14:30:03 +000070func createBp2BuildRule() Rule {
71 return NeverAllow().
72 With("bazel_module.bp2build_available", "true").
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000073 NotIn("soong_tests"). // only used in tests
Jingwen Chen1735b2e2022-10-10 14:30:03 +000074 Because("setting bp2build_available in Android.bp is not " +
75 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000076}
77
Sam Delmerico46d08b42022-11-15 15:51:04 -050078var (
79 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010080 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000081 "art/libnativebridge",
82 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010083 "libcore",
84 "libnativehelper",
85 "external/apache-harmony",
86 "external/apache-xml",
87 "external/boringssl",
88 "external/bouncycastle",
89 "external/conscrypt",
90 "external/icu",
91 "external/okhttp",
92 "external/vixl",
93 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010094 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050095 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000096 "frameworks/av/apex",
97 "frameworks/av/tools",
98 "frameworks/native/cmds",
99 "system/apex",
100 "system/bpf",
101 "system/gatekeeper",
102 "system/hwservicemanager",
103 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000104 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000105 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000106 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500107)
Paul Duffinc8111702019-07-22 12:13:55 +0100108
Sam Delmerico46d08b42022-11-15 15:51:04 -0500109func createIncludeDirsRules() []Rule {
110 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000111
Sam Delmerico46d08b42022-11-15 15:51:04 -0500112 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100113 rule :=
114 NeverAllow().
115 WithMatcher("include_dirs", StartsWith(path+"/")).
116 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
117 " to use alternate mechanisms and so can no longer be used.")
118
119 rules = append(rules, rule)
120 }
121
Sam Delmerico46d08b42022-11-15 15:51:04 -0500122 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000123 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
124 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
125 " to use alternate mechanisms and so can no longer be used.")
126 rules = append(rules, rule)
127 }
128
Paul Duffinc8111702019-07-22 12:13:55 +0100129 return rules
130}
131
Paul Duffin730f2a52019-06-27 14:08:51 +0100132func createTrebleRules() []Rule {
133 return []Rule{
134 NeverAllow().
135 In("vendor", "device").
136 With("vndk.enabled", "true").
137 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900138 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100139 Because("the VNDK can never contain a library that is device dependent."),
140 NeverAllow().
141 With("vndk.enabled", "true").
142 Without("vendor", "true").
143 Without("owner", "").
144 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800145
Neil Fullerdf5f3562018-10-21 17:19:10 +0100146 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100147 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800148 Without("name", "libhidlbase-combined-impl").
149 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100150 With("product_variables.enforce_vintf_manifest.cflags", "*").
151 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100152
153 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100154 NeverAllow().
155 Without("name", "libc_bionic_ndk").
156 With("product_variables.treble_linker_namespaces.cflags", "*").
157 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100158
159 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100160 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100161 }
162}
163
Paul Duffin730f2a52019-06-27 14:08:51 +0100164func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700165 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700166 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700167 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400168 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800169 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000170 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000171 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800172 }
173
Paul Duffin730f2a52019-06-27 14:08:51 +0100174 return []Rule{
175 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700176 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100177 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700178 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800179 }
180}
181
Colin Crossc511bc52020-04-07 16:50:32 +0000182func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700183 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000184 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
185 // This sometimes works because the APEX modules that contain derive_sdk and
186 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
187 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100188 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700189 // These are for apps and shouldn't be used by non-SDK variant modules.
190 "prebuilts/ndk",
191 "tools/test/graphicsbenchmark/apps/sample_app",
192 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700193 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000194 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000195 }
196
Colin Cross440e0d02020-06-11 11:32:11 -0700197 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000198 // android_native_app_glue and libRSSupport use native_window.h but target old
199 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
200 // so they can't add libnativewindow to shared_libs to get the header directory
201 // for the platform variant. Allow them to use the platform variant
202 // property to set shared_libs.
203 "prebuilts/ndk",
204 "frameworks/rs",
205 }
206
207 return []Rule{
208 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700209 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000210 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700211 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000212 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700213 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000214 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700215 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000216 }
217}
218
Alan Stokes73feba32022-11-14 12:21:24 +0000219func createCcStubsRule() Rule {
220 ccStubsImplementationInstallableProjectsAllowedList := []string{
221 "packages/modules/Virtualization/vm_payload",
222 }
223
224 return NeverAllow().
225 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
226 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
227 Because("implementation_installable can only be used in allowed projects.")
228}
229
David Srbeckye033cba2020-05-20 22:20:28 +0100230func createUncompressDexRules() []Rule {
231 return []Rule{
232 NeverAllow().
233 NotIn("art").
234 WithMatcher("uncompress_dex", isSetMatcherInstance).
235 Because("uncompress_dex is only allowed for certain jars for test in art."),
236 }
237}
238
Yifan Hong696ed4d2020-07-27 12:59:58 -0700239func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900240 allowlist := []string{
241 // libwifi_hal uses makefile_goal for its dependencies
242 "frameworks/opt/net/wifi/libwifi_hal",
243 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700244 return []Rule{
245 NeverAllow().
246 ModuleType("makefile_goal").
247 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900248 NotIn(allowlist...).
249 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700250 }
251}
252
Inseob Kim800d1142021-06-14 12:03:51 +0900253func createInitFirstStageRules() []Rule {
254 return []Rule{
255 NeverAllow().
256 Without("name", "init_first_stage").
257 With("install_in_root", "true").
258 Because("install_in_root is only for init_first_stage."),
259 }
260}
261
Jiyong Park3c306f32022-04-05 15:29:53 +0900262func createProhibitFrameworkAccessRules() []Rule {
263 return []Rule{
264 NeverAllow().
265 With("libs", "framework").
266 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
267 Because("framework can't be used when building against SDK"),
268 }
269}
270
Steven Moreland65b3fd92017-12-06 14:18:35 -0800271func neverallowMutator(ctx BottomUpMutatorContext) {
272 m, ok := ctx.Module().(Module)
273 if !ok {
274 return
275 }
276
277 dir := ctx.ModuleDir() + "/"
278 properties := m.GetProperties()
279
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100280 osClass := ctx.Module().Target().Os.Class
281
Paul Duffin115445b2019-08-07 15:31:07 +0100282 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100283 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800284 if !n.appliesToPath(dir) {
285 continue
286 }
287
Colin Crossfd4f7432019-03-05 15:06:16 -0800288 if !n.appliesToModuleType(ctx.ModuleType()) {
289 continue
290 }
291
Anton Hanssone1b18362021-12-23 15:05:38 +0000292 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800293 continue
294 }
295
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100296 if !n.appliesToOsClass(osClass) {
297 continue
298 }
299
Paul Duffin35781882019-07-25 15:41:09 +0100300 if !n.appliesToDirectDeps(ctx) {
301 continue
302 }
303
Steven Moreland65b3fd92017-12-06 14:18:35 -0800304 ctx.ModuleErrorf("violates " + n.String())
305 }
306}
307
Paul Duffin73bf0542019-07-12 14:12:49 +0100308type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000309 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100310 String() string
311}
312
313type equalMatcher struct {
314 expected string
315}
316
Anton Hanssone1b18362021-12-23 15:05:38 +0000317func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100318 return m.expected == value
319}
320
321func (m *equalMatcher) String() string {
322 return "=" + m.expected
323}
324
325type anyMatcher struct {
326}
327
Anton Hanssone1b18362021-12-23 15:05:38 +0000328func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100329 return true
330}
331
332func (m *anyMatcher) String() string {
333 return "=*"
334}
335
336var anyMatcherInstance = &anyMatcher{}
337
Paul Duffinc8111702019-07-22 12:13:55 +0100338type startsWithMatcher struct {
339 prefix string
340}
341
Anton Hanssone1b18362021-12-23 15:05:38 +0000342func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100343 return strings.HasPrefix(value, m.prefix)
344}
345
346func (m *startsWithMatcher) String() string {
347 return ".starts-with(" + m.prefix + ")"
348}
349
Anton Hansson45376402020-04-09 14:18:21 +0100350type regexMatcher struct {
351 re *regexp.Regexp
352}
353
Anton Hanssone1b18362021-12-23 15:05:38 +0000354func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100355 return m.re.MatchString(value)
356}
357
358func (m *regexMatcher) String() string {
359 return ".regexp(" + m.re.String() + ")"
360}
361
Andrei Onea115e7e72020-06-05 21:14:03 +0100362type notInListMatcher struct {
363 allowed []string
364}
365
Anton Hanssone1b18362021-12-23 15:05:38 +0000366func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100367 return !InList(value, m.allowed)
368}
369
370func (m *notInListMatcher) String() string {
371 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
372}
373
Colin Crossc511bc52020-04-07 16:50:32 +0000374type isSetMatcher struct{}
375
Anton Hanssone1b18362021-12-23 15:05:38 +0000376func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000377 return value != ""
378}
379
380func (m *isSetMatcher) String() string {
381 return ".is-set"
382}
383
384var isSetMatcherInstance = &isSetMatcher{}
385
Steven Moreland65b3fd92017-12-06 14:18:35 -0800386type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100387 fields []string // e.x.: Vndk.Enabled
388 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800389}
390
Liz Kammera3d79152021-10-28 18:14:04 -0400391func (r *ruleProperty) String() string {
392 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
393}
394
395type ruleProperties []ruleProperty
396
397func (r ruleProperties) String() string {
398 var s []string
399 for _, r := range r {
400 s = append(s, r.String())
401 }
402 return strings.Join(s, " ")
403}
404
Paul Duffin730f2a52019-06-27 14:08:51 +0100405// A NeverAllow rule.
406type Rule interface {
407 In(path ...string) Rule
408
409 NotIn(path ...string) Rule
410
Paul Duffin35781882019-07-25 15:41:09 +0100411 InDirectDeps(deps ...string) Rule
412
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100413 WithOsClass(osClasses ...OsClass) Rule
414
Paul Duffin730f2a52019-06-27 14:08:51 +0100415 ModuleType(types ...string) Rule
416
417 NotModuleType(types ...string) Rule
418
419 With(properties, value string) Rule
420
Paul Duffinc8111702019-07-22 12:13:55 +0100421 WithMatcher(properties string, matcher ValueMatcher) Rule
422
Paul Duffin730f2a52019-06-27 14:08:51 +0100423 Without(properties, value string) Rule
424
Paul Duffinc8111702019-07-22 12:13:55 +0100425 WithoutMatcher(properties string, matcher ValueMatcher) Rule
426
Paul Duffin730f2a52019-06-27 14:08:51 +0100427 Because(reason string) Rule
428}
429
Steven Moreland65b3fd92017-12-06 14:18:35 -0800430type rule struct {
431 // User string for why this is a thing.
432 reason string
433
434 paths []string
435 unlessPaths []string
436
Paul Duffin35781882019-07-25 15:41:09 +0100437 directDeps map[string]bool
438
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100439 osClasses []OsClass
440
Colin Crossfd4f7432019-03-05 15:06:16 -0800441 moduleTypes []string
442 unlessModuleTypes []string
443
Liz Kammera3d79152021-10-28 18:14:04 -0400444 props ruleProperties
445 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100446
447 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800448}
449
Paul Duffin730f2a52019-06-27 14:08:51 +0100450// Create a new NeverAllow rule.
451func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100452 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800453}
Colin Crossfd4f7432019-03-05 15:06:16 -0800454
Liz Kammera3d79152021-10-28 18:14:04 -0400455// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100456func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457 r.paths = append(r.paths, cleanPaths(path)...)
458 return r
459}
Colin Crossfd4f7432019-03-05 15:06:16 -0800460
Liz Kammera3d79152021-10-28 18:14:04 -0400461// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100462func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800463 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
464 return r
465}
Colin Crossfd4f7432019-03-05 15:06:16 -0800466
Liz Kammera3d79152021-10-28 18:14:04 -0400467// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100468func (r *rule) InDirectDeps(deps ...string) Rule {
469 for _, d := range deps {
470 r.directDeps[d] = true
471 }
472 return r
473}
474
Liz Kammera3d79152021-10-28 18:14:04 -0400475// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100476func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
477 r.osClasses = append(r.osClasses, osClasses...)
478 return r
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100482func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800483 r.moduleTypes = append(r.moduleTypes, types...)
484 return r
485}
486
Liz Kammera3d79152021-10-28 18:14:04 -0400487// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100488func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800489 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
490 return r
491}
492
Liz Kammera3d79152021-10-28 18:14:04 -0400493// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100494func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100495 return r.WithMatcher(properties, selectMatcher(value))
496}
497
Liz Kammera3d79152021-10-28 18:14:04 -0400498// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100499func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800500 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100501 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100502 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800503 })
504 return r
505}
Colin Crossfd4f7432019-03-05 15:06:16 -0800506
Liz Kammera3d79152021-10-28 18:14:04 -0400507// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100508func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100509 return r.WithoutMatcher(properties, selectMatcher(value))
510}
511
Liz Kammera3d79152021-10-28 18:14:04 -0400512// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100513func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800514 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100515 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100516 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800517 })
518 return r
519}
Colin Crossfd4f7432019-03-05 15:06:16 -0800520
Paul Duffin73bf0542019-07-12 14:12:49 +0100521func selectMatcher(expected string) ValueMatcher {
522 if expected == "*" {
523 return anyMatcherInstance
524 }
525 return &equalMatcher{expected: expected}
526}
527
Liz Kammera3d79152021-10-28 18:14:04 -0400528// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100529func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800530 r.reason = reason
531 return r
532}
533
534func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400535 s := []string{"neverallow requirements. Not allowed:"}
536 if len(r.paths) > 0 {
537 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800538 }
Liz Kammera3d79152021-10-28 18:14:04 -0400539 if len(r.moduleTypes) > 0 {
540 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800541 }
Liz Kammera3d79152021-10-28 18:14:04 -0400542 if len(r.props) > 0 {
543 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800544 }
Liz Kammera3d79152021-10-28 18:14:04 -0400545 if len(r.directDeps) > 0 {
546 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800547 }
Liz Kammera3d79152021-10-28 18:14:04 -0400548 if len(r.osClasses) > 0 {
549 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100550 }
Liz Kammera3d79152021-10-28 18:14:04 -0400551 if len(r.unlessPaths) > 0 {
552 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
553 }
554 if len(r.unlessModuleTypes) > 0 {
555 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
556 }
557 if len(r.unlessProps) > 0 {
558 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100559 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800560 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400561 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800562 }
Liz Kammera3d79152021-10-28 18:14:04 -0400563 if len(s) == 1 {
564 s[0] = "neverallow requirements (empty)"
565 }
566 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800567}
568
569func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800570 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
571 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800572 return includePath && !excludePath
573}
574
Paul Duffin35781882019-07-25 15:41:09 +0100575func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
576 if len(r.directDeps) == 0 {
577 return true
578 }
579
580 matches := false
581 ctx.VisitDirectDeps(func(m Module) {
582 if !matches {
583 name := ctx.OtherModuleName(m)
584 matches = r.directDeps[name]
585 }
586 })
587
588 return matches
589}
590
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100591func (r *rule) appliesToOsClass(osClass OsClass) bool {
592 if len(r.osClasses) == 0 {
593 return true
594 }
595
596 for _, c := range r.osClasses {
597 if c == osClass {
598 return true
599 }
600 }
601
602 return false
603}
604
Colin Crossfd4f7432019-03-05 15:06:16 -0800605func (r *rule) appliesToModuleType(moduleType string) bool {
606 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
607}
608
Anton Hanssone1b18362021-12-23 15:05:38 +0000609func (r *rule) appliesToProperties(properties []interface{}) bool {
610 includeProps := hasAllProperties(properties, r.props)
611 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800612 return includeProps && !excludeProps
613}
614
Paul Duffinc8111702019-07-22 12:13:55 +0100615func StartsWith(prefix string) ValueMatcher {
616 return &startsWithMatcher{prefix}
617}
618
Anton Hansson45376402020-04-09 14:18:21 +0100619func Regexp(re string) ValueMatcher {
620 r, err := regexp.Compile(re)
621 if err != nil {
622 panic(err)
623 }
624 return &regexMatcher{r}
625}
626
Andrei Onea115e7e72020-06-05 21:14:03 +0100627func NotInList(allowed []string) ValueMatcher {
628 return &notInListMatcher{allowed}
629}
630
Steven Moreland65b3fd92017-12-06 14:18:35 -0800631// assorted utils
632
633func cleanPaths(paths []string) []string {
634 res := make([]string, len(paths))
635 for i, v := range paths {
636 res[i] = filepath.Clean(v) + "/"
637 }
638 return res
639}
640
641func fieldNamesForProperties(propertyNames string) []string {
642 names := strings.Split(propertyNames, ".")
643 for i, v := range names {
644 names[i] = proptools.FieldNameForProperty(v)
645 }
646 return names
647}
648
Anton Hanssone1b18362021-12-23 15:05:38 +0000649func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800650 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000651 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800652 return true
653 }
654 }
655 return false
656}
657
Anton Hanssone1b18362021-12-23 15:05:38 +0000658func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800659 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000660 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800661 return false
662 }
663 }
664 return true
665}
666
Anton Hanssone1b18362021-12-23 15:05:38 +0000667func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800668 for _, propertyStruct := range properties {
669 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
670 for _, v := range prop.fields {
671 if !propertiesValue.IsValid() {
672 break
673 }
674 propertiesValue = propertiesValue.FieldByName(v)
675 }
676 if !propertiesValue.IsValid() {
677 continue
678 }
679
Paul Duffin73bf0542019-07-12 14:12:49 +0100680 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000681 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800682 }
683
684 if matchValue(propertiesValue, check) {
685 return true
686 }
687 }
688 return false
689}
690
691func matchValue(value reflect.Value, check func(string) bool) bool {
692 if !value.IsValid() {
693 return false
694 }
695
696 if value.Kind() == reflect.Ptr {
697 if value.IsNil() {
698 return check("")
699 }
700 value = value.Elem()
701 }
702
703 switch value.Kind() {
704 case reflect.String:
705 return check(value.String())
706 case reflect.Bool:
707 return check(strconv.FormatBool(value.Bool()))
708 case reflect.Int:
709 return check(strconv.FormatInt(value.Int(), 10))
710 case reflect.Slice:
711 slice, ok := value.Interface().([]string)
712 if !ok {
713 panic("Can only handle slice of string")
714 }
715 for _, v := range slice {
716 if check(v) {
717 return true
718 }
719 }
720 return false
721 }
722
723 panic("Can't handle type: " + value.Kind().String())
724}
Paul Duffin115445b2019-08-07 15:31:07 +0100725
726var neverallowRulesKey = NewOnceKey("neverallowRules")
727
728func neverallowRules(config Config) []Rule {
729 return config.Once(neverallowRulesKey, func() interface{} {
730 // No test rules were set by setTestNeverallowRules, use the global rules
731 return neverallows
732 }).([]Rule)
733}
734
735// Overrides the default neverallow rules for the supplied config.
736//
737// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100738func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100739 config.Once(neverallowRulesKey, func() interface{} { return testRules })
740}
Paul Duffin45338f02021-03-30 23:07:52 +0100741
742// Prepares for a test by setting neverallow rules and enabling the mutator.
743//
744// If the supplied rules are nil then the default rules are used.
745func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
746 return GroupFixturePreparers(
747 FixtureModifyConfig(func(config Config) {
748 if testRules != nil {
749 setTestNeverallowRules(config, testRules)
750 }
751 }),
752 FixtureRegisterWithContext(func(ctx RegistrationContext) {
753 ctx.PostDepsMutators(registerNeverallowMutator)
754 }),
755 )
756}