|
| 1 | +/* |
| 2 | + * Copyright (c) 2014-2025 Stream.io Inc. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Stream 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 | + * https://github.com/GetStream/stream-core-android/blob/main/LICENSE |
| 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 | +package io.getstream.android.core.lint.detectors |
| 17 | + |
| 18 | +import com.android.tools.lint.client.api.UElementHandler |
| 19 | +import com.android.tools.lint.detector.api.* |
| 20 | +import org.jetbrains.kotlin.lexer.KtTokens |
| 21 | +import org.jetbrains.kotlin.psi.* |
| 22 | +import org.jetbrains.uast.* |
| 23 | + |
| 24 | +class StreamApiExplicitMarkerDetector : Detector(), Detector.UastScanner { |
| 25 | + |
| 26 | + override fun getApplicableUastTypes() = |
| 27 | + listOf(UClass::class.java, UMethod::class.java, UField::class.java, UFile::class.java) |
| 28 | + |
| 29 | + override fun createUastHandler(context: JavaContext) = |
| 30 | + object : UElementHandler() { |
| 31 | + override fun visitClass(node: UClass) { |
| 32 | + val uFile = node.getContainingUFileOrNull() ?: return |
| 33 | + if (!context.packageMatchesConfig(uFile.packageName)) return |
| 34 | + checkUAnnotated(context, node, node.sourcePsi as? KtDeclaration) |
| 35 | + } |
| 36 | + |
| 37 | + override fun visitMethod(node: UMethod) { |
| 38 | + val uFile = node.getContainingUFileOrNull() ?: return |
| 39 | + if (!context.packageMatchesConfig(uFile.packageName)) return |
| 40 | + checkUAnnotated(context, node, node.sourcePsi as? KtNamedFunction) |
| 41 | + } |
| 42 | + |
| 43 | + override fun visitField(node: UField) { |
| 44 | + val uFile = node.getContainingUFileOrNull() ?: return |
| 45 | + if (!context.packageMatchesConfig(uFile.packageName)) return |
| 46 | + checkUAnnotated(context, node, node.sourcePsi as? KtProperty) |
| 47 | + } |
| 48 | + |
| 49 | + override fun visitFile(node: UFile) { |
| 50 | + val ktFile = node.sourcePsi as? KtFile ?: return |
| 51 | + val pkg = ktFile.packageFqName.asString() |
| 52 | + if (!context.packageMatchesConfig(pkg)) return |
| 53 | + ktFile.declarations.filterIsInstance<KtTypeAlias>().forEach { alias -> |
| 54 | + checkTypeAlias(context, alias) |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private fun checkUAnnotated(context: JavaContext, u: UElement, kt: KtDeclaration?) { |
| 60 | + kt ?: return |
| 61 | + if (!kt.isTopLevelPublic()) return |
| 62 | + val annotated = (u as? UAnnotated)?.hasAnyAnnotation(MARKERS) ?: false |
| 63 | + if (annotated) return |
| 64 | + reportWithDualFix(context, u, kt) |
| 65 | + } |
| 66 | + |
| 67 | + private fun checkTypeAlias(context: JavaContext, alias: KtTypeAlias) { |
| 68 | + if (!alias.isTopLevelPublic()) return |
| 69 | + val annotated = alias.hasAnyAnnotationPsi(MARKERS_SIMPLE) |
| 70 | + if (annotated) return |
| 71 | + reportWithDualFix(context, alias, alias) |
| 72 | + } |
| 73 | + |
| 74 | + private fun reportWithDualFix(context: JavaContext, node: KtTypeAlias, decl: KtDeclaration) { |
| 75 | + val loc = context.getLocation(decl) |
| 76 | + val fixPublished = |
| 77 | + LintFix.create() |
| 78 | + .name("Annotate with @$PUBLISHED_SIMPLE") |
| 79 | + .replace() |
| 80 | + .range(loc) |
| 81 | + .pattern("^") |
| 82 | + .with("@$PUBLISHED_FQ\n") |
| 83 | + .reformat(true) |
| 84 | + .shortenNames() |
| 85 | + .autoFix() |
| 86 | + .build() |
| 87 | + val fixInternal = |
| 88 | + LintFix.create() |
| 89 | + .name("Annotate with @$INTERNAL_SIMPLE") |
| 90 | + .replace() |
| 91 | + .range(loc) |
| 92 | + .pattern("^") |
| 93 | + .with("@$INTERNAL_FQ\n") |
| 94 | + .reformat(true) |
| 95 | + .shortenNames() |
| 96 | + .autoFix() |
| 97 | + .build() |
| 98 | + |
| 99 | + context.report( |
| 100 | + ISSUE, |
| 101 | + node, |
| 102 | + loc, |
| 103 | + "Public API must be explicitly marked with @$PUBLISHED_SIMPLE or @$INTERNAL_SIMPLE.", |
| 104 | + LintFix.create().group(fixPublished, fixInternal), |
| 105 | + ) |
| 106 | + } |
| 107 | + |
| 108 | + private fun reportWithDualFix(context: JavaContext, node: UElement, decl: KtDeclaration) { |
| 109 | + val loc = context.getLocation(decl) |
| 110 | + val fixPublished = |
| 111 | + LintFix.create() |
| 112 | + .name("Annotate with @$PUBLISHED_SIMPLE") |
| 113 | + .replace() |
| 114 | + .range(loc) |
| 115 | + .pattern("^") |
| 116 | + .with("@$PUBLISHED_FQ\n") |
| 117 | + .reformat(true) |
| 118 | + .shortenNames() |
| 119 | + .autoFix() |
| 120 | + .build() |
| 121 | + val fixInternal = |
| 122 | + LintFix.create() |
| 123 | + .name("Annotate with @$INTERNAL_SIMPLE") |
| 124 | + .replace() |
| 125 | + .range(loc) |
| 126 | + .pattern("^") |
| 127 | + .with("@$INTERNAL_FQ\n") |
| 128 | + .reformat(true) |
| 129 | + .shortenNames() |
| 130 | + .autoFix() |
| 131 | + .build() |
| 132 | + |
| 133 | + context.report( |
| 134 | + ISSUE, |
| 135 | + node, |
| 136 | + loc, |
| 137 | + "Public API must be explicitly marked with @$PUBLISHED_SIMPLE or @$INTERNAL_SIMPLE.", |
| 138 | + LintFix.create().group(fixPublished, fixInternal), |
| 139 | + ) |
| 140 | + } |
| 141 | + |
| 142 | + // ----- package filtering helpers ----- |
| 143 | + |
| 144 | + private fun JavaContext.packageMatchesConfig(pkg: String): Boolean { |
| 145 | + val patterns = configuredPackageGlobs() |
| 146 | + |
| 147 | + // Default if not configured → only io.getstream.android.core.* |
| 148 | + val effectivePatterns = patterns.ifEmpty { listOf("io.getstream.android.core.api") } |
| 149 | + |
| 150 | + val included = effectivePatterns.any { pkgMatchesGlob(pkg, it) } |
| 151 | + val excluded = packageMatchesExcludeConfig(pkg) |
| 152 | + return included && !excluded |
| 153 | + } |
| 154 | + |
| 155 | + private fun JavaContext.packageMatchesExcludeConfig(pkg: String): Boolean { |
| 156 | + val raw = configuration.getOption(ISSUE, OPTION_PACKAGES_EXCLUDE.name, "")?.trim().orEmpty() |
| 157 | + if (raw.isEmpty()) return false |
| 158 | + val patterns = raw.split(',').map { it.trim() }.filter { it.isNotEmpty() } |
| 159 | + return patterns.any { pkgMatchesGlob(pkg, it) } |
| 160 | + } |
| 161 | + |
| 162 | + private fun JavaContext.configuredPackageGlobs(): List<String> { |
| 163 | + val raw = configuration.getOption(ISSUE, OPTION_PACKAGES.name, "")?.trim().orEmpty() |
| 164 | + if (raw.isEmpty()) return emptyList() |
| 165 | + return raw.split(',').map { it.trim() }.filter { it.isNotEmpty() } |
| 166 | + } |
| 167 | + |
| 168 | + /** Simple glob matcher: `*` → `.*`, `?` → `.`, dot escaped; anchored. */ |
| 169 | + private fun pkgMatchesGlob(pkg: String, glob: String): Boolean = globToRegex(glob).matches(pkg) |
| 170 | + |
| 171 | + private fun globToRegex(glob: String): Regex { |
| 172 | + val sb = StringBuilder("^") |
| 173 | + for (ch in glob) { |
| 174 | + when (ch) { |
| 175 | + '*' -> sb.append(".*") |
| 176 | + '?' -> sb.append('.') |
| 177 | + '.' -> sb.append("\\.") |
| 178 | + else -> sb.append(Regex.escape(ch.toString())) |
| 179 | + } |
| 180 | + } |
| 181 | + sb.append('$') |
| 182 | + return sb.toString().toRegex() |
| 183 | + } |
| 184 | + |
| 185 | + // ----- misc helpers ----- |
| 186 | + |
| 187 | + private fun UAnnotated.hasAnyAnnotation(qns: Set<String>) = |
| 188 | + qns.any { findAnnotation(it) != null || findAnnotation(it.substringAfterLast('.')) != null } |
| 189 | + |
| 190 | + private fun KtAnnotated.hasAnyAnnotationPsi(simpleNames: Set<String>): Boolean = |
| 191 | + annotationEntries.any { entry -> |
| 192 | + entry.shortName?.asString() in simpleNames || |
| 193 | + entry.typeReference?.text in simpleNames // handles rare fully-qualified usage |
| 194 | + } |
| 195 | + |
| 196 | + private fun UElement.getContainingUFileOrNull(): UFile? { |
| 197 | + var cur: UElement? = this |
| 198 | + while (cur != null) { |
| 199 | + if (cur is UFile) return cur |
| 200 | + cur = cur.uastParent |
| 201 | + } |
| 202 | + return null |
| 203 | + } |
| 204 | + |
| 205 | + private fun KtDeclaration.isTopLevelPublic(): Boolean { |
| 206 | + if (parent !is KtFile) return false |
| 207 | + val mods = modifierList |
| 208 | + val isPublic = |
| 209 | + mods?.hasModifier(KtTokens.PUBLIC_KEYWORD) == true || |
| 210 | + !(mods?.hasModifier(KtTokens.PRIVATE_KEYWORD) == true || |
| 211 | + mods?.hasModifier(KtTokens.PROTECTED_KEYWORD) == true || |
| 212 | + mods?.hasModifier(KtTokens.INTERNAL_KEYWORD) == true) |
| 213 | + return isPublic |
| 214 | + } |
| 215 | + |
| 216 | + companion object { |
| 217 | + private const val PUBLISHED_FQ = "io.getstream.android.core.annotations.StreamPublishedApi" |
| 218 | + private const val PUBLISHED_SIMPLE = "StreamPublishedApi" |
| 219 | + private const val INTERNAL_FQ = "io.getstream.android.core.annotations.StreamInternalApi" |
| 220 | + private const val INTERNAL_SIMPLE = "StreamInternalApi" |
| 221 | + private val MARKERS = setOf(PUBLISHED_FQ, INTERNAL_FQ) |
| 222 | + private val MARKERS_SIMPLE = setOf(PUBLISHED_SIMPLE, INTERNAL_SIMPLE) |
| 223 | + |
| 224 | + private val OPTION_PACKAGES = |
| 225 | + StringOption( |
| 226 | + name = "packages", |
| 227 | + description = "Comma-separated package **glob** patterns where the rule applies.", |
| 228 | + explanation = |
| 229 | + """ |
| 230 | + Supports wildcards: '*' (any sequence) and '?' (single char). |
| 231 | + Examples: |
| 232 | + - 'io.getstream.android.core.api' |
| 233 | + - 'io.getstream.android.core.*.api' |
| 234 | + - 'io.getstream.android.*' |
| 235 | + """ |
| 236 | + .trimIndent(), |
| 237 | + ) |
| 238 | + |
| 239 | + private val OPTION_PACKAGES_EXCLUDE = |
| 240 | + StringOption( |
| 241 | + name = "exclude_packages", |
| 242 | + description = "Comma-separated package **glob** patterns to exclude from the rule.", |
| 243 | + explanation = |
| 244 | + """ |
| 245 | + Same glob syntax as 'packages'. Evaluated after includes. |
| 246 | + """ |
| 247 | + .trimIndent(), |
| 248 | + ) |
| 249 | + |
| 250 | + private val IMPLEMENTATION = |
| 251 | + Implementation(StreamApiExplicitMarkerDetector::class.java, Scope.JAVA_FILE_SCOPE) |
| 252 | + |
| 253 | + @JvmField |
| 254 | + val ISSUE: Issue = |
| 255 | + Issue.create( |
| 256 | + "StreamApiExplicitMarkerMissing", |
| 257 | + "Public API must be explicitly marked", |
| 258 | + """ |
| 259 | + To prevent accidental exposure, all top-level public declarations must be explicitly \ |
| 260 | + marked as @StreamPublishedApi (allowed to leak) or @StreamInternalApi (not allowed to leak). |
| 261 | + """ |
| 262 | + .trimIndent(), |
| 263 | + Category.CORRECTNESS, |
| 264 | + 7, |
| 265 | + Severity.ERROR, |
| 266 | + IMPLEMENTATION, |
| 267 | + ) |
| 268 | + .setOptions(listOf(OPTION_PACKAGES, OPTION_PACKAGES_EXCLUDE)) |
| 269 | + } |
| 270 | +} |
0 commit comments