greenlight/internal/cli/playscan.go
ethan zhou 7223ea2c4a
feat(playscan): scan Android projects against Google Play policies (#17)
* feat(playscan): scan Android projects against Google Play policies

Adds a Google Play tier alongside the existing App Store checks. Android
projects are detected automatically, including the android/ directory of an
Expo or React Native app, so a cross-platform repo is checked against both
stores in one pass. Also available standalone as `greenlight playscan`.

Deadline checks, both landing 2026-08-31:
- Target API level: CRITICAL below API 35, HIGH below 36, with a live
  day countdown
- Play Billing Library 7 and below, which has no direct v7 to v9 path

Policy checks:
- Restricted permissions: SMS and Call Log (including the 2026-07-15 change
  dropping phone-call account verification), All files access,
  QUERY_ALL_PACKAGES, REQUEST_INSTALL_PACKAGES, background location, broad
  photo/video access, accessibility service, overlays, device admin, usage
  stats, contacts
- Foreground service types missing their FOREGROUND_SERVICE_* permission,
  which throws at startForeground() on Android 14+
- android:exported missing on components with an intent filter, debuggable,
  cleartext traffic
- Ads SDK without the AD_ID permission, which silently zeroes the ad ID
- Account creation without both in-app and web deletion paths

Every finding carries a Doc link to the policy page it comes from. Play
policies are named rather than numbered and change often, so the citation is
worth more than a section reference.

The Apple scanners now skip only when a project is unambiguously
Android-only. Previously every pure-Android repo led with a CRITICAL for a
missing PrivacyInfo.xcprivacy, an iOS-only requirement. iOS-only and
cross-platform projects are unaffected.

targetSdk is resolved from the app module, convention plugins, version
catalogs, gradle.properties, and named constants, since most real projects
reach it through a reference rather than a literal. lint.targetSdk and
testOptions.targetSdk are explicitly excluded. When it cannot be resolved the
scan says so rather than reporting a pass.

Scope is documented in the README and command help: this reads the pre-merge
manifest, so permissions contributed by library manifests are not visible
until the build merges them.

Validated against nowinandroid, AnkiDroid, Thunderbird, Pocket Casts,
DuckDuckGo, and Mattermost, with every finding checked against source.

* feat(playscan): scan built APKs and AABs, with 16 KB page size checks

Adds `greenlight playscan --apk` / `--aab`, closing the gap the source scan
documents: a repo's AndroidManifest.xml is the pre-merge manifest, so
permissions contributed by library manifests are invisible until build time.
A built artifact carries the merged manifest, so its permission list is
complete.

Every existing policy rule runs unchanged against the decoded manifest. The
archive scan adds the native code checks, which only exist at this layer:

- 16 KB page size: ELF LOAD segment alignment on arm64-v8a, 16 KB zip
  alignment of uncompressed libraries, and GNU_RELRO presence. Google Play
  requires apps targeting Android 15+ to support 16 KB memory pages; an
  unaligned library fails to load and crashes at startup on those devices.

Both container formats are decoded in pure Go with no new dependencies, so no
Android SDK, aapt2, or bundletool is required:

- APK: Android binary XML, including the string pool in both UTF-8 and UTF-16
  form and the resource ID map. aapt2 emits an empty string-pool entry for
  framework attributes and identifies them only by resource ID, so without the
  map every android:* attribute reads as unnamed.
- AAB: the protobuf-encoded manifest, walked directly off the wire format.

foregroundServiceType is a bitmask once compiled; it is rendered back to the
pipe-separated names the source manifest uses so the foreground service rule
needs no second code path.

Only arm64-v8a is assessed for 16 KB alignment. 16 KB page size devices are
64-bit ARM, so flagging a 32-bit library at 4 KB would be noise.

Verified against real APKs. Termux 0.118.3 decodes to exactly the 15
permissions in its published source manifest, and its 4 KB aligned libraries
are flagged; F-Droid's 16 KB aligned library is not. Alignment findings were
cross-checked by parsing the ELF program headers independently.

* fix(playscan): address code review findings

Two denial-of-service bugs in the binary parsers, both reachable through the
stated threat model of scanning an archive someone handed you, and both
reproduced before and after the fix:

- protoxml: the decoder recursed once per manifest nesting level with no
  bound. A deeply nested AAB drove a Go stack overflow, which is a process
  abort recover() cannot catch. An 8.9 MB file was enough. Now capped at 100
  levels, matching Android's own parser; the repro drops to 0.35s / 22 MB and
  reports an undecodable manifest.
- axml: attrCount is a uint16 read straight from the file and need not match
  the bytes present, but it was used directly to size an allocation. A 97 KB
  APK of 36-byte chunks each claiming 65535 attributes cost 65s CPU and
  1.46 GB RSS. Capped by the chunk's actual capacity; the repro drops to
  0.04s / 110 MB.

Correctness:

- protoxml decoded compiled values against a guessed schema. Primitive's oneof
  is non-contiguous in Resources.proto (float=3, int_decimal=6, int_hex=7,
  boolean=8), and the code treated field 3 as the boolean, so every compiled
  boolean in a bundle was misread and an AAB's debuggable=true was missed
  entirely. Now decodes Item.str and Item.prim against the real field numbers.
- The BIND_* permissions are never requested via <uses-permission>; the
  framework requires them as the bound component's android:permission. Those
  rules could therefore never fire. Component permissions are now inspected,
  and BIND_VPN_SERVICE is covered alongside accessibility and device admin.
- Every foreground service needs the base FOREGROUND_SERVICE permission from
  API 28 regardless of type. Only the type-specific permissions were checked,
  so an app missing the base one was reported clean.
- Gradle file ranking assumed the app module is named "app", the same
  assumption already fixed for manifest selection. Ranking is now tied to the
  module the selected manifest belongs to, so a library module's targetSdk
  cannot be reported as the app's.
- The Billing Library version had to be a literal, but most builds reach it
  through a variable or a version catalog version.ref, so the support-window
  check silently never fired on them. Both forms now resolve. This surfaces a
  real finding on Thunderbird, which ships Billing 7.1.1 via version.ref.
- detectIOS missed Objective-C sources and app.config.json, either of which
  could classify a cross-platform repo as Android-only and skip the Apple
  scanners.

Also drops GradleInfo.CompileSDK and .Dependencies, which were written or
declared but never read, and serializes an empty findings list as [] rather
than null.

---------

Co-authored-by: ethan zhou <231755529+ethanzhoucool@users.noreply.github.com>
2026-07-27 16:47:29 -07:00

280 lines
8.4 KiB
Go

package cli
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/RevylAI/greenlight/internal/playscan"
"github.com/fatih/color"
"github.com/spf13/cobra"
)
var (
playscanFormat string
playscanOutput string
playscanExitCode bool
playscanArchive string
)
var playscanCmd = &cobra.Command{
Use: "playscan [path]",
Short: "Scan an Android project against Google Play's policies",
Long: `Check an Android app against Google Play's Developer Program Policies
and its published distribution deadlines, before you upload.
Checks:
• Target API level — the annual requirement that silently pulls apps
from distribution when missed
• Play Billing Library — versions past their support window
• Restricted permissions — SMS, Call Log, All files access, QUERY_ALL_PACKAGES,
background location, broad photo/video access
• Foreground services — service types missing their required permission
• Manifest requirements — android:exported, debuggable, cleartext traffic
• Advertising ID — ads SDK shipped without the AD_ID permission
• Account deletion — the in-app and web deletion requirement
Pass --apk or --aab to scan a BUILT artifact instead of source. That reads the
merged manifest, so it sees permissions contributed by library manifests that a
source scan structurally cannot, and adds the native code checks:
• 16 KB page size — ELF LOAD alignment, zip alignment, GNU_RELRO
Runs entirely offline. No Play Console account needed.
Scope: scanning source reads the AndroidManifest.xml and Gradle files in your
repo, which is the pre-merge manifest. Permissions contributed by library
manifests only appear after the build merges them, so a clean source scan is
not proof of a clean merged manifest. Scan the built artifact to close that gap.
Usage:
greenlight playscan .
greenlight playscan --apk app-release.apk
greenlight playscan --aab app-release.aab
greenlight playscan ./android --format json
greenlight playscan . --exit-code`,
Args: cobra.MaximumNArgs(1),
RunE: runPlayscan,
}
func init() {
playscanCmd.Flags().StringVar(&playscanFormat, "format", "terminal", "output format: terminal, json")
playscanCmd.Flags().StringVar(&playscanOutput, "output", "", "write report to file (stdout if omitted)")
playscanCmd.Flags().BoolVar(&playscanExitCode, "exit-code", false, "exit non-zero on any CRITICAL or HIGH finding — for CI gating")
playscanCmd.Flags().StringVar(&playscanArchive, "apk", "", "scan a built .apk (merged manifest + native code checks) instead of source")
playscanCmd.Flags().StringVar(&playscanArchive, "aab", "", "scan a built .aab (merged manifest + native code checks) instead of source")
rootCmd.AddCommand(playscanCmd)
}
func runPlayscan(cmd *cobra.Command, args []string) error {
path := "."
if len(args) > 0 {
path = args[0]
}
// --apk / --aab share one variable: they select the same archive scan and
// the format is detected from the file, so passing the wrong one is not an
// error the user needs to care about.
archive := playscanArchive
if archive != "" {
if info, err := os.Stat(archive); err != nil {
return fmt.Errorf("cannot access archive: %w", err)
} else if info.IsDir() {
return fmt.Errorf("--apk/--aab expects a file, not a directory: %s", archive)
}
} else {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("cannot access path: %w", err)
}
if !info.IsDir() {
return fmt.Errorf("path must be a directory: %s", path)
}
}
isJSON := strings.ToLower(playscanFormat) == "json"
if !isJSON {
purple.Println("\n greenlight playscan — know before you upload to Google Play.")
if archive != "" {
fmt.Printf(" Archive: %s\n\n", archive)
} else {
fmt.Printf(" Project: %s\n\n", path)
}
}
start := time.Now()
var result *playscan.ScanResult
var err error
if archive != "" {
result, err = playscan.ScanArchive(archive)
} else {
result, err = playscan.Scan(path)
}
if err != nil {
return fmt.Errorf("play scan failed: %w", err)
}
elapsed := time.Since(start)
out := os.Stdout
if playscanOutput != "" {
out, err = os.Create(playscanOutput)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer out.Close()
}
if isJSON {
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
if err := enc.Encode(result); err != nil {
return err
}
} else {
printPlayscanReport(out, result, elapsed)
}
if playscanExitCode {
for _, f := range result.Findings {
if f.Severity == "CRITICAL" || f.Severity == "HIGH" {
return ErrThreshold
}
}
}
return nil
}
func printPlayscanReport(w *os.File, result *playscan.ScanResult, elapsed time.Duration) {
red := color.New(color.FgRed, color.Bold)
hiYellow := color.New(color.FgHiYellow, color.Bold)
yellow := color.New(color.FgYellow)
green := color.New(color.FgGreen, color.Bold)
greenC := color.New(color.FgGreen)
bold := color.New(color.Bold)
if result.ManifestPath == "" && result.TargetSDK == 0 {
dim.Fprintln(w, " No Android project found at this path.")
dim.Fprintln(w, " Looked for AndroidManifest.xml and Gradle build files.")
fmt.Fprintln(w)
return
}
// Project context
if result.ArchiveKind != "" {
fmt.Fprintf(w, " Format: %s (merged manifest)\n", result.ArchiveKind)
}
if result.PackageName != "" {
fmt.Fprintf(w, " Package: %s\n", result.PackageName)
}
if result.TargetSDK > 0 {
fmt.Fprintf(w, " targetSdk: %d\n", result.TargetSDK)
}
if result.ManifestPath != "" {
fmt.Fprintf(w, " Manifest: %s\n", result.ManifestPath)
}
if result.IsArchive {
fmt.Fprintf(w, " Native libs: %d\n", result.NativeLibCount)
}
fmt.Fprintln(w)
// Sort by severity, then policy, so the output is stable run to run.
sevRank := map[string]int{"CRITICAL": 4, "HIGH": 3, "WARN": 2, "INFO": 1}
findings := append([]playscan.Finding{}, result.Findings...)
sort.SliceStable(findings, func(i, j int) bool {
if ri, rj := sevRank[findings[i].Severity], sevRank[findings[j].Severity]; ri != rj {
return ri > rj
}
return findings[i].Policy < findings[j].Policy
})
var criticals, highs, warns, infos int
for _, f := range findings {
switch f.Severity {
case "CRITICAL":
criticals++
case "HIGH":
highs++
case "WARN":
warns++
case "INFO":
infos++
}
}
lastSeverity := ""
for _, f := range findings {
if f.Severity != lastSeverity {
switch f.Severity {
case "CRITICAL":
red.Fprintln(w, " CRITICAL — Will be rejected or already losing distribution")
case "HIGH":
hiYellow.Fprintln(w, " HIGH — Likely rejection")
case "WARN":
yellow.Fprintln(w, " WARNING — Worth fixing")
case "INFO":
dim.Fprintln(w, " INFO — Best practices")
}
fmt.Fprintln(w)
lastSeverity = f.Severity
}
switch f.Severity {
case "CRITICAL":
red.Fprintf(w, " [CRITICAL] ")
case "HIGH":
hiYellow.Fprintf(w, " [HIGH] ")
case "WARN":
yellow.Fprintf(w, " [WARN] ")
case "INFO":
dim.Fprintf(w, " [INFO] ")
}
if f.Policy != "" {
bold.Fprintf(w, "%s: ", f.Policy)
}
bold.Fprintln(w, f.Title)
if f.File != "" {
loc := f.File
if f.Line > 0 {
loc = fmt.Sprintf("%s:%d", f.File, f.Line)
}
dim.Fprintf(w, " %s\n", loc)
}
fmt.Fprintf(w, " %s\n", f.Detail)
if f.Fix != "" {
greenC.Fprintf(w, " Fix: ")
fmt.Fprintln(w, f.Fix)
}
if f.Doc != "" {
dim.Fprintf(w, " %s\n", f.Doc)
}
fmt.Fprintln(w)
}
dim.Fprintln(w, " ─────────────────────────────────────────────")
fmt.Fprintln(w)
switch {
case criticals > 0:
red.Fprint(w, " NOT READY")
fmt.Fprintf(w, " — %d critical, %d high, %d warnings\n", criticals, highs, warns)
case highs > 0:
hiYellow.Fprint(w, " NEEDS REVIEW")
fmt.Fprintf(w, " — %d high, %d warnings\n", highs, warns)
default:
green.Fprint(w, " LOOKS GOOD")
fmt.Fprintf(w, " — %d warnings, %d notes\n", warns, infos)
}
fmt.Fprintf(w, " Scanned in %s\n\n", elapsed.Round(time.Millisecond))
// Console-side obligations no static scan can see.
dim.Fprintln(w, " Not checkable from source — verify in Play Console:")
dim.Fprintln(w, " • Data safety form matches what the app actually collects")
dim.Fprintln(w, " • Advertising ID declaration, content rating, target audience")
dim.Fprintf(w, " • %s\n\n", playscan.DocAppContent)
}