blob: 0f363e78f049c8c47dfbabe93430b7938074eb7b [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()...)
Inseob Kim800d1142021-06-14 12:03:51 +090058 AddNeverAllowRules(createInitFirstStageRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090059 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Alan Stokes73feba32022-11-14 12:21:24 +000060 AddNeverAllowRules(createCcStubsRule())
Jihoon Kang381c2fa2023-06-01 22:17:32 +000061 AddNeverAllowRules(createJavaExcludeStaticLibsRule())
Mark Whitea15790a2023-08-22 21:28:11 +000062 AddNeverAllowRules(createProhibitHeaderOnlyRule())
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
Sam Delmerico46d08b42022-11-15 15:51:04 -050070var (
71 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010072 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000073 "art/libnativebridge",
74 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010075 "libcore",
76 "libnativehelper",
77 "external/apache-harmony",
78 "external/apache-xml",
79 "external/boringssl",
80 "external/bouncycastle",
81 "external/conscrypt",
82 "external/icu",
83 "external/okhttp",
84 "external/vixl",
85 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010086 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050087 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000088 "frameworks/av/apex",
89 "frameworks/av/tools",
90 "frameworks/native/cmds",
91 "system/apex",
92 "system/bpf",
93 "system/gatekeeper",
94 "system/hwservicemanager",
95 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000096 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +000097 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000098 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050099)
Paul Duffinc8111702019-07-22 12:13:55 +0100100
Sam Delmerico46d08b42022-11-15 15:51:04 -0500101func createIncludeDirsRules() []Rule {
102 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000103
Sam Delmerico46d08b42022-11-15 15:51:04 -0500104 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100105 rule :=
106 NeverAllow().
107 WithMatcher("include_dirs", StartsWith(path+"/")).
108 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
109 " to use alternate mechanisms and so can no longer be used.")
110
111 rules = append(rules, rule)
112 }
113
Sam Delmerico46d08b42022-11-15 15:51:04 -0500114 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000115 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
116 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
117 " to use alternate mechanisms and so can no longer be used.")
118 rules = append(rules, rule)
119 }
120
Paul Duffinc8111702019-07-22 12:13:55 +0100121 return rules
122}
123
Paul Duffin730f2a52019-06-27 14:08:51 +0100124func createTrebleRules() []Rule {
125 return []Rule{
126 NeverAllow().
127 In("vendor", "device").
128 With("vndk.enabled", "true").
129 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900130 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100131 Because("the VNDK can never contain a library that is device dependent."),
132 NeverAllow().
133 With("vndk.enabled", "true").
134 Without("vendor", "true").
135 Without("owner", "").
136 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800137
Neil Fullerdf5f3562018-10-21 17:19:10 +0100138 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100139 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800140 Without("name", "libhidlbase-combined-impl").
141 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100142 With("product_variables.enforce_vintf_manifest.cflags", "*").
143 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100144
145 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 NeverAllow().
147 Without("name", "libc_bionic_ndk").
148 With("product_variables.treble_linker_namespaces.cflags", "*").
149 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100150
151 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100152 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100153 }
154}
155
Paul Duffin730f2a52019-06-27 14:08:51 +0100156func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700157 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700158 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700159 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400160 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800161 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000162 "external/robolectric",
Makoto Onukib66bba32023-11-11 00:06:09 +0000163 "frameworks/base/ravenwood",
164 "frameworks/base/tools/hoststubgen",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000165 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800166 }
167
Paul Duffin730f2a52019-06-27 14:08:51 +0100168 return []Rule{
169 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700170 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100171 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700172 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800173 }
174}
175
Colin Crossc511bc52020-04-07 16:50:32 +0000176func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700177 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000178 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
179 // This sometimes works because the APEX modules that contain derive_sdk and
180 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
181 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100182 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700183 // These are for apps and shouldn't be used by non-SDK variant modules.
184 "prebuilts/ndk",
185 "tools/test/graphicsbenchmark/apps/sample_app",
186 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700187 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000188 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000189 }
190
Colin Cross440e0d02020-06-11 11:32:11 -0700191 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000192 // android_native_app_glue and libRSSupport use native_window.h but target old
193 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
194 // so they can't add libnativewindow to shared_libs to get the header directory
195 // for the platform variant. Allow them to use the platform variant
196 // property to set shared_libs.
197 "prebuilts/ndk",
198 "frameworks/rs",
199 }
200
201 return []Rule{
202 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700203 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000204 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700205 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000206 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700207 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000208 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700209 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000210 }
211}
212
Alan Stokes73feba32022-11-14 12:21:24 +0000213func createCcStubsRule() Rule {
214 ccStubsImplementationInstallableProjectsAllowedList := []string{
Jiyong Parkf6736c72024-07-22 11:22:35 +0900215 "packages/modules/Virtualization/libs/libvm_payload",
Alan Stokes73feba32022-11-14 12:21:24 +0000216 }
217
218 return NeverAllow().
219 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
220 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
221 Because("implementation_installable can only be used in allowed projects.")
222}
223
David Srbeckye033cba2020-05-20 22:20:28 +0100224func createUncompressDexRules() []Rule {
225 return []Rule{
226 NeverAllow().
227 NotIn("art").
228 WithMatcher("uncompress_dex", isSetMatcherInstance).
229 Because("uncompress_dex is only allowed for certain jars for test in art."),
230 }
231}
232
Inseob Kim800d1142021-06-14 12:03:51 +0900233func createInitFirstStageRules() []Rule {
234 return []Rule{
235 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100236 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900237 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100238 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900239 With("install_in_root", "true").
Inseob Kimbe6a66d2024-07-11 15:43:44 +0900240 NotModuleType("prebuilt_root").
Inseob Kim800d1142021-06-14 12:03:51 +0900241 Because("install_in_root is only for init_first_stage."),
242 }
243}
244
Jiyong Park3c306f32022-04-05 15:29:53 +0900245func createProhibitFrameworkAccessRules() []Rule {
246 return []Rule{
247 NeverAllow().
248 With("libs", "framework").
249 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
250 Because("framework can't be used when building against SDK"),
251 }
252}
253
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000254func createJavaExcludeStaticLibsRule() Rule {
255 return NeverAllow().
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000256 NotIn("build/soong", "libcore", "frameworks/base/api").
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000257 ModuleType("java_library").
258 WithMatcher("exclude_static_libs", isSetMatcherInstance).
Jihoon Kang3d4d88d2023-06-14 23:14:42 +0000259 Because("exclude_static_libs property is only allowed for java modules defined in build/soong, libcore, and frameworks/base/api")
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000260}
261
Mark Whitea15790a2023-08-22 21:28:11 +0000262func createProhibitHeaderOnlyRule() Rule {
263 return NeverAllow().
264 Without("name", "framework-minus-apex-headers").
265 With("headers_only", "true").
266 Because("headers_only can only be used for generating framework-minus-apex headers for non-updatable modules")
267}
268
Steven Moreland65b3fd92017-12-06 14:18:35 -0800269func neverallowMutator(ctx BottomUpMutatorContext) {
270 m, ok := ctx.Module().(Module)
271 if !ok {
272 return
273 }
274
275 dir := ctx.ModuleDir() + "/"
276 properties := m.GetProperties()
277
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100278 osClass := ctx.Module().Target().Os.Class
279
Paul Duffin115445b2019-08-07 15:31:07 +0100280 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100281 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800282 if !n.appliesToPath(dir) {
283 continue
284 }
285
Colin Crossfd4f7432019-03-05 15:06:16 -0800286 if !n.appliesToModuleType(ctx.ModuleType()) {
287 continue
288 }
289
Anton Hanssone1b18362021-12-23 15:05:38 +0000290 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800291 continue
292 }
293
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100294 if !n.appliesToOsClass(osClass) {
295 continue
296 }
297
Paul Duffin35781882019-07-25 15:41:09 +0100298 if !n.appliesToDirectDeps(ctx) {
299 continue
300 }
301
Steven Moreland65b3fd92017-12-06 14:18:35 -0800302 ctx.ModuleErrorf("violates " + n.String())
303 }
304}
305
Paul Duffin73bf0542019-07-12 14:12:49 +0100306type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000307 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100308 String() string
309}
310
311type equalMatcher struct {
312 expected string
313}
314
Anton Hanssone1b18362021-12-23 15:05:38 +0000315func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100316 return m.expected == value
317}
318
319func (m *equalMatcher) String() string {
320 return "=" + m.expected
321}
322
323type anyMatcher struct {
324}
325
Anton Hanssone1b18362021-12-23 15:05:38 +0000326func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100327 return true
328}
329
330func (m *anyMatcher) String() string {
331 return "=*"
332}
333
334var anyMatcherInstance = &anyMatcher{}
335
Paul Duffinc8111702019-07-22 12:13:55 +0100336type startsWithMatcher struct {
337 prefix string
338}
339
Anton Hanssone1b18362021-12-23 15:05:38 +0000340func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100341 return strings.HasPrefix(value, m.prefix)
342}
343
344func (m *startsWithMatcher) String() string {
345 return ".starts-with(" + m.prefix + ")"
346}
347
Anton Hansson45376402020-04-09 14:18:21 +0100348type regexMatcher struct {
349 re *regexp.Regexp
350}
351
Anton Hanssone1b18362021-12-23 15:05:38 +0000352func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100353 return m.re.MatchString(value)
354}
355
356func (m *regexMatcher) String() string {
357 return ".regexp(" + m.re.String() + ")"
358}
359
Andrei Onea115e7e72020-06-05 21:14:03 +0100360type notInListMatcher struct {
361 allowed []string
362}
363
Anton Hanssone1b18362021-12-23 15:05:38 +0000364func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100365 return !InList(value, m.allowed)
366}
367
368func (m *notInListMatcher) String() string {
369 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
370}
371
Colin Crossc511bc52020-04-07 16:50:32 +0000372type isSetMatcher struct{}
373
Anton Hanssone1b18362021-12-23 15:05:38 +0000374func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000375 return value != ""
376}
377
378func (m *isSetMatcher) String() string {
379 return ".is-set"
380}
381
382var isSetMatcherInstance = &isSetMatcher{}
383
Steven Moreland65b3fd92017-12-06 14:18:35 -0800384type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100385 fields []string // e.x.: Vndk.Enabled
386 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800387}
388
Liz Kammera3d79152021-10-28 18:14:04 -0400389func (r *ruleProperty) String() string {
390 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
391}
392
393type ruleProperties []ruleProperty
394
395func (r ruleProperties) String() string {
396 var s []string
397 for _, r := range r {
398 s = append(s, r.String())
399 }
400 return strings.Join(s, " ")
401}
402
Paul Duffin730f2a52019-06-27 14:08:51 +0100403// A NeverAllow rule.
404type Rule interface {
405 In(path ...string) Rule
406
407 NotIn(path ...string) Rule
408
Paul Duffin35781882019-07-25 15:41:09 +0100409 InDirectDeps(deps ...string) Rule
410
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100411 WithOsClass(osClasses ...OsClass) Rule
412
Paul Duffin730f2a52019-06-27 14:08:51 +0100413 ModuleType(types ...string) Rule
414
415 NotModuleType(types ...string) Rule
416
417 With(properties, value string) Rule
418
Paul Duffinc8111702019-07-22 12:13:55 +0100419 WithMatcher(properties string, matcher ValueMatcher) Rule
420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421 Without(properties, value string) Rule
422
Paul Duffinc8111702019-07-22 12:13:55 +0100423 WithoutMatcher(properties string, matcher ValueMatcher) Rule
424
Paul Duffin730f2a52019-06-27 14:08:51 +0100425 Because(reason string) Rule
426}
427
Steven Moreland65b3fd92017-12-06 14:18:35 -0800428type rule struct {
429 // User string for why this is a thing.
430 reason string
431
432 paths []string
433 unlessPaths []string
434
Paul Duffin35781882019-07-25 15:41:09 +0100435 directDeps map[string]bool
436
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100437 osClasses []OsClass
438
Colin Crossfd4f7432019-03-05 15:06:16 -0800439 moduleTypes []string
440 unlessModuleTypes []string
441
Liz Kammera3d79152021-10-28 18:14:04 -0400442 props ruleProperties
443 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100444
445 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800446}
447
Paul Duffin730f2a52019-06-27 14:08:51 +0100448// Create a new NeverAllow rule.
449func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100450 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800451}
Colin Crossfd4f7432019-03-05 15:06:16 -0800452
Liz Kammera3d79152021-10-28 18:14:04 -0400453// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100454func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800455 r.paths = append(r.paths, cleanPaths(path)...)
456 return r
457}
Colin Crossfd4f7432019-03-05 15:06:16 -0800458
Liz Kammera3d79152021-10-28 18:14:04 -0400459// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100460func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800461 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
462 return r
463}
Colin Crossfd4f7432019-03-05 15:06:16 -0800464
Liz Kammera3d79152021-10-28 18:14:04 -0400465// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100466func (r *rule) InDirectDeps(deps ...string) Rule {
467 for _, d := range deps {
468 r.directDeps[d] = true
469 }
470 return r
471}
472
Liz Kammera3d79152021-10-28 18:14:04 -0400473// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100474func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
475 r.osClasses = append(r.osClasses, osClasses...)
476 return r
477}
478
Liz Kammera3d79152021-10-28 18:14:04 -0400479// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100480func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800481 r.moduleTypes = append(r.moduleTypes, types...)
482 return r
483}
484
Liz Kammera3d79152021-10-28 18:14:04 -0400485// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100486func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800487 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
488 return r
489}
490
Liz Kammera3d79152021-10-28 18:14:04 -0400491// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100492func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100493 return r.WithMatcher(properties, selectMatcher(value))
494}
495
Liz Kammera3d79152021-10-28 18:14:04 -0400496// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100497func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800498 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100499 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100500 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800501 })
502 return r
503}
Colin Crossfd4f7432019-03-05 15:06:16 -0800504
Liz Kammera3d79152021-10-28 18:14:04 -0400505// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100506func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100507 return r.WithoutMatcher(properties, selectMatcher(value))
508}
509
Liz Kammera3d79152021-10-28 18:14:04 -0400510// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100511func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800512 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100513 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100514 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800515 })
516 return r
517}
Colin Crossfd4f7432019-03-05 15:06:16 -0800518
Paul Duffin73bf0542019-07-12 14:12:49 +0100519func selectMatcher(expected string) ValueMatcher {
520 if expected == "*" {
521 return anyMatcherInstance
522 }
523 return &equalMatcher{expected: expected}
524}
525
Liz Kammera3d79152021-10-28 18:14:04 -0400526// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100527func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800528 r.reason = reason
529 return r
530}
531
532func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400533 s := []string{"neverallow requirements. Not allowed:"}
534 if len(r.paths) > 0 {
535 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800536 }
Liz Kammera3d79152021-10-28 18:14:04 -0400537 if len(r.moduleTypes) > 0 {
538 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800539 }
Liz Kammera3d79152021-10-28 18:14:04 -0400540 if len(r.props) > 0 {
541 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800542 }
Liz Kammera3d79152021-10-28 18:14:04 -0400543 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800544 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800545 }
Liz Kammera3d79152021-10-28 18:14:04 -0400546 if len(r.osClasses) > 0 {
547 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100548 }
Liz Kammera3d79152021-10-28 18:14:04 -0400549 if len(r.unlessPaths) > 0 {
550 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
551 }
552 if len(r.unlessModuleTypes) > 0 {
553 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
554 }
555 if len(r.unlessProps) > 0 {
556 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100557 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800558 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400559 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800560 }
Liz Kammera3d79152021-10-28 18:14:04 -0400561 if len(s) == 1 {
562 s[0] = "neverallow requirements (empty)"
563 }
564 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800565}
566
567func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800568 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
569 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800570 return includePath && !excludePath
571}
572
Paul Duffin35781882019-07-25 15:41:09 +0100573func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
574 if len(r.directDeps) == 0 {
575 return true
576 }
577
578 matches := false
579 ctx.VisitDirectDeps(func(m Module) {
580 if !matches {
581 name := ctx.OtherModuleName(m)
582 matches = r.directDeps[name]
583 }
584 })
585
586 return matches
587}
588
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100589func (r *rule) appliesToOsClass(osClass OsClass) bool {
590 if len(r.osClasses) == 0 {
591 return true
592 }
593
594 for _, c := range r.osClasses {
595 if c == osClass {
596 return true
597 }
598 }
599
600 return false
601}
602
Colin Crossfd4f7432019-03-05 15:06:16 -0800603func (r *rule) appliesToModuleType(moduleType string) bool {
604 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
605}
606
Anton Hanssone1b18362021-12-23 15:05:38 +0000607func (r *rule) appliesToProperties(properties []interface{}) bool {
608 includeProps := hasAllProperties(properties, r.props)
609 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800610 return includeProps && !excludeProps
611}
612
Paul Duffinc8111702019-07-22 12:13:55 +0100613func StartsWith(prefix string) ValueMatcher {
614 return &startsWithMatcher{prefix}
615}
616
Anton Hansson45376402020-04-09 14:18:21 +0100617func Regexp(re string) ValueMatcher {
618 r, err := regexp.Compile(re)
619 if err != nil {
620 panic(err)
621 }
622 return &regexMatcher{r}
623}
624
Andrei Onea115e7e72020-06-05 21:14:03 +0100625func NotInList(allowed []string) ValueMatcher {
626 return &notInListMatcher{allowed}
627}
628
Steven Moreland65b3fd92017-12-06 14:18:35 -0800629// assorted utils
630
631func cleanPaths(paths []string) []string {
632 res := make([]string, len(paths))
633 for i, v := range paths {
634 res[i] = filepath.Clean(v) + "/"
635 }
636 return res
637}
638
639func fieldNamesForProperties(propertyNames string) []string {
640 names := strings.Split(propertyNames, ".")
641 for i, v := range names {
642 names[i] = proptools.FieldNameForProperty(v)
643 }
644 return names
645}
646
Anton Hanssone1b18362021-12-23 15:05:38 +0000647func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000649 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800650 return true
651 }
652 }
653 return false
654}
655
Anton Hanssone1b18362021-12-23 15:05:38 +0000656func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800657 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000658 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800659 return false
660 }
661 }
662 return true
663}
664
Anton Hanssone1b18362021-12-23 15:05:38 +0000665func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800666 for _, propertyStruct := range properties {
667 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
668 for _, v := range prop.fields {
669 if !propertiesValue.IsValid() {
670 break
671 }
672 propertiesValue = propertiesValue.FieldByName(v)
673 }
674 if !propertiesValue.IsValid() {
675 continue
676 }
677
Paul Duffin73bf0542019-07-12 14:12:49 +0100678 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000679 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800680 }
681
682 if matchValue(propertiesValue, check) {
683 return true
684 }
685 }
686 return false
687}
688
689func matchValue(value reflect.Value, check func(string) bool) bool {
690 if !value.IsValid() {
691 return false
692 }
693
694 if value.Kind() == reflect.Ptr {
695 if value.IsNil() {
696 return check("")
697 }
698 value = value.Elem()
699 }
700
701 switch value.Kind() {
702 case reflect.String:
703 return check(value.String())
704 case reflect.Bool:
705 return check(strconv.FormatBool(value.Bool()))
706 case reflect.Int:
707 return check(strconv.FormatInt(value.Int(), 10))
708 case reflect.Slice:
709 slice, ok := value.Interface().([]string)
710 if !ok {
711 panic("Can only handle slice of string")
712 }
713 for _, v := range slice {
714 if check(v) {
715 return true
716 }
717 }
718 return false
719 }
720
721 panic("Can't handle type: " + value.Kind().String())
722}
Paul Duffin115445b2019-08-07 15:31:07 +0100723
724var neverallowRulesKey = NewOnceKey("neverallowRules")
725
726func neverallowRules(config Config) []Rule {
727 return config.Once(neverallowRulesKey, func() interface{} {
728 // No test rules were set by setTestNeverallowRules, use the global rules
729 return neverallows
730 }).([]Rule)
731}
732
733// Overrides the default neverallow rules for the supplied config.
734//
735// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100736func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100737 config.Once(neverallowRulesKey, func() interface{} { return testRules })
738}
Paul Duffin45338f02021-03-30 23:07:52 +0100739
740// Prepares for a test by setting neverallow rules and enabling the mutator.
741//
742// If the supplied rules are nil then the default rules are used.
743func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
744 return GroupFixturePreparers(
745 FixtureModifyConfig(func(config Config) {
746 if testRules != nil {
747 setTestNeverallowRules(config, testRules)
748 }
749 }),
750 FixtureRegisterWithContext(func(ctx RegistrationContext) {
751 ctx.PostDepsMutators(registerNeverallowMutator)
752 }),
753 )
754}