blob: 5b5e61328695976543c52454216741220804634a [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())
Neil Fullerdf5f3562018-10-21 17:19:10 +010062}
Steven Moreland65b3fd92017-12-06 14:18:35 -080063
Paul Duffin730f2a52019-06-27 14:08:51 +010064// Add a NeverAllow rule to the set of rules to apply.
65func AddNeverAllowRules(rules ...Rule) {
66 neverallows = append(neverallows, rules...)
67}
68
Jingwen Chen1735b2e2022-10-10 14:30:03 +000069func createBp2BuildRule() Rule {
70 return NeverAllow().
71 With("bazel_module.bp2build_available", "true").
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000072 NotIn("soong_tests"). // only used in tests
Jingwen Chen1735b2e2022-10-10 14:30:03 +000073 Because("setting bp2build_available in Android.bp is not " +
74 "supported for custom conversion, use allowlists.go instead.")
Jingwen Chena4b7eed2022-10-07 09:54:16 +000075}
76
Sam Delmerico46d08b42022-11-15 15:51:04 -050077var (
78 neverallowNotInIncludeDir = []string{
Paul Duffinc8111702019-07-22 12:13:55 +010079 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000080 "art/libnativebridge",
81 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010082 "libcore",
83 "libnativehelper",
84 "external/apache-harmony",
85 "external/apache-xml",
86 "external/boringssl",
87 "external/bouncycastle",
88 "external/conscrypt",
89 "external/icu",
90 "external/okhttp",
91 "external/vixl",
92 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +010093 }
Sam Delmerico46d08b42022-11-15 15:51:04 -050094 neverallowNoUseIncludeDir = []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +000095 "frameworks/av/apex",
96 "frameworks/av/tools",
97 "frameworks/native/cmds",
98 "system/apex",
99 "system/bpf",
100 "system/gatekeeper",
101 "system/hwservicemanager",
102 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000103 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000104 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000105 }
Sam Delmerico46d08b42022-11-15 15:51:04 -0500106)
Paul Duffinc8111702019-07-22 12:13:55 +0100107
Sam Delmerico46d08b42022-11-15 15:51:04 -0500108func createIncludeDirsRules() []Rule {
109 rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000110
Sam Delmerico46d08b42022-11-15 15:51:04 -0500111 for _, path := range neverallowNotInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100112 rule :=
113 NeverAllow().
114 WithMatcher("include_dirs", StartsWith(path+"/")).
115 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
116 " to use alternate mechanisms and so can no longer be used.")
117
118 rules = append(rules, rule)
119 }
120
Sam Delmerico46d08b42022-11-15 15:51:04 -0500121 for _, path := range neverallowNoUseIncludeDir {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000122 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
123 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
124 " to use alternate mechanisms and so can no longer be used.")
125 rules = append(rules, rule)
126 }
127
Paul Duffinc8111702019-07-22 12:13:55 +0100128 return rules
129}
130
Paul Duffin730f2a52019-06-27 14:08:51 +0100131func createTrebleRules() []Rule {
132 return []Rule{
133 NeverAllow().
134 In("vendor", "device").
135 With("vndk.enabled", "true").
136 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900137 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100138 Because("the VNDK can never contain a library that is device dependent."),
139 NeverAllow().
140 With("vndk.enabled", "true").
141 Without("vendor", "true").
142 Without("owner", "").
143 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800144
Neil Fullerdf5f3562018-10-21 17:19:10 +0100145 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800147 Without("name", "libhidlbase-combined-impl").
148 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100149 With("product_variables.enforce_vintf_manifest.cflags", "*").
150 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100151
152 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100153 NeverAllow().
154 Without("name", "libc_bionic_ndk").
155 With("product_variables.treble_linker_namespaces.cflags", "*").
156 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100157
158 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100159 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100160 }
161}
162
Paul Duffin730f2a52019-06-27 14:08:51 +0100163func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700164 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700165 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700166 "external/guava",
Steve Elliott8053f822022-10-18 17:09:28 -0400167 "external/kotlinx.coroutines",
Colin Crossfd4f7432019-03-05 15:06:16 -0800168 "external/robolectric-shadows",
Rex Hoffman54641d22022-08-25 17:29:50 +0000169 "external/robolectric",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000170 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800171 }
172
Paul Duffin730f2a52019-06-27 14:08:51 +0100173 return []Rule{
174 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700175 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100176 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700177 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800178 }
179}
180
Colin Crossc511bc52020-04-07 16:50:32 +0000181func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700182 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000183 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
184 // This sometimes works because the APEX modules that contain derive_sdk and
185 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
186 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100187 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700188 // These are for apps and shouldn't be used by non-SDK variant modules.
189 "prebuilts/ndk",
190 "tools/test/graphicsbenchmark/apps/sample_app",
191 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700192 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000193 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000194 }
195
Colin Cross440e0d02020-06-11 11:32:11 -0700196 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000197 // android_native_app_glue and libRSSupport use native_window.h but target old
198 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
199 // so they can't add libnativewindow to shared_libs to get the header directory
200 // for the platform variant. Allow them to use the platform variant
201 // property to set shared_libs.
202 "prebuilts/ndk",
203 "frameworks/rs",
204 }
205
206 return []Rule{
207 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700208 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000209 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700210 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000211 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700212 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000213 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700214 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000215 }
216}
217
Alan Stokes73feba32022-11-14 12:21:24 +0000218func createCcStubsRule() Rule {
219 ccStubsImplementationInstallableProjectsAllowedList := []string{
220 "packages/modules/Virtualization/vm_payload",
221 }
222
223 return NeverAllow().
224 NotIn(ccStubsImplementationInstallableProjectsAllowedList...).
225 WithMatcher("stubs.implementation_installable", isSetMatcherInstance).
226 Because("implementation_installable can only be used in allowed projects.")
227}
228
David Srbeckye033cba2020-05-20 22:20:28 +0100229func createUncompressDexRules() []Rule {
230 return []Rule{
231 NeverAllow().
232 NotIn("art").
233 WithMatcher("uncompress_dex", isSetMatcherInstance).
234 Because("uncompress_dex is only allowed for certain jars for test in art."),
235 }
236}
237
Inseob Kim800d1142021-06-14 12:03:51 +0900238func createInitFirstStageRules() []Rule {
239 return []Rule{
240 NeverAllow().
241 Without("name", "init_first_stage").
242 With("install_in_root", "true").
243 Because("install_in_root is only for init_first_stage."),
244 }
245}
246
Jiyong Park3c306f32022-04-05 15:29:53 +0900247func createProhibitFrameworkAccessRules() []Rule {
248 return []Rule{
249 NeverAllow().
250 With("libs", "framework").
251 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
252 Because("framework can't be used when building against SDK"),
253 }
254}
255
Steven Moreland65b3fd92017-12-06 14:18:35 -0800256func neverallowMutator(ctx BottomUpMutatorContext) {
257 m, ok := ctx.Module().(Module)
258 if !ok {
259 return
260 }
261
262 dir := ctx.ModuleDir() + "/"
263 properties := m.GetProperties()
264
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100265 osClass := ctx.Module().Target().Os.Class
266
Paul Duffin115445b2019-08-07 15:31:07 +0100267 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100268 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800269 if !n.appliesToPath(dir) {
270 continue
271 }
272
Colin Crossfd4f7432019-03-05 15:06:16 -0800273 if !n.appliesToModuleType(ctx.ModuleType()) {
274 continue
275 }
276
Anton Hanssone1b18362021-12-23 15:05:38 +0000277 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800278 continue
279 }
280
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100281 if !n.appliesToOsClass(osClass) {
282 continue
283 }
284
Paul Duffin35781882019-07-25 15:41:09 +0100285 if !n.appliesToDirectDeps(ctx) {
286 continue
287 }
288
Steven Moreland65b3fd92017-12-06 14:18:35 -0800289 ctx.ModuleErrorf("violates " + n.String())
290 }
291}
292
Paul Duffin73bf0542019-07-12 14:12:49 +0100293type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000294 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100295 String() string
296}
297
298type equalMatcher struct {
299 expected string
300}
301
Anton Hanssone1b18362021-12-23 15:05:38 +0000302func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100303 return m.expected == value
304}
305
306func (m *equalMatcher) String() string {
307 return "=" + m.expected
308}
309
310type anyMatcher struct {
311}
312
Anton Hanssone1b18362021-12-23 15:05:38 +0000313func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100314 return true
315}
316
317func (m *anyMatcher) String() string {
318 return "=*"
319}
320
321var anyMatcherInstance = &anyMatcher{}
322
Paul Duffinc8111702019-07-22 12:13:55 +0100323type startsWithMatcher struct {
324 prefix string
325}
326
Anton Hanssone1b18362021-12-23 15:05:38 +0000327func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100328 return strings.HasPrefix(value, m.prefix)
329}
330
331func (m *startsWithMatcher) String() string {
332 return ".starts-with(" + m.prefix + ")"
333}
334
Anton Hansson45376402020-04-09 14:18:21 +0100335type regexMatcher struct {
336 re *regexp.Regexp
337}
338
Anton Hanssone1b18362021-12-23 15:05:38 +0000339func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100340 return m.re.MatchString(value)
341}
342
343func (m *regexMatcher) String() string {
344 return ".regexp(" + m.re.String() + ")"
345}
346
Andrei Onea115e7e72020-06-05 21:14:03 +0100347type notInListMatcher struct {
348 allowed []string
349}
350
Anton Hanssone1b18362021-12-23 15:05:38 +0000351func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100352 return !InList(value, m.allowed)
353}
354
355func (m *notInListMatcher) String() string {
356 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
357}
358
Colin Crossc511bc52020-04-07 16:50:32 +0000359type isSetMatcher struct{}
360
Anton Hanssone1b18362021-12-23 15:05:38 +0000361func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000362 return value != ""
363}
364
365func (m *isSetMatcher) String() string {
366 return ".is-set"
367}
368
369var isSetMatcherInstance = &isSetMatcher{}
370
Steven Moreland65b3fd92017-12-06 14:18:35 -0800371type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100372 fields []string // e.x.: Vndk.Enabled
373 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800374}
375
Liz Kammera3d79152021-10-28 18:14:04 -0400376func (r *ruleProperty) String() string {
377 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
378}
379
380type ruleProperties []ruleProperty
381
382func (r ruleProperties) String() string {
383 var s []string
384 for _, r := range r {
385 s = append(s, r.String())
386 }
387 return strings.Join(s, " ")
388}
389
Paul Duffin730f2a52019-06-27 14:08:51 +0100390// A NeverAllow rule.
391type Rule interface {
392 In(path ...string) Rule
393
394 NotIn(path ...string) Rule
395
Paul Duffin35781882019-07-25 15:41:09 +0100396 InDirectDeps(deps ...string) Rule
397
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100398 WithOsClass(osClasses ...OsClass) Rule
399
Paul Duffin730f2a52019-06-27 14:08:51 +0100400 ModuleType(types ...string) Rule
401
402 NotModuleType(types ...string) Rule
403
404 With(properties, value string) Rule
405
Paul Duffinc8111702019-07-22 12:13:55 +0100406 WithMatcher(properties string, matcher ValueMatcher) Rule
407
Paul Duffin730f2a52019-06-27 14:08:51 +0100408 Without(properties, value string) Rule
409
Paul Duffinc8111702019-07-22 12:13:55 +0100410 WithoutMatcher(properties string, matcher ValueMatcher) Rule
411
Paul Duffin730f2a52019-06-27 14:08:51 +0100412 Because(reason string) Rule
413}
414
Steven Moreland65b3fd92017-12-06 14:18:35 -0800415type rule struct {
416 // User string for why this is a thing.
417 reason string
418
419 paths []string
420 unlessPaths []string
421
Paul Duffin35781882019-07-25 15:41:09 +0100422 directDeps map[string]bool
423
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100424 osClasses []OsClass
425
Colin Crossfd4f7432019-03-05 15:06:16 -0800426 moduleTypes []string
427 unlessModuleTypes []string
428
Liz Kammera3d79152021-10-28 18:14:04 -0400429 props ruleProperties
430 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100431
432 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800433}
434
Paul Duffin730f2a52019-06-27 14:08:51 +0100435// Create a new NeverAllow rule.
436func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100437 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800438}
Colin Crossfd4f7432019-03-05 15:06:16 -0800439
Liz Kammera3d79152021-10-28 18:14:04 -0400440// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100441func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800442 r.paths = append(r.paths, cleanPaths(path)...)
443 return r
444}
Colin Crossfd4f7432019-03-05 15:06:16 -0800445
Liz Kammera3d79152021-10-28 18:14:04 -0400446// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100447func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800448 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
449 return r
450}
Colin Crossfd4f7432019-03-05 15:06:16 -0800451
Liz Kammera3d79152021-10-28 18:14:04 -0400452// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100453func (r *rule) InDirectDeps(deps ...string) Rule {
454 for _, d := range deps {
455 r.directDeps[d] = true
456 }
457 return r
458}
459
Liz Kammera3d79152021-10-28 18:14:04 -0400460// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100461func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
462 r.osClasses = append(r.osClasses, osClasses...)
463 return r
464}
465
Liz Kammera3d79152021-10-28 18:14:04 -0400466// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100467func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800468 r.moduleTypes = append(r.moduleTypes, types...)
469 return r
470}
471
Liz Kammera3d79152021-10-28 18:14:04 -0400472// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100473func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800474 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
475 return r
476}
477
Liz Kammera3d79152021-10-28 18:14:04 -0400478// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100479func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100480 return r.WithMatcher(properties, selectMatcher(value))
481}
482
Liz Kammera3d79152021-10-28 18:14:04 -0400483// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100484func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800485 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100486 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100487 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800488 })
489 return r
490}
Colin Crossfd4f7432019-03-05 15:06:16 -0800491
Liz Kammera3d79152021-10-28 18:14:04 -0400492// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100493func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100494 return r.WithoutMatcher(properties, selectMatcher(value))
495}
496
Liz Kammera3d79152021-10-28 18:14:04 -0400497// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100498func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800499 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100500 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100501 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800502 })
503 return r
504}
Colin Crossfd4f7432019-03-05 15:06:16 -0800505
Paul Duffin73bf0542019-07-12 14:12:49 +0100506func selectMatcher(expected string) ValueMatcher {
507 if expected == "*" {
508 return anyMatcherInstance
509 }
510 return &equalMatcher{expected: expected}
511}
512
Liz Kammera3d79152021-10-28 18:14:04 -0400513// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100514func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800515 r.reason = reason
516 return r
517}
518
519func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400520 s := []string{"neverallow requirements. Not allowed:"}
521 if len(r.paths) > 0 {
522 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800523 }
Liz Kammera3d79152021-10-28 18:14:04 -0400524 if len(r.moduleTypes) > 0 {
525 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800526 }
Liz Kammera3d79152021-10-28 18:14:04 -0400527 if len(r.props) > 0 {
528 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800529 }
Liz Kammera3d79152021-10-28 18:14:04 -0400530 if len(r.directDeps) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -0800531 s = append(s, fmt.Sprintf("dep(s): %q", SortedKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800532 }
Liz Kammera3d79152021-10-28 18:14:04 -0400533 if len(r.osClasses) > 0 {
534 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100535 }
Liz Kammera3d79152021-10-28 18:14:04 -0400536 if len(r.unlessPaths) > 0 {
537 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
538 }
539 if len(r.unlessModuleTypes) > 0 {
540 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
541 }
542 if len(r.unlessProps) > 0 {
543 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100544 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800545 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400546 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800547 }
Liz Kammera3d79152021-10-28 18:14:04 -0400548 if len(s) == 1 {
549 s[0] = "neverallow requirements (empty)"
550 }
551 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800552}
553
554func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800555 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
556 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800557 return includePath && !excludePath
558}
559
Paul Duffin35781882019-07-25 15:41:09 +0100560func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
561 if len(r.directDeps) == 0 {
562 return true
563 }
564
565 matches := false
566 ctx.VisitDirectDeps(func(m Module) {
567 if !matches {
568 name := ctx.OtherModuleName(m)
569 matches = r.directDeps[name]
570 }
571 })
572
573 return matches
574}
575
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100576func (r *rule) appliesToOsClass(osClass OsClass) bool {
577 if len(r.osClasses) == 0 {
578 return true
579 }
580
581 for _, c := range r.osClasses {
582 if c == osClass {
583 return true
584 }
585 }
586
587 return false
588}
589
Colin Crossfd4f7432019-03-05 15:06:16 -0800590func (r *rule) appliesToModuleType(moduleType string) bool {
591 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
592}
593
Anton Hanssone1b18362021-12-23 15:05:38 +0000594func (r *rule) appliesToProperties(properties []interface{}) bool {
595 includeProps := hasAllProperties(properties, r.props)
596 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800597 return includeProps && !excludeProps
598}
599
Paul Duffinc8111702019-07-22 12:13:55 +0100600func StartsWith(prefix string) ValueMatcher {
601 return &startsWithMatcher{prefix}
602}
603
Anton Hansson45376402020-04-09 14:18:21 +0100604func Regexp(re string) ValueMatcher {
605 r, err := regexp.Compile(re)
606 if err != nil {
607 panic(err)
608 }
609 return &regexMatcher{r}
610}
611
Andrei Onea115e7e72020-06-05 21:14:03 +0100612func NotInList(allowed []string) ValueMatcher {
613 return &notInListMatcher{allowed}
614}
615
Steven Moreland65b3fd92017-12-06 14:18:35 -0800616// assorted utils
617
618func cleanPaths(paths []string) []string {
619 res := make([]string, len(paths))
620 for i, v := range paths {
621 res[i] = filepath.Clean(v) + "/"
622 }
623 return res
624}
625
626func fieldNamesForProperties(propertyNames string) []string {
627 names := strings.Split(propertyNames, ".")
628 for i, v := range names {
629 names[i] = proptools.FieldNameForProperty(v)
630 }
631 return names
632}
633
Anton Hanssone1b18362021-12-23 15:05:38 +0000634func hasAnyProperty(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800635 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000636 if hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800637 return true
638 }
639 }
640 return false
641}
642
Anton Hanssone1b18362021-12-23 15:05:38 +0000643func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800644 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000645 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800646 return false
647 }
648 }
649 return true
650}
651
Anton Hanssone1b18362021-12-23 15:05:38 +0000652func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653 for _, propertyStruct := range properties {
654 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
655 for _, v := range prop.fields {
656 if !propertiesValue.IsValid() {
657 break
658 }
659 propertiesValue = propertiesValue.FieldByName(v)
660 }
661 if !propertiesValue.IsValid() {
662 continue
663 }
664
Paul Duffin73bf0542019-07-12 14:12:49 +0100665 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000666 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800667 }
668
669 if matchValue(propertiesValue, check) {
670 return true
671 }
672 }
673 return false
674}
675
676func matchValue(value reflect.Value, check func(string) bool) bool {
677 if !value.IsValid() {
678 return false
679 }
680
681 if value.Kind() == reflect.Ptr {
682 if value.IsNil() {
683 return check("")
684 }
685 value = value.Elem()
686 }
687
688 switch value.Kind() {
689 case reflect.String:
690 return check(value.String())
691 case reflect.Bool:
692 return check(strconv.FormatBool(value.Bool()))
693 case reflect.Int:
694 return check(strconv.FormatInt(value.Int(), 10))
695 case reflect.Slice:
696 slice, ok := value.Interface().([]string)
697 if !ok {
698 panic("Can only handle slice of string")
699 }
700 for _, v := range slice {
701 if check(v) {
702 return true
703 }
704 }
705 return false
706 }
707
708 panic("Can't handle type: " + value.Kind().String())
709}
Paul Duffin115445b2019-08-07 15:31:07 +0100710
711var neverallowRulesKey = NewOnceKey("neverallowRules")
712
713func neverallowRules(config Config) []Rule {
714 return config.Once(neverallowRulesKey, func() interface{} {
715 // No test rules were set by setTestNeverallowRules, use the global rules
716 return neverallows
717 }).([]Rule)
718}
719
720// Overrides the default neverallow rules for the supplied config.
721//
722// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100723func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100724 config.Once(neverallowRulesKey, func() interface{} { return testRules })
725}
Paul Duffin45338f02021-03-30 23:07:52 +0100726
727// Prepares for a test by setting neverallow rules and enabling the mutator.
728//
729// If the supplied rules are nil then the default rules are used.
730func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
731 return GroupFixturePreparers(
732 FixtureModifyConfig(func(config Config) {
733 if testRules != nil {
734 setTestNeverallowRules(config, testRules)
735 }
736 }),
737 FixtureRegisterWithContext(func(ctx RegistrationContext) {
738 ctx.PostDepsMutators(registerNeverallowMutator)
739 }),
740 )
741}