1 /*
<lambda>null2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.libraries.pcc.chronicle.api.policy
18 
19 import com.android.libraries.pcc.chronicle.api.error.MalformedPolicySet
20 
21 /**
22  * Applies the following conformance rules to the set of [Policies][Policy] passed to it:
23  *
24  * 1. All [Policies][Policy] must have non-empty [Policy.description] values.
25  * 1. All [PolicyTargets][PolicyTarget] must contain at least one [PolicyRetention] value.
26  */
27 class DefaultPolicyConformanceCheck : PolicyConformanceCheck {
28   override fun checkPoliciesConform(policies: Set<Policy>) {
29     val issues =
30       policies.flatMap { ensureDescriptionExists(it) + ensureTargetsSpecifyRetentionRules(it) }
31 
32     if (issues.isNotEmpty()) {
33       throw MalformedPolicySet(issues.joinToString(", ", prefix = "Malformed policies found: "))
34     }
35   }
36 
37   private fun ensureDescriptionExists(policy: Policy): List<String> {
38     if (policy.description.isNotBlank()) return emptyList()
39     return listOf("Policy: \"${policy.name}\" has an empty description")
40   }
41 
42   private fun ensureTargetsSpecifyRetentionRules(policy: Policy): List<String> {
43     return policy.targets.mapNotNull { target ->
44       if (target.retentions.isNotEmpty()) return@mapNotNull null
45 
46       "Target \"${target.schemaName}\" from policy: \"${policy.name}\" does not specify " +
47         "any retention rules"
48     }
49   }
50 }
51