This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: android-15-private-space-decoupled-storage-isolation

Android 15 Private Space Decoupled Storage & Cryptographic Isolation

Enforces strict cryptographic hardware key isolation, profile-specific storage scoping, and decoupled cache lifecycles under Android 15 Private Space. Prohibits cross-profile keystore reuse, shared static singletons across profile boundaries, and uncleared memory-mapped storage when private profiles are locked or suspended.

Prohibited Anti-Pattern: Cross-Profile Key Reuse and Static Cache Persistence Across Android 15 Private Space Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 Private Space Decoupled Storage & Cryptographic Isolation - Enforces strict cryptographic hardware key isolation, profile-specific storage scoping, and decoupled cache lifecycles under Android 15 Private Space. Prohibits cross-profile keystore reuse, shared static singletons across profile boundaries, and uncleared memory-mapped storage when private profiles are locked or suspended.
globs: app/src/**/*.kt, app/src/**/*.java, core/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-15-private-space-decoupled-storage-isolation"
---

# Android 15 Private Space Decoupled Storage & Cryptographic Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Profile Key Reuse and Static Cache Persistence Across Android 15 Private Space Boundaries

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer enforcing strict compliance with Android 15 (API level 35) Private Space decoupled storage sandboxing. You must ensure that cryptographic keys, hardware-backed Keystore operations, cache lifecycles, and storage directories remain completely segregated per-user-profile. You must mandate profile-aware key generation, zeroization on profile locking, and prevent multi-profile data cross-contamination.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Android Keystore key aliases using profile-scoped namespaces and generate hardware-backed keys within the profile-specific context.
- Engineers MUST NOT share or persist encryption keys, cached files, or sensitive payloads in cross-user locations, external storage, or static application singletons across profile switches.
- Services MUST register for `ACTION_PROFILE_AVAILABLE` and `ACTION_PROFILE_UNAVAILABLE` broadcast intents to flush in-memory buffers and invalidate crypto handles when Private Space is suspended or locked.
- Code SHOULD dynamically detect isolated environments using `UserManager.isPrivateProfile()` on API 35+ and apply ephemeral storage retention policies to cache directories.
- Components NEVER store sensitive decrypted state in global unmanaged memory or retain open file descriptors to private profile storage when backgrounded or locked.

## Bad vs Good Implementations
### Hardware Key Generation and Storage Scoping in Android 15 Private Space

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The implementation uses a static key alias without profile scoping and caches decrypted data in an unmanaged static collection. On Android 15, if the app runs in both the main profile and Private Space, keys and cached memory may overlap or fail to clear when the Private Space profile is locked or destroyed.
```kotlin
// Anti-Pattern: Global static Keystore client and un-scoped cache storage
object CryptoStorageManager {
    private const val KEY_ALIAS = "enterprise_master_key"
    private val memoryCache = mutableMapOf<String, ByteArray>()

    fun getSecretKey(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        if (!keyStore.containsAlias(KEY_ALIAS)) {
            val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
            keyGenerator.init(
                KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .build()
            )
            return keyGenerator.generateKey()
        }
        return (keyStore.getEntry(KEY_ALIAS, null) as KeyStore.SecretKeyEntry).secretKey
    }

    fun cacheDecryptedData(id: String, payload: ByteArray) {
        // Leaks across profile contexts if process is retained
        memoryCache[id] = payload
    }
}
```

#### Production Standard (Correct)
> **Standard**: Correctly determines profile isolation using `UserManager.isPrivateProfile` on Android 15 (API 35), binds key aliases to distinct UserHandle identities, leverages StrongBox hardware backing where available, and provides strict lifecycle-aware directory isolation and purging capabilities.
```kotlin
// Production Standard: Profile-aware isolated key manager with lifecycle eviction
class ProfileAwareSecureStorage(private val context: Context) {
    private val userManager = context.getSystemService(Context.USER_SERVICE) as UserManager
    private val keyAlias: String

    init {
        val isPrivate = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
            userManager.isPrivateProfile
        } else {
            false
        }
        val profileId = Process.myUserHandle().hashCode()
        keyAlias = if (isPrivate) "private_space_key_$profileId" else "main_profile_key_$profileId"
    }

    fun getOrCreateKey(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        if (!keyStore.containsAlias(keyAlias)) {
            val keyGenSpec = KeyGenParameterSpec.Builder(
                keyAlias,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setUserAuthenticationRequired(false)
                .setIsStrongBoxBacked(context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE))
                .build()

            val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
            keyGenerator.init(keyGenSpec)
            return keyGenerator.generateKey()
        }
        return (keyStore.getEntry(keyAlias, null) as KeyStore.SecretKeyEntry).secretKey
    }

    fun getIsolatedCacheDir(): File {
        // Guaranteed decoupled storage directory per Android user profile sandbox
        return File(context.noBackupFilesDir, "secure_cache").apply { mkdirs() }
    }

    fun purgeSensitiveResources() {
        getIsolatedCacheDir().deleteRecursively()
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Android 15 Private Space Decoupled Storage & Cryptographic Isolation

Android 15 Private Space Decoupled Storage & Cryptographic Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cryptographic hardware key isolation, profile-specific storage scoping, and decoupled cache lifecycles under Android 15 Private Space. Prohibits cross-profile keystore reuse, shared static singletons across profile boundaries, and uncleared memory-mapped storage when private profiles are locked or suspended. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Cross-Profile Key Reuse and Static Cache Persistence Across Android 15 Private Space Boundaries Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftCross-Profile Key Reuse and Static Cache Persistence Across Android 15 Private Space BoundariesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate Android Keystore key aliases using profile-scoped namespaces and generate hardware-backed keys within the profile-specific context.

Engineers MUST ALWAYS isolate Android Keystore key aliases using profile-scoped namespaces and generate hardware-backed keys within the profile-specific context.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT share or persist encryption keys, cached files, or sensitive payloads in cross-user locations, external storage, or static application singletons across profile switches.

Engineers MUST NOT share or persist encryption keys, cached files, or sensitive payloads in cross-user locations, external storage, or static application singletons across profile switches.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST register for `ACTION_PROFILE_AVAILABLE` and `ACTION_PROFILE_UNAVAILABLE` broadcast intents to flush in-memory buffers and invalidate crypto handles when Private Space is suspended or locked.

Services MUST register for `ACTION_PROFILE_AVAILABLE` and `ACTION_PROFILE_UNAVAILABLE` broadcast intents to flush in-memory buffers and invalidate crypto handles when Private Space is suspended or locked.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD dynamically detect isolated environments using `UserManager.isPrivateProfile()` on API 35+ and apply ephemeral storage retention policies to cache directories.

Code SHOULD dynamically detect isolated environments using `UserManager.isPrivateProfile()` on API 35+ and apply ephemeral storage retention policies to cache directories.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store sensitive decrypted state in global unmanaged memory or retain open file descriptors to private profile storage when backgrounded or locked.

Components NEVER store sensitive decrypted state in global unmanaged memory or retain open file descriptors to private profile storage when backgrounded or locked.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Android 15 Private Space Decoupled Storage & Cryptographic Isolation critical for AI coding assistants?

Enforces strict cryptographic hardware key isolation, profile-specific storage scoping, and decoupled cache lifecycles under Android 15 Private Space. Prohibits cross-profile keystore reuse, shared static singletons across profile boundaries, and uncleared memory-mapped storage when private profiles are locked or suspended. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Cross-Profile Key Reuse and Static Cache Persistence Across Android 15 Private Space Boundaries) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Android