blob: 41105e6b46247eb650031d54c754154f2df7fdbc [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()...)
Jingwen Chen1735b2e2022-10-10 14:30:03 +000060 AddNeverAllowRules(createBp2BuildRule())
Alan Stokes73feba32022-11-14 12:21:24 +000061 AddNeverAllowRules(createCcStubsRule())
Jihoon Kang381c2fa2023-06-01 22:17:32 +000062 AddNeverAllowRules(createJavaExcludeStaticLibsRule())
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
Inseob Kim800d1142021-06-14 12:03:51 +0900239func createInitFirstStageRules() []Rule {
240 return []Rule{
241 NeverAllow().
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100242 Without("name", "init_first_stage_defaults").
Inseob Kim800d1142021-06-14 12:03:51 +0900243 Without("name", "init_first_stage").
Nikita Ioffe11a9c2c2023-06-21 16:51:09 +0100244 Without("name", "init_first_stage.microdroid").
Inseob Kim800d1142021-06-14 12:03:51 +0900245 With("install_in_root", "true").
246 Because("install_in_root is only for init_first_stage."),
247 }
248}
249
Jiyong Park3c306f32022-04-05 15:29:53 +0900250func createProhibitFrameworkAccessRules() []Rule {
251 return []Rule{
252 NeverAllow().
253 With("libs", "framework").
254 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
255 Because("framework can't be used when building against SDK"),
256 }
257}
258
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000259func createJavaExcludeStaticLibsRule() Rule {
260 return NeverAllow().
261 NotIn("build/soong").
262 ModuleType("java_library").
263 WithMatcher("exclude_static_libs", isSetMatcherInstance).
264 Because("exclude_static_libs property is only allowed for java modules defined in build/soong")
265}
266
Steven Moreland65b3fd92017-12-06 14:18:35 -0800267func neverallowMutator(ctx BottomUpMutatorContext) {
268 m, ok := ctx.Module().(Module)
269 if !ok {
270 return
271 }
272
273 dir := ctx.ModuleDir() + "/"
274 properties := m.GetProperties()
275
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100276 osClass := ctx.Module().Target().Os.Class
277
Paul Duffin115445b2019-08-07 15:31:07 +0100278 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100279 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800280 if !n.appliesToPath(dir) {
281 continue
282 }
283
Colin Crossfd4f7432019-03-05 15:06:16 -0800284 if !n.appliesToModuleType(ctx.ModuleType()) {
285 continue
286 }
287
Anton Hanssone1b18362021-12-23 15:05:38 +0000288 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800289 continue
290 }
291
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100292 if !n.appliesToOsClass(osClass) {
293 continue
294 }
295
Paul Duffin35781882019-07-25 15:41:09 +0100296 if !n.appliesToDirectDeps(ctx) {
297 continue
298 }
299
Steven Moreland65b3fd92017-12-06 14:18:35 -0800300 ctx.ModuleErrorf("violates " + n.String())
301 }
302}
303
Paul Duffin73bf0542019-07-12 14:12:49 +0100304type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000305 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100306 String() string
307}
308
309type equalMatcher struct {
310 expected string
311}
312
Anton Hanssone1b18362021-12-23 15:05:38 +0000313func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100314 return m.expected == value
315}
316
317func (m *equalMatcher) String() string {
318 return "=" + m.expected
319}
320
321type anyMatcher struct {
322}
323
Anton Hanssone1b18362021-12-23 15:05:38 +0000324func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100325 return true
326}
327
328func (m *anyMatcher) String() string {
329 return "=*"
330}
331
332var anyMatcherInstance = &anyMatcher{}
333
Paul Duffinc8111702019-07-22 12:13:55 +0100334type startsWithMatcher struct {
335 prefix string
336}
337
Anton Hanssone1b18362021-12-23 15:05:38 +0000338func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100339 return strings.HasPrefix(value, m.prefix)
340}
341
342func (m *startsWithMatcher) String() string {
343 return ".starts-with(" + m.prefix + ")"
344}
345
Anton Hansson45376402020-04-09 14:18:21 +0100346type regexMatcher struct {
347 re *regexp.Regexp
348}
349
Anton Hanssone1b18362021-12-23 15:05:38 +0000350func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100351 return m.re.MatchString(value)
352}
353
354func (m *regexMatcher) String() string {
355 return ".regexp(" + m.re.String() + ")"
356}
357
Andrei Onea115e7e72020-06-05 21:14:03 +0100358type notInListMatcher struct {
359 allowed []string
360}
361
Anton Hanssone1b18362021-12-23 15:05:38 +0000362func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100363 return !InList(value, m.allowed)
364}
365
366func (m *notInListMatcher) String() string {
367 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
368}
369
Colin Crossc511bc52020-04-07 16:50:32 +0000370type isSetMatcher struct{}
371
Anton Hanssone1b18362021-12-23 15:05:38 +0000372func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000373 return value != ""
374}
375
376func (m *isSetMatcher) String() string {
377 return ".is-set"
378}
379
380var isSetMatcherInstance = &isSetMatcher{}
381
Steven Moreland65b3fd92017-12-06 14:18:35 -0800382type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100383 fields []string // e.x.: Vndk.Enabled
384 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800385}
386
Liz Kammera3d79152021-10-28 18:14:04 -0400387func (r *ruleProperty) String() string {
388 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
389}
390
391type ruleProperties []ruleProperty
392
393func (r ruleProperties) String() string {
394 var s []string
395 for _, r := range r {
396 s = append(s, r.String())
397 }
398 return strings.Join(s, " ")
399}
400
Paul Duffin730f2a52019-06-27 14:08:51 +0100401// A NeverAllow rule.
402type Rule interface {
403 In(path ...string) Rule
404
405 NotIn(path ...string) Rule
406
Paul Duffin35781882019-07-25 15:41:09 +0100407 InDirectDeps(deps ...string) Rule
408
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100409 WithOsClass(osClasses ...OsClass) Rule
410
Paul Duffin730f2a52019-06-27 14:08:51 +0100411 ModuleType(types ...string) Rule
412
413 NotModuleType(types ...string) Rule
414
415 With(properties, value string) Rule
416
Paul Duffinc8111702019-07-22 12:13:55 +0100417 WithMatcher(properties string, matcher ValueMatcher) Rule
418
Paul Duffin730f2a52019-06-27 14:08:51 +0100419 Without(properties, value string) Rule
420
Paul Duffinc8111702019-07-22 12:13:55 +0100421 WithoutMatcher(properties string, matcher ValueMatcher) Rule
422
Paul Duffin730f2a52019-06-27 14:08:51 +0100423 Because(reason string) Rule
424}
425
Steven Moreland65b3fd92017-12-06 14:18:35 -0800426type rule struct {
427 // User string for why this is a thing.
428 reason string
429
430 paths []string
431 unlessPaths []string
432
Paul Duffin35781882019-07-25 15:41:09 +0100433 directDeps map[string]bool
434
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100435 osClasses []OsClass
436
Colin Crossfd4f7432019-03-05 15:06:16 -0800437 moduleTypes []string
438 unlessModuleTypes []string
439
Liz Kammera3d79152021-10-28 18:14:04 -0400440 props ruleProperties
441 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100442
443 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800444}
445
Paul Duffin730f2a52019-06-27 14:08:51 +0100446// Create a new NeverAllow rule.
447func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100448 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800449}
Colin Crossfd4f7432019-03-05 15:06:16 -0800450
Liz Kammera3d79152021-10-28 18:14:04 -0400451// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100452func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800453 r.paths = append(r.paths, cleanPaths(path)...)
454 return r
455}
Colin Crossfd4f7432019-03-05 15:06:16 -0800456
Liz Kammera3d79152021-10-28 18:14:04 -0400457// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100458func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800459 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
460 return r
461}
Colin Crossfd4f7432019-03-05 15:06:16 -0800462
Liz Kammera3d79152021-10-28 18:14:04 -0400463// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100464func (r *rule) InDirectDeps(deps ...string) Rule {
465 for _, d := range deps {
466 r.directDeps[d] = true
467 }
468 return r
469}
470
Liz Kammera3d79152021-10-28 18:14:04 -0400471// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100472func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
473 r.osClasses = append(r.osClasses, osClasses...)
474 return r
475}
476
Liz Kammera3d79152021-10-28 18:14:04 -0400477// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100478func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800479 r.moduleTypes = append(r.moduleTypes, types...)
480 return r
481}
482
Liz Kammera3d79152021-10-28 18:14:04 -0400483// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100484func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800485 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
486 return r
487}
488
Liz Kammera3d79152021-10-28 18:14:04 -0400489// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100490func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100491 return r.WithMatcher(properties, selectMatcher(value))
492}
493
Liz Kammera3d79152021-10-28 18:14:04 -0400494// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100495func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800496 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100497 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100498 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800499 })
500 return r
501}
Colin Crossfd4f7432019-03-05 15:06:16 -0800502
Liz Kammera3d79152021-10-28 18:14:04 -0400503// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100504func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100505 return r.WithoutMatcher(properties, selectMatcher(value))
506}
507
Liz Kammera3d79152021-10-28 18:14:04 -0400508// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100509func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800510 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100511 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100512 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800513 })
514 return r
515}
Colin Crossfd4f7432019-03-05 15:06:16 -0800516
Paul Duffin73bf0542019-07-12 14:12:49 +0100517func selectMatcher(expected string) ValueMatcher {
518 if expected == "*" {
519 return anyMatcherInstance
520 }
521 return &equalMatcher{expected: expected}
522}
523
Liz Kammera3d79152021-10-28 18:14:04 -0400524// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100525func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800526 r.reason = reason
527 return r
528}
529
530func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400531 s := []string{"neverallow requirements. Not allowed:"}
532 if len(r.paths) > 0 {
533 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800534 }
Liz Kammera3d79152021-10-28 18:14:04 -0400535 if len(r.moduleTypes) > 0 {
536 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800537 }
Liz Kammera3d79152021-10-28 18:14:04 -0400538 if len(r.props) > 0 {
539 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800540 }
Liz Kammera3d79152021-10-28 18:14:04 -0400541 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800542 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800543 }
Liz Kammera3d79152021-10-28 18:14:04 -0400544 if len(r.osClasses) > 0 {
545 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100546 }
Liz Kammera3d79152021-10-28 18:14:04 -0400547 if len(r.unlessPaths) > 0 {
548 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
549 }
550 if len(r.unlessModuleTypes) > 0 {
551 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
552 }
553 if len(r.unlessProps) > 0 {
554 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100555 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800556 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400557 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800558 }
Liz Kammera3d79152021-10-28 18:14:04 -0400559 if len(s) == 1 {
560 s[0] = "neverallow requirements (empty)"
561 }
562 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800563}
564
565func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800566 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
567 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800568 return includePath && !excludePath
569}
570
Paul Duffin35781882019-07-25 15:41:09 +0100571func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
572 if len(r.directDeps) == 0 {
573 return true
574 }
575
576 matches := false
577 ctx.VisitDirectDeps(func(m Module) {
578 if !matches {
579 name := ctx.OtherModuleName(m)
580 matches = r.directDeps[name]
581 }
582 })
583
584 return matches
585}
586
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100587func (r *rule) appliesToOsClass(osClass OsClass) bool {
588 if len(r.osClasses) == 0 {
589 return true
590 }
591
592 for _, c := range r.osClasses {
593 if c == osClass {
594 return true
595 }
596 }
597
598 return false
599}
600
Colin Crossfd4f7432019-03-05 15:06:16 -0800601func (r *rule) appliesToModuleType(moduleType string) bool {
602 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
603}
604
Anton Hanssone1b18362021-12-23 15:05:38 +0000605func (r *rule) appliesToProperties(properties []interface{}) bool {
606 includeProps := hasAllProperties(properties, r.props)
607 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800608 return includeProps && !excludeProps
609}
610
Paul Duffinc8111702019-07-22 12:13:55 +0100611func StartsWith(prefix string) ValueMatcher {
612 return &startsWithMatcher{prefix}
613}
614
Anton Hansson45376402020-04-09 14:18:21 +0100615func Regexp(re string) ValueMatcher {
616 r, err := regexp.Compile(re)
617 if err != nil {
618 panic(err)
619 }
620 return &regexMatcher{r}
621}
622
Andrei Onea115e7e72020-06-05 21:14:03 +0100623func NotInList(allowed []string) ValueMatcher {
624 return &notInListMatcher{allowed}
625}
626
Steven Moreland65b3fd92017-12-06 14:18:35 -0800627// assorted utils
628
629func cleanPaths(paths []string) []string {
630 res := make([]string, len(paths))
631 for i, v := range paths {
632 res[i] = filepath.Clean(v) + "/"
633 }
634 return res
635}
636
637func fieldNamesForProperties(propertyNames string) []string {
638 names := strings.Split(propertyNames, ".")
639 for i, v := range names {
640 names[i] = proptools.FieldNameForProperty(v)
641 }
642 return names
643}
644
Anton Hanssone1b18362021-12-23 15:05:38 +0000645func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000647 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800648 return true
649 }
650 }
651 return false
652}
653
Anton Hanssone1b18362021-12-23 15:05:38 +0000654func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800655 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000656 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800657 return false
658 }
659 }
660 return true
661}
662
Anton Hanssone1b18362021-12-23 15:05:38 +0000663func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800664 for _, propertyStruct := range properties {
665 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
666 for _, v := range prop.fields {
667 if !propertiesValue.IsValid() {
668 break
669 }
670 propertiesValue = propertiesValue.FieldByName(v)
671 }
672 if !propertiesValue.IsValid() {
673 continue
674 }
675
Paul Duffin73bf0542019-07-12 14:12:49 +0100676 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000677 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800678 }
679
680 if matchValue(propertiesValue, check) {
681 return true
682 }
683 }
684 return false
685}
686
687func matchValue(value reflect.Value, check func(string) bool) bool {
688 if !value.IsValid() {
689 return false
690 }
691
692 if value.Kind() == reflect.Ptr {
693 if value.IsNil() {
694 return check("")
695 }
696 value = value.Elem()
697 }
698
699 switch value.Kind() {
700 case reflect.String:
701 return check(value.String())
702 case reflect.Bool:
703 return check(strconv.FormatBool(value.Bool()))
704 case reflect.Int:
705 return check(strconv.FormatInt(value.Int(), 10))
706 case reflect.Slice:
707 slice, ok := value.Interface().([]string)
708 if !ok {
709 panic("Can only handle slice of string")
710 }
711 for _, v := range slice {
712 if check(v) {
713 return true
714 }
715 }
716 return false
717 }
718
719 panic("Can't handle type: " + value.Kind().String())
720}
Paul Duffin115445b2019-08-07 15:31:07 +0100721
722var neverallowRulesKey = NewOnceKey("neverallowRules")
723
724func neverallowRules(config Config) []Rule {
725 return config.Once(neverallowRulesKey, func() interface{} {
726 // No test rules were set by setTestNeverallowRules, use the global rules
727 return neverallows
728 }).([]Rule)
729}
730
731// Overrides the default neverallow rules for the supplied config.
732//
733// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100734func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100735 config.Once(neverallowRulesKey, func() interface{} { return testRules })
736}
Paul Duffin45338f02021-03-30 23:07:52 +0100737
738// Prepares for a test by setting neverallow rules and enabling the mutator.
739//
740// If the supplied rules are nil then the default rules are used.
741func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
742 return GroupFixturePreparers(
743 FixtureModifyConfig(func(config Config) {
744 if testRules != nil {
745 setTestNeverallowRules(config, testRules)
746 }
747 }),
748 FixtureRegisterWithContext(func(ctx RegistrationContext) {
749 ctx.PostDepsMutators(registerNeverallowMutator)
750 }),
751 )
752}