Testing Java Security Policies and Permissions with AccessController
AccessController was the traditional gateway between a Java application and the runtime’s permission model. With a SecurityManager installed, AccessController.checkPermission asks it to validate a java.security.Permission against the current access context. A denial normally appears as SecurityException, although policy grants, principals and protection domains determine the result.
AccessController.doPrivileged adds a controlled elevation boundary. It does not create permission; it changes which protection domain the runtime searches during a check. That distinction causes misleading tests: one can pass because every component received AllPermission, or fail because the privileged helper came from a different JAR than expected.
Before building fixtures, capture the workflow in a technology needs assessment. Record who may perform the action, which data it touches and which component should hold the grant. This keeps the test aligned with the business rule rather than a convenient implementation.
The same discipline matters in Australia. Sydney and Melbourne contain large banking, fintech and health-software teams operating Java backends, while the OAIC expects covered organisations to demonstrate accountable access under the Privacy Act 1988 and the Australian Privacy Principles. A passing test supports that evidence, but does not establish privacy compliance.
Map the permission model before testing
A policy maps protection domains and principals to Permission objects. A domain represents a code source and its signing or runtime identity; a principal represents an authenticated identity. A custom business permission can be narrower than AllPermission, allowing export of a customer record only for a named action and resource. Implement equals, hashCode and implies correctly because the policy engine relies on them.
The main mechanisms differ in where authority comes from and what should be asserted:
| Mechanism | Permission source | Behaviour to verify | Main risk |
|---|---|---|---|
AccessController.checkPermission |
Current access context and policy | Allow or deny the requested operation | Over-broad grants hide missing checks |
AccessController.doPrivileged |
Grant held by the privileged caller’s domain | Trusted helper can cross the boundary | Treating it as a permission grant itself |
Policy.getPermissions |
Domain and principal mapping | The expected permissions are returned | Testing a fixture that differs from deployment |
| Explicit application guard | Application-owned policy object | Business decision is deterministic | Being mistaken for runtime-level equivalence |
Build a small decision matrix before coding. For each sensitive operation, identify the caller domain, authenticated principal, protected action, expected outcome and the point at which the check occurs. Keep the matrix in test resources or documentation, not production logic, so developers can review the intended boundary independently of implementation details.
A useful assertion targets observable behaviour: the call completes for an authorised domain and throws SecurityException for an unauthorised one. Avoid asserting the full access-control context, stack trace or implementation-specific message, because those details can change without changing the security decision.
Create a deterministic policy fixture
Run legacy permission tests in a dedicated forked JVM rather than changing the JVM running the whole suite. Start the fork with the SecurityManager enabled, load a test-specific Policy, and grant only the permissions needed by the test runner and target code. Keep production policies, user-specific grants and AllPermission out of this fixture. A stable code source or marker class is safer than principal names alone because test identities are often synthetic.
A focused denial test then expresses the intended rule directly:
@Test
@SuppressWarnings("removal")
void rejectsCallerWithoutExportGrant() {
CustomerDataPermission required =
new CustomerDataPermission("export", "customer-42");
assertThrows(SecurityException.class, () ->
AccessController.checkPermission(required));
}
The corresponding policy grants that permission only to the protection domain containing the exporter component. The trusted path should be tested through the component rather than by checking the fixture directly, so the test proves that the right code source reaches the protected operation. Testing Policy.getPermissions separately is still valuable, but it complements rather than replaces the end-to-end permission check.
Give every fixture its own temporary policy data and reset caches between scenarios. The JUnit 5 lifecycle can create a fresh application context per test, while the forked process remains isolated from parallel test workers. This prevents one scenario’s grants from affecting another and makes failures reproducible on a developer’s laptop as well as a build agent.
Assert outcomes at each permission boundary
Use JUnit 5 assertions to verify both sides of every boundary. A suite containing only successful calls cannot reveal an operation accidentally granted to everyone, while a suite containing only failures cannot show that the trusted path still works. The principal under test should be represented by the real component boundary wherever practical.
First, assert the business outcomes:
- An untrusted caller is denied the protected operation.
- A trusted component with the matching grant completes it.
- A valid principal with the wrong action or resource is denied.
- A failed operation propagates the expected exception without leaking access.
For an Australian software supplier, these tests can also support evidence mapped to the Australian Signals Directorate’s Essential Eight, a widely used security benchmark rather than a statute. The useful result is not a generic “security passed” label; it is reproducible evidence that a particular code path can read, export or modify a protected resource only through the intended grant.
Next, assert the privilege mechanics:
doPrivilegedsucceeds because the helper’s domain holds the required grant.- The outer caller remains subject to checks performed before the privileged block.
- Access returns to the ordinary context after the privileged action ends.
- Nested privileged blocks do not widen either component’s authority.
Inspect AccessController.getContext when a decision depends on the wrong principal or code source, but assert only the relevant domain and identity. The context is valuable diagnostic information, yet its complete representation is not a stable business contract. Likewise, do not use a broad mock as the primary oracle: it can confirm that a method was called while missing the runtime context used to make the real decision.
Test privilege scope and failure paths
Privilege often leaks in tests because the trusted helper and untrusted caller share one code source. Place the helper in a distinct module, JAR or test fixture when the production design depends on separate protection domains. If that separation cannot be reproduced, state the limitation and avoid claiming that the runtime boundary is covered.
Exercise failures inside and outside privileged blocks. A checked exception can be wrapped by PrivilegedExceptionAction, a runtime exception should retain its identity, and cleanup code may perform further permission checks after the main operation fails. Each path needs an explicit expectation. A test that verifies only the happy-path denial can miss a handler that performs an unauthorised write while reporting the original error.
Add a regression assertion after a successful privileged call. Attempt the same sensitive operation through the ordinary caller again and require a denial. This catches accidental persistence of elevated context and keeps the test honest about where elevation begins and ends. Use separate test methods where order independence matters; relying on one test to “warm up” permissions makes parallel execution unsafe.
Automate policy checks in delivery pipelines
Expose policy tests as a dedicated Maven or Gradle task and run them in a forked JVM with a pinned policy file and Java runtime. For organisations maintaining Java 8, 11 and 17 estates, include the supported versions in a small compatibility matrix rather than running every unrelated integration test on every JDK. Keep this legacy lane separate from current-JDK builds because runtime security-manager behaviour differs by release.
The pipeline should publish the policy fixture, test reports and Java version as traceability artefacts. That makes it possible to connect a failed permission decision to an exact build and configuration. It also supports incident review under the Privacy Act 1988, including assessment of unauthorised access under the Notifiable Data Breaches scheme when the facts indicate a serious incident. Privacy specialists still determine reporting obligations; automation supplies evidence, not legal conclusions.
Distributed teams add another practical concern. A Brisbane worker or a scheduled job in Perth may resume work created by a colleague in Sydney. The job must not silently inherit the originating user’s access merely because it runs in a shared worker. Model service identities and queue consumers explicitly, then test that a privileged operation uses the service account’s limited grant. This mirrors the Australian expectation behind tap-to-pay and mobile banking: an authorised person should remain distinguishable from a background service.
Modernise the approach without losing coverage
SecurityManager has been deprecated for removal since Java 17, runtime installation became restricted by default in Java 18, and JDK 24 permanently disables the mechanism. The AccessController APIs are also deprecated for removal and remain in many long-lived Java 8, 11 and 17 systems, so teams still need reliable tests for those applications. New Java services, however, should not treat a legacy compatibility lane as their long-term authorisation architecture.
Keep characterising tests while migrating checks to explicit application guards, a policy engine or modern framework security features. Each legacy call can be mapped to the business action it protects, allowing a permission denial to become an application-level deny decision. This is especially relevant for Melbourne and Sydney health-service organisations subject to the My Health Records Act 2012 and for financial systems where access evidence supports internal and regulatory reviews.
Make the migration boundary visible in the suite: retain only compatibility cases with a named owner and removal date, and require new features to use the current authorisation path. That prevents an old doPrivileged block from quietly becoming the default escape hatch as the codebase changes.
Convert the first sensitive AccessController-protected operation in the affected repository into an allow-and-deny characterisation test.