blob: 274523806b8965ac711e5622c2b491caf0b2bfbe [file] [log] [blame]
Steven Moreland65b3fd92017-12-06 14:18:35 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
Liz Kammera3d79152021-10-28 18:14:04 -040018 "fmt"
Steven Moreland65b3fd92017-12-06 14:18:35 -080019 "path/filepath"
20 "reflect"
Anton Hansson45376402020-04-09 14:18:21 +010021 "regexp"
Steven Moreland65b3fd92017-12-06 14:18:35 -080022 "strconv"
23 "strings"
24
25 "github.com/google/blueprint/proptools"
26)
27
28// "neverallow" rules for the build system.
29//
30// This allows things which aren't related to the build system and are enforced
Joe Onoratob4638c12021-10-27 15:47:06 -070031// against assumptions, in progress code refactors, or policy to be expressed in a
Steven Moreland65b3fd92017-12-06 14:18:35 -080032// straightforward away disjoint from implementations and tests which should
33// work regardless of these restrictions.
34//
35// A module is disallowed if all of the following are true:
Paul Duffin730f2a52019-06-27 14:08:51 +010036// - it is in one of the "In" paths
37// - it is not in one of the "NotIn" paths
38// - it has all "With" properties matched
Steven Moreland65b3fd92017-12-06 14:18:35 -080039// - - values are matched in their entirety
40// - - nil is interpreted as an empty string
41// - - nested properties are separated with a '.'
42// - - if the property is a list, any of the values in the list being matches
43// counts as a match
Paul Duffin730f2a52019-06-27 14:08:51 +010044// - it has none of the "Without" properties matched (same rules as above)
Steven Moreland65b3fd92017-12-06 14:18:35 -080045
Paul Duffin45338f02021-03-30 23:07:52 +010046func registerNeverallowMutator(ctx RegisterMutatorsContext) {
Steven Moreland65b3fd92017-12-06 14:18:35 -080047 ctx.BottomUp("neverallow", neverallowMutator).Parallel()
48}
49
Paul Duffin730f2a52019-06-27 14:08:51 +010050var neverallows = []Rule{}
Steven Moreland65b3fd92017-12-06 14:18:35 -080051
Paul Duffin730f2a52019-06-27 14:08:51 +010052func init() {
Paul Duffinc8111702019-07-22 12:13:55 +010053 AddNeverAllowRules(createIncludeDirsRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010054 AddNeverAllowRules(createTrebleRules()...)
Paul Duffin730f2a52019-06-27 14:08:51 +010055 AddNeverAllowRules(createJavaDeviceForHostRules()...)
Colin Crossc511bc52020-04-07 16:50:32 +000056 AddNeverAllowRules(createCcSdkVariantRules()...)
David Srbeckye033cba2020-05-20 22:20:28 +010057 AddNeverAllowRules(createUncompressDexRules()...)
Yifan Hong696ed4d2020-07-27 12:59:58 -070058 AddNeverAllowRules(createMakefileGoalRules()...)
Inseob Kim800d1142021-06-14 12:03:51 +090059 AddNeverAllowRules(createInitFirstStageRules()...)
Jiyong Park3c306f32022-04-05 15:29:53 +090060 AddNeverAllowRules(createProhibitFrameworkAccessRules()...)
Jingwen Chena4b7eed2022-10-07 09:54:16 +000061 AddNeverAllowRules(createBp2BuildRules()...)
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 Chena4b7eed2022-10-07 09:54:16 +000069func createBp2BuildRules() []Rule {
70 rules := []Rule{}
71 bp2buildAvailableAllowedDirs := []string{
72 // Can we just allowlist these modules in allowlists.go?
73 "bionic/libc",
74 }
75
76 for _, dir := range bp2buildAvailableAllowedDirs {
77 rule := NeverAllow().
78 With("bazel_module.bp2build_available", "true").
79 NotIn(dir).
80 Because("disallowed usages of bp2build_available for custom conversion")
81 rules = append(rules, rule)
82 }
83
84 return rules
85}
86
Paul Duffinc8111702019-07-22 12:13:55 +010087func createIncludeDirsRules() []Rule {
Steven Moreland8fc8dbf2021-04-27 02:31:07 +000088 notInIncludeDir := []string{
Paul Duffinc8111702019-07-22 12:13:55 +010089 "art",
Orion Hodson6341f012019-11-06 13:39:46 +000090 "art/libnativebridge",
91 "art/libnativeloader",
Paul Duffinc8111702019-07-22 12:13:55 +010092 "libcore",
93 "libnativehelper",
94 "external/apache-harmony",
95 "external/apache-xml",
96 "external/boringssl",
97 "external/bouncycastle",
98 "external/conscrypt",
99 "external/icu",
100 "external/okhttp",
101 "external/vixl",
102 "external/wycheproof",
Paul Duffinc8111702019-07-22 12:13:55 +0100103 }
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000104 noUseIncludeDir := []string{
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000105 "frameworks/av/apex",
106 "frameworks/av/tools",
107 "frameworks/native/cmds",
108 "system/apex",
109 "system/bpf",
110 "system/gatekeeper",
111 "system/hwservicemanager",
112 "system/libbase",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000113 "system/libfmq",
Steven Morelandf36a3ac2021-04-27 18:03:14 +0000114 "system/libvintf",
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000115 }
Paul Duffinc8111702019-07-22 12:13:55 +0100116
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000117 rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
118
119 for _, path := range notInIncludeDir {
Paul Duffinc8111702019-07-22 12:13:55 +0100120 rule :=
121 NeverAllow().
122 WithMatcher("include_dirs", StartsWith(path+"/")).
123 Because("include_dirs is deprecated, all usages of '" + path + "' have been migrated" +
124 " to use alternate mechanisms and so can no longer be used.")
125
126 rules = append(rules, rule)
127 }
128
Steven Moreland8fc8dbf2021-04-27 02:31:07 +0000129 for _, path := range noUseIncludeDir {
130 rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
131 Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
132 " to use alternate mechanisms and so can no longer be used.")
133 rules = append(rules, rule)
134 }
135
Paul Duffinc8111702019-07-22 12:13:55 +0100136 return rules
137}
138
Paul Duffin730f2a52019-06-27 14:08:51 +0100139func createTrebleRules() []Rule {
140 return []Rule{
141 NeverAllow().
142 In("vendor", "device").
143 With("vndk.enabled", "true").
144 Without("vendor", "true").
Justin Yun0ecf0b22020-02-28 15:07:59 +0900145 Without("product_specific", "true").
Paul Duffin730f2a52019-06-27 14:08:51 +0100146 Because("the VNDK can never contain a library that is device dependent."),
147 NeverAllow().
148 With("vndk.enabled", "true").
149 Without("vendor", "true").
150 Without("owner", "").
151 Because("a VNDK module can never have an owner."),
Steven Moreland65b3fd92017-12-06 14:18:35 -0800152
Neil Fullerdf5f3562018-10-21 17:19:10 +0100153 // TODO(b/67974785): always enforce the manifest
Paul Duffin730f2a52019-06-27 14:08:51 +0100154 NeverAllow().
Steven Moreland51ce4f62020-02-10 17:21:32 -0800155 Without("name", "libhidlbase-combined-impl").
156 Without("name", "libhidlbase").
Paul Duffin730f2a52019-06-27 14:08:51 +0100157 With("product_variables.enforce_vintf_manifest.cflags", "*").
158 Because("manifest enforcement should be independent of ."),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100159
160 // TODO(b/67975799): vendor code should always use /vendor/bin/sh
Paul Duffin730f2a52019-06-27 14:08:51 +0100161 NeverAllow().
162 Without("name", "libc_bionic_ndk").
163 With("product_variables.treble_linker_namespaces.cflags", "*").
164 Because("nothing should care if linker namespaces are enabled or not"),
Neil Fullerdf5f3562018-10-21 17:19:10 +0100165
166 // Example:
Paul Duffin730f2a52019-06-27 14:08:51 +0100167 // *NeverAllow().with("Srcs", "main.cpp"))
Neil Fullerdf5f3562018-10-21 17:19:10 +0100168 }
169}
170
Paul Duffin730f2a52019-06-27 14:08:51 +0100171func createJavaDeviceForHostRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700172 javaDeviceForHostProjectsAllowedList := []string{
Dan Willemsen9fe14102021-07-13 21:52:04 -0700173 "development/build",
Colin Crossb5191a52019-04-11 14:07:38 -0700174 "external/guava",
Colin Crossfd4f7432019-03-05 15:06:16 -0800175 "external/robolectric-shadows",
Jerome Gaillard655ee022021-09-23 11:38:08 +0000176 "frameworks/layoutlib",
Colin Crossfd4f7432019-03-05 15:06:16 -0800177 }
178
Paul Duffin730f2a52019-06-27 14:08:51 +0100179 return []Rule{
180 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700181 NotIn(javaDeviceForHostProjectsAllowedList...).
Paul Duffin730f2a52019-06-27 14:08:51 +0100182 ModuleType("java_device_for_host", "java_host_for_device").
Colin Cross440e0d02020-06-11 11:32:11 -0700183 Because("java_device_for_host can only be used in allowed projects"),
Colin Crossfd4f7432019-03-05 15:06:16 -0800184 }
185}
186
Colin Crossc511bc52020-04-07 16:50:32 +0000187func createCcSdkVariantRules() []Rule {
Colin Cross440e0d02020-06-11 11:32:11 -0700188 sdkVersionOnlyAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000189 // derive_sdk_prefer32 has stem: "derive_sdk" which conflicts with the derive_sdk.
190 // This sometimes works because the APEX modules that contain derive_sdk and
191 // derive_sdk_prefer32 suppress the platform installation rules, but fails when
192 // the APEX modules contain the SDK variant and the platform variant still exists.
Anton Hansson4b8e64b2020-05-27 18:25:23 +0100193 "packages/modules/SdkExtensions/derive_sdk",
Dan Alberte2054a92020-04-20 14:46:47 -0700194 // These are for apps and shouldn't be used by non-SDK variant modules.
195 "prebuilts/ndk",
196 "tools/test/graphicsbenchmark/apps/sample_app",
197 "tools/test/graphicsbenchmark/functional_tests/java",
Dan Albert55576052020-04-20 14:46:47 -0700198 "vendor/xts/gts-tests/hostsidetests/gamedevicecert/apps/javatests",
Chang Li66d3cb72021-06-18 14:04:50 +0000199 "external/libtextclassifier/native",
Colin Crossc511bc52020-04-07 16:50:32 +0000200 }
201
Colin Cross440e0d02020-06-11 11:32:11 -0700202 platformVariantPropertiesAllowedList := []string{
Colin Crossc511bc52020-04-07 16:50:32 +0000203 // android_native_app_glue and libRSSupport use native_window.h but target old
204 // sdk versions (minimum and 9 respectively) where libnativewindow didn't exist,
205 // so they can't add libnativewindow to shared_libs to get the header directory
206 // for the platform variant. Allow them to use the platform variant
207 // property to set shared_libs.
208 "prebuilts/ndk",
209 "frameworks/rs",
210 }
211
212 return []Rule{
213 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700214 NotIn(sdkVersionOnlyAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000215 WithMatcher("sdk_variant_only", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700216 Because("sdk_variant_only can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000217 NeverAllow().
Colin Cross440e0d02020-06-11 11:32:11 -0700218 NotIn(platformVariantPropertiesAllowedList...).
Colin Crossc511bc52020-04-07 16:50:32 +0000219 WithMatcher("platform.shared_libs", isSetMatcherInstance).
Colin Cross440e0d02020-06-11 11:32:11 -0700220 Because("platform variant properties can only be used in allowed projects"),
Colin Crossc511bc52020-04-07 16:50:32 +0000221 }
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
Yifan Hong696ed4d2020-07-27 12:59:58 -0700233func createMakefileGoalRules() []Rule {
Jooyung Han39cadf92022-07-25 12:32:32 +0900234 allowlist := []string{
235 // libwifi_hal uses makefile_goal for its dependencies
236 "frameworks/opt/net/wifi/libwifi_hal",
237 }
Yifan Hong696ed4d2020-07-27 12:59:58 -0700238 return []Rule{
239 NeverAllow().
240 ModuleType("makefile_goal").
241 WithoutMatcher("product_out_path", Regexp("^boot[0-9a-zA-Z.-]*[.]img$")).
Jooyung Han39cadf92022-07-25 12:32:32 +0900242 NotIn(allowlist...).
243 Because("Only boot images may be imported as a makefile goal if not in allowed projects"),
Yifan Hong696ed4d2020-07-27 12:59:58 -0700244 }
245}
246
Inseob Kim800d1142021-06-14 12:03:51 +0900247func createInitFirstStageRules() []Rule {
248 return []Rule{
249 NeverAllow().
250 Without("name", "init_first_stage").
251 With("install_in_root", "true").
252 Because("install_in_root is only for init_first_stage."),
253 }
254}
255
Jiyong Park3c306f32022-04-05 15:29:53 +0900256func createProhibitFrameworkAccessRules() []Rule {
257 return []Rule{
258 NeverAllow().
259 With("libs", "framework").
260 WithoutMatcher("sdk_version", Regexp("(core_.*|^$)")).
261 Because("framework can't be used when building against SDK"),
262 }
263}
264
Steven Moreland65b3fd92017-12-06 14:18:35 -0800265func neverallowMutator(ctx BottomUpMutatorContext) {
266 m, ok := ctx.Module().(Module)
267 if !ok {
268 return
269 }
270
271 dir := ctx.ModuleDir() + "/"
272 properties := m.GetProperties()
273
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100274 osClass := ctx.Module().Target().Os.Class
275
Paul Duffin115445b2019-08-07 15:31:07 +0100276 for _, r := range neverallowRules(ctx.Config()) {
Paul Duffin730f2a52019-06-27 14:08:51 +0100277 n := r.(*rule)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800278 if !n.appliesToPath(dir) {
279 continue
280 }
281
Colin Crossfd4f7432019-03-05 15:06:16 -0800282 if !n.appliesToModuleType(ctx.ModuleType()) {
283 continue
284 }
285
Anton Hanssone1b18362021-12-23 15:05:38 +0000286 if !n.appliesToProperties(properties) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800287 continue
288 }
289
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100290 if !n.appliesToOsClass(osClass) {
291 continue
292 }
293
Paul Duffin35781882019-07-25 15:41:09 +0100294 if !n.appliesToDirectDeps(ctx) {
295 continue
296 }
297
Steven Moreland65b3fd92017-12-06 14:18:35 -0800298 ctx.ModuleErrorf("violates " + n.String())
299 }
300}
301
Paul Duffin73bf0542019-07-12 14:12:49 +0100302type ValueMatcher interface {
Anton Hanssone1b18362021-12-23 15:05:38 +0000303 Test(string) bool
Paul Duffin73bf0542019-07-12 14:12:49 +0100304 String() string
305}
306
307type equalMatcher struct {
308 expected string
309}
310
Anton Hanssone1b18362021-12-23 15:05:38 +0000311func (m *equalMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100312 return m.expected == value
313}
314
315func (m *equalMatcher) String() string {
316 return "=" + m.expected
317}
318
319type anyMatcher struct {
320}
321
Anton Hanssone1b18362021-12-23 15:05:38 +0000322func (m *anyMatcher) Test(value string) bool {
Paul Duffin73bf0542019-07-12 14:12:49 +0100323 return true
324}
325
326func (m *anyMatcher) String() string {
327 return "=*"
328}
329
330var anyMatcherInstance = &anyMatcher{}
331
Paul Duffinc8111702019-07-22 12:13:55 +0100332type startsWithMatcher struct {
333 prefix string
334}
335
Anton Hanssone1b18362021-12-23 15:05:38 +0000336func (m *startsWithMatcher) Test(value string) bool {
Paul Duffinc8111702019-07-22 12:13:55 +0100337 return strings.HasPrefix(value, m.prefix)
338}
339
340func (m *startsWithMatcher) String() string {
341 return ".starts-with(" + m.prefix + ")"
342}
343
Anton Hansson45376402020-04-09 14:18:21 +0100344type regexMatcher struct {
345 re *regexp.Regexp
346}
347
Anton Hanssone1b18362021-12-23 15:05:38 +0000348func (m *regexMatcher) Test(value string) bool {
Anton Hansson45376402020-04-09 14:18:21 +0100349 return m.re.MatchString(value)
350}
351
352func (m *regexMatcher) String() string {
353 return ".regexp(" + m.re.String() + ")"
354}
355
Andrei Onea115e7e72020-06-05 21:14:03 +0100356type notInListMatcher struct {
357 allowed []string
358}
359
Anton Hanssone1b18362021-12-23 15:05:38 +0000360func (m *notInListMatcher) Test(value string) bool {
Andrei Onea115e7e72020-06-05 21:14:03 +0100361 return !InList(value, m.allowed)
362}
363
364func (m *notInListMatcher) String() string {
365 return ".not-in-list(" + strings.Join(m.allowed, ",") + ")"
366}
367
Colin Crossc511bc52020-04-07 16:50:32 +0000368type isSetMatcher struct{}
369
Anton Hanssone1b18362021-12-23 15:05:38 +0000370func (m *isSetMatcher) Test(value string) bool {
Colin Crossc511bc52020-04-07 16:50:32 +0000371 return value != ""
372}
373
374func (m *isSetMatcher) String() string {
375 return ".is-set"
376}
377
378var isSetMatcherInstance = &isSetMatcher{}
379
Steven Moreland65b3fd92017-12-06 14:18:35 -0800380type ruleProperty struct {
Paul Duffin73bf0542019-07-12 14:12:49 +0100381 fields []string // e.x.: Vndk.Enabled
382 matcher ValueMatcher
Steven Moreland65b3fd92017-12-06 14:18:35 -0800383}
384
Liz Kammera3d79152021-10-28 18:14:04 -0400385func (r *ruleProperty) String() string {
386 return fmt.Sprintf("%q matches: %s", strings.Join(r.fields, "."), r.matcher)
387}
388
389type ruleProperties []ruleProperty
390
391func (r ruleProperties) String() string {
392 var s []string
393 for _, r := range r {
394 s = append(s, r.String())
395 }
396 return strings.Join(s, " ")
397}
398
Paul Duffin730f2a52019-06-27 14:08:51 +0100399// A NeverAllow rule.
400type Rule interface {
401 In(path ...string) Rule
402
403 NotIn(path ...string) Rule
404
Paul Duffin35781882019-07-25 15:41:09 +0100405 InDirectDeps(deps ...string) Rule
406
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100407 WithOsClass(osClasses ...OsClass) Rule
408
Paul Duffin730f2a52019-06-27 14:08:51 +0100409 ModuleType(types ...string) Rule
410
411 NotModuleType(types ...string) Rule
412
413 With(properties, value string) Rule
414
Paul Duffinc8111702019-07-22 12:13:55 +0100415 WithMatcher(properties string, matcher ValueMatcher) Rule
416
Paul Duffin730f2a52019-06-27 14:08:51 +0100417 Without(properties, value string) Rule
418
Paul Duffinc8111702019-07-22 12:13:55 +0100419 WithoutMatcher(properties string, matcher ValueMatcher) Rule
420
Paul Duffin730f2a52019-06-27 14:08:51 +0100421 Because(reason string) Rule
422}
423
Steven Moreland65b3fd92017-12-06 14:18:35 -0800424type rule struct {
425 // User string for why this is a thing.
426 reason string
427
428 paths []string
429 unlessPaths []string
430
Paul Duffin35781882019-07-25 15:41:09 +0100431 directDeps map[string]bool
432
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100433 osClasses []OsClass
434
Colin Crossfd4f7432019-03-05 15:06:16 -0800435 moduleTypes []string
436 unlessModuleTypes []string
437
Liz Kammera3d79152021-10-28 18:14:04 -0400438 props ruleProperties
439 unlessProps ruleProperties
Andrei Onea115e7e72020-06-05 21:14:03 +0100440
441 onlyBootclasspathJar bool
Steven Moreland65b3fd92017-12-06 14:18:35 -0800442}
443
Paul Duffin730f2a52019-06-27 14:08:51 +0100444// Create a new NeverAllow rule.
445func NeverAllow() Rule {
Paul Duffin35781882019-07-25 15:41:09 +0100446 return &rule{directDeps: make(map[string]bool)}
Steven Moreland65b3fd92017-12-06 14:18:35 -0800447}
Colin Crossfd4f7432019-03-05 15:06:16 -0800448
Liz Kammera3d79152021-10-28 18:14:04 -0400449// In adds path(s) where this rule applies.
Paul Duffin730f2a52019-06-27 14:08:51 +0100450func (r *rule) In(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800451 r.paths = append(r.paths, cleanPaths(path)...)
452 return r
453}
Colin Crossfd4f7432019-03-05 15:06:16 -0800454
Liz Kammera3d79152021-10-28 18:14:04 -0400455// NotIn adds path(s) to that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100456func (r *rule) NotIn(path ...string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800457 r.unlessPaths = append(r.unlessPaths, cleanPaths(path)...)
458 return r
459}
Colin Crossfd4f7432019-03-05 15:06:16 -0800460
Liz Kammera3d79152021-10-28 18:14:04 -0400461// InDirectDeps adds dep(s) that are not allowed with this rule.
Paul Duffin35781882019-07-25 15:41:09 +0100462func (r *rule) InDirectDeps(deps ...string) Rule {
463 for _, d := range deps {
464 r.directDeps[d] = true
465 }
466 return r
467}
468
Liz Kammera3d79152021-10-28 18:14:04 -0400469// WithOsClass adds osClass(es) that this rule applies to.
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100470func (r *rule) WithOsClass(osClasses ...OsClass) Rule {
471 r.osClasses = append(r.osClasses, osClasses...)
472 return r
473}
474
Liz Kammera3d79152021-10-28 18:14:04 -0400475// ModuleType adds type(s) that this rule applies to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100476func (r *rule) ModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800477 r.moduleTypes = append(r.moduleTypes, types...)
478 return r
479}
480
Liz Kammera3d79152021-10-28 18:14:04 -0400481// NotModuleType adds type(s) that this rule does not apply to..
Paul Duffin730f2a52019-06-27 14:08:51 +0100482func (r *rule) NotModuleType(types ...string) Rule {
Colin Crossfd4f7432019-03-05 15:06:16 -0800483 r.unlessModuleTypes = append(r.unlessModuleTypes, types...)
484 return r
485}
486
Liz Kammera3d79152021-10-28 18:14:04 -0400487// With specifies property/value combinations that are restricted for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100488func (r *rule) With(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100489 return r.WithMatcher(properties, selectMatcher(value))
490}
491
Liz Kammera3d79152021-10-28 18:14:04 -0400492// WithMatcher specifies property/matcher combinations that are restricted for this rule.
Paul Duffinc8111702019-07-22 12:13:55 +0100493func (r *rule) WithMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800494 r.props = append(r.props, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100495 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100496 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800497 })
498 return r
499}
Colin Crossfd4f7432019-03-05 15:06:16 -0800500
Liz Kammera3d79152021-10-28 18:14:04 -0400501// Without specifies property/value combinations that this rule does not apply to.
Paul Duffin730f2a52019-06-27 14:08:51 +0100502func (r *rule) Without(properties, value string) Rule {
Paul Duffinc8111702019-07-22 12:13:55 +0100503 return r.WithoutMatcher(properties, selectMatcher(value))
504}
505
Liz Kammera3d79152021-10-28 18:14:04 -0400506// Without specifies property/matcher combinations that this rule does not apply to.
Paul Duffinc8111702019-07-22 12:13:55 +0100507func (r *rule) WithoutMatcher(properties string, matcher ValueMatcher) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800508 r.unlessProps = append(r.unlessProps, ruleProperty{
Paul Duffin73bf0542019-07-12 14:12:49 +0100509 fields: fieldNamesForProperties(properties),
Paul Duffinc8111702019-07-22 12:13:55 +0100510 matcher: matcher,
Steven Moreland65b3fd92017-12-06 14:18:35 -0800511 })
512 return r
513}
Colin Crossfd4f7432019-03-05 15:06:16 -0800514
Paul Duffin73bf0542019-07-12 14:12:49 +0100515func selectMatcher(expected string) ValueMatcher {
516 if expected == "*" {
517 return anyMatcherInstance
518 }
519 return &equalMatcher{expected: expected}
520}
521
Liz Kammera3d79152021-10-28 18:14:04 -0400522// Because specifies a reason for this rule.
Paul Duffin730f2a52019-06-27 14:08:51 +0100523func (r *rule) Because(reason string) Rule {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800524 r.reason = reason
525 return r
526}
527
528func (r *rule) String() string {
Liz Kammera3d79152021-10-28 18:14:04 -0400529 s := []string{"neverallow requirements. Not allowed:"}
530 if len(r.paths) > 0 {
531 s = append(s, fmt.Sprintf("in dirs: %q", r.paths))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800532 }
Liz Kammera3d79152021-10-28 18:14:04 -0400533 if len(r.moduleTypes) > 0 {
534 s = append(s, fmt.Sprintf("module types: %q", r.moduleTypes))
Steven Moreland65b3fd92017-12-06 14:18:35 -0800535 }
Liz Kammera3d79152021-10-28 18:14:04 -0400536 if len(r.props) > 0 {
537 s = append(s, fmt.Sprintf("properties matching: %s", r.props))
Colin Crossfd4f7432019-03-05 15:06:16 -0800538 }
Liz Kammera3d79152021-10-28 18:14:04 -0400539 if len(r.directDeps) > 0 {
540 s = append(s, fmt.Sprintf("dep(s): %q", SortedStringKeys(r.directDeps)))
Colin Crossfd4f7432019-03-05 15:06:16 -0800541 }
Liz Kammera3d79152021-10-28 18:14:04 -0400542 if len(r.osClasses) > 0 {
543 s = append(s, fmt.Sprintf("os class(es): %q", r.osClasses))
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100544 }
Liz Kammera3d79152021-10-28 18:14:04 -0400545 if len(r.unlessPaths) > 0 {
546 s = append(s, fmt.Sprintf("EXCEPT in dirs: %q", r.unlessPaths))
547 }
548 if len(r.unlessModuleTypes) > 0 {
549 s = append(s, fmt.Sprintf("EXCEPT module types: %q", r.unlessModuleTypes))
550 }
551 if len(r.unlessProps) > 0 {
552 s = append(s, fmt.Sprintf("EXCEPT properties matching: %q", r.unlessProps))
Andrei Onea115e7e72020-06-05 21:14:03 +0100553 }
Steven Moreland65b3fd92017-12-06 14:18:35 -0800554 if len(r.reason) != 0 {
Liz Kammera3d79152021-10-28 18:14:04 -0400555 s = append(s, " which is restricted because "+r.reason)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800556 }
Liz Kammera3d79152021-10-28 18:14:04 -0400557 if len(s) == 1 {
558 s[0] = "neverallow requirements (empty)"
559 }
560 return strings.Join(s, "\n\t")
Steven Moreland65b3fd92017-12-06 14:18:35 -0800561}
562
563func (r *rule) appliesToPath(dir string) bool {
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800564 includePath := len(r.paths) == 0 || HasAnyPrefix(dir, r.paths)
565 excludePath := HasAnyPrefix(dir, r.unlessPaths)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800566 return includePath && !excludePath
567}
568
Paul Duffin35781882019-07-25 15:41:09 +0100569func (r *rule) appliesToDirectDeps(ctx BottomUpMutatorContext) bool {
570 if len(r.directDeps) == 0 {
571 return true
572 }
573
574 matches := false
575 ctx.VisitDirectDeps(func(m Module) {
576 if !matches {
577 name := ctx.OtherModuleName(m)
578 matches = r.directDeps[name]
579 }
580 })
581
582 return matches
583}
584
Paul Duffinf1c9bbe2019-07-26 10:48:06 +0100585func (r *rule) appliesToOsClass(osClass OsClass) bool {
586 if len(r.osClasses) == 0 {
587 return true
588 }
589
590 for _, c := range r.osClasses {
591 if c == osClass {
592 return true
593 }
594 }
595
596 return false
597}
598
Colin Crossfd4f7432019-03-05 15:06:16 -0800599func (r *rule) appliesToModuleType(moduleType string) bool {
600 return (len(r.moduleTypes) == 0 || InList(moduleType, r.moduleTypes)) && !InList(moduleType, r.unlessModuleTypes)
601}
602
Anton Hanssone1b18362021-12-23 15:05:38 +0000603func (r *rule) appliesToProperties(properties []interface{}) bool {
604 includeProps := hasAllProperties(properties, r.props)
605 excludeProps := hasAnyProperty(properties, r.unlessProps)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800606 return includeProps && !excludeProps
607}
608
Paul Duffinc8111702019-07-22 12:13:55 +0100609func StartsWith(prefix string) ValueMatcher {
610 return &startsWithMatcher{prefix}
611}
612
Anton Hansson45376402020-04-09 14:18:21 +0100613func Regexp(re string) ValueMatcher {
614 r, err := regexp.Compile(re)
615 if err != nil {
616 panic(err)
617 }
618 return &regexMatcher{r}
619}
620
Andrei Onea115e7e72020-06-05 21:14:03 +0100621func NotInList(allowed []string) ValueMatcher {
622 return &notInListMatcher{allowed}
623}
624
Steven Moreland65b3fd92017-12-06 14:18:35 -0800625// assorted utils
626
627func cleanPaths(paths []string) []string {
628 res := make([]string, len(paths))
629 for i, v := range paths {
630 res[i] = filepath.Clean(v) + "/"
631 }
632 return res
633}
634
635func fieldNamesForProperties(propertyNames string) []string {
636 names := strings.Split(propertyNames, ".")
637 for i, v := range names {
638 names[i] = proptools.FieldNameForProperty(v)
639 }
640 return names
641}
642
Anton Hanssone1b18362021-12-23 15:05:38 +0000643func hasAnyProperty(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 true
647 }
648 }
649 return false
650}
651
Anton Hanssone1b18362021-12-23 15:05:38 +0000652func hasAllProperties(properties []interface{}, props []ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800653 for _, v := range props {
Anton Hanssone1b18362021-12-23 15:05:38 +0000654 if !hasProperty(properties, v) {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800655 return false
656 }
657 }
658 return true
659}
660
Anton Hanssone1b18362021-12-23 15:05:38 +0000661func hasProperty(properties []interface{}, prop ruleProperty) bool {
Steven Moreland65b3fd92017-12-06 14:18:35 -0800662 for _, propertyStruct := range properties {
663 propertiesValue := reflect.ValueOf(propertyStruct).Elem()
664 for _, v := range prop.fields {
665 if !propertiesValue.IsValid() {
666 break
667 }
668 propertiesValue = propertiesValue.FieldByName(v)
669 }
670 if !propertiesValue.IsValid() {
671 continue
672 }
673
Paul Duffin73bf0542019-07-12 14:12:49 +0100674 check := func(value string) bool {
Anton Hanssone1b18362021-12-23 15:05:38 +0000675 return prop.matcher.Test(value)
Steven Moreland65b3fd92017-12-06 14:18:35 -0800676 }
677
678 if matchValue(propertiesValue, check) {
679 return true
680 }
681 }
682 return false
683}
684
685func matchValue(value reflect.Value, check func(string) bool) bool {
686 if !value.IsValid() {
687 return false
688 }
689
690 if value.Kind() == reflect.Ptr {
691 if value.IsNil() {
692 return check("")
693 }
694 value = value.Elem()
695 }
696
697 switch value.Kind() {
698 case reflect.String:
699 return check(value.String())
700 case reflect.Bool:
701 return check(strconv.FormatBool(value.Bool()))
702 case reflect.Int:
703 return check(strconv.FormatInt(value.Int(), 10))
704 case reflect.Slice:
705 slice, ok := value.Interface().([]string)
706 if !ok {
707 panic("Can only handle slice of string")
708 }
709 for _, v := range slice {
710 if check(v) {
711 return true
712 }
713 }
714 return false
715 }
716
717 panic("Can't handle type: " + value.Kind().String())
718}
Paul Duffin115445b2019-08-07 15:31:07 +0100719
720var neverallowRulesKey = NewOnceKey("neverallowRules")
721
722func neverallowRules(config Config) []Rule {
723 return config.Once(neverallowRulesKey, func() interface{} {
724 // No test rules were set by setTestNeverallowRules, use the global rules
725 return neverallows
726 }).([]Rule)
727}
728
729// Overrides the default neverallow rules for the supplied config.
730//
731// For testing only.
Paul Duffin45338f02021-03-30 23:07:52 +0100732func setTestNeverallowRules(config Config, testRules []Rule) {
Paul Duffin115445b2019-08-07 15:31:07 +0100733 config.Once(neverallowRulesKey, func() interface{} { return testRules })
734}
Paul Duffin45338f02021-03-30 23:07:52 +0100735
736// Prepares for a test by setting neverallow rules and enabling the mutator.
737//
738// If the supplied rules are nil then the default rules are used.
739func PrepareForTestWithNeverallowRules(testRules []Rule) FixturePreparer {
740 return GroupFixturePreparers(
741 FixtureModifyConfig(func(config Config) {
742 if testRules != nil {
743 setTestNeverallowRules(config, testRules)
744 }
745 }),
746 FixtureRegisterWithContext(func(ctx RegistrationContext) {
747 ctx.PostDepsMutators(registerNeverallowMutator)
748 }),
749 )
750}