Skip to main content

archenstack-rbac-java

archenstack-rbac-java is a framework-agnostic role × feature access matrix for the JVM — one of Archenstack's sibling cores, alongside Python, Node.js, Go, and Rust. It ships a pure resolving core with zero runtime dependencies, plus a Spring Boot starter that auto-configures the whole management API — so you wire one bean and get roles, features, a permission matrix, and per-request access checks.

The core resolves a (role, feature) pair to an ordered AccessLevel (NONE < VIEW < PARTIAL < FULL): a code default ships in your catalogue and runtime overrides layer on top. Superusers always resolve FULL; aliases mirror one role onto another; and the rbac.manage management feature can never be locked out (at least one active standard role must resolve FULL on it). See the model and resolution & scopes for the concepts.

Modules​

The Maven aggregator is archenstack-rbac-java (group io.archenstack), holding three library modules:

ModuleWhat it is
archenstack-rbac-coreThe spec-conformant resolving core: access levels, the resolution algorithm, scope evaluation, the snapshot model, validation, canonical JSON, and policy IO. Zero runtime dependencies.
archenstack-rbac-tenancyThe dependency-light write-side tenancy primitives — TenantOwned, ArchenstackTenantContext, and the @PrePersist ArchenstackTenantListener. jakarta.persistence only — no Spring — so a modular host references them from its entity modules without dragging the starter down there.
archenstack-rbac-spring-boot-starterThe Spring Boot adapter: JPA persistence, the management REST API (roles / features / groups / matrix / me / check / audit), seeding, the anti-lockout check, version-stamped snapshot caching, and the ArchenstackTenantFilter that populates the tenant context.

A ready-to-run Spring Boot demo consuming the published starter lives in the separate archenstack-demo repo (spring-demo) — see Running the demo.

Published to Archenstack's GitLab Maven registry

archenstack-rbac-core, archenstack-rbac-tenancy, and archenstack-rbac-spring-boot-starter are published to Archenstack's GitLab Maven registry — add it as a repository and depend on them by their io.archenstack coordinates. See Installation.

Conformance​

archenstack-rbac-core is validated against the shared normative corpus in the sibling archenstack-rbac-spec/ repo (vectors/*.json + wire-golden/*.json) — the identical cases every Archenstack core runs. Canonical JSON is byte-for-byte compatible across all the implementations, so a snapshot serialized by the Java core is indistinguishable from one serialized by any other.

Tests run: 160, Failures: 0
(131 conformance + 12 core facade/policy + 16 adapter API + 1 fail-closed)

See the normative spec and the wire protocol for what the corpus pins down.

Build & test​

Targets Java 17 bytecode (runs on 17+); build with any JDK 17–21.

# from archenstack-rbac-java/
mvn install # build + test + install all three modules
mvn -pl archenstack-rbac-core test # just the core conformance suite

Use the core in any JVM framework​

archenstack-rbac-core is a plain library with zero runtime dependencies — no Spring, no reflection, no annotations. Use it directly from any JVM stack — plain Java, Quarkus, Micronaut, Jakarta EE / servlets, Vert.x, a CLI — not just Spring Boot:

import io.archenstack.core.AccessLevel;
import io.archenstack.core.Matrix;

Matrix matrix = new Matrix()
.superusers(List.of("owner"))
.aliases(Map.of("supervisor", "manager"))
.addRole("administrator").addRole("manager").addRole("staff")
.addFeature("records.edit", "Edit records")
.defineRows(List.of("administrator", "manager", "staff"),
Map.of("records.edit", List.of(3, 2, 2))); // FULL, PARTIAL, PARTIAL

matrix.canWrite("records.edit", "staff"); // true (PARTIAL is writable)
matrix.level("records.edit", "owner"); // AccessLevel.FULL (superuser)
matrix.override("records.edit", "staff", 0); // a runtime override → NONE

Check a request in your own controller, filter, or interceptor:

if (!matrix.canWrite("records.edit", currentRole(request))) {
throw new ForbiddenException();
}

The core also ships the normative pieces — MatrixSnapshot, Resolver, Scope.evalScope, Validate, CanonicalJson, Policy — so you can persist a snapshot and serve the wire protocol from your own framework. The Spring Boot starter below is simply one adapter built on exactly these primitives; a Quarkus or Micronaut adapter would wrap them the same way (persist a snapshot → compile it through the core → serve /me/ and /check/).

Using the Spring Boot starter​

Add the starter dependency and the whole management API auto-configures — entities, repositories, services, controllers, error handling, seeding, and authorization:

<dependency>
<groupId>io.archenstack</groupId>
<artifactId>archenstack-rbac-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>

Then provide one bean bridging your authentication to the caller's stable OIDC sub. Archenstack reads the role from its own (org, sub) assignment table — your token never carries one. RbacPrincipalResolver is a functional interface, so a lambda is enough:

@Bean
RbacPrincipalResolver rbacPrincipalResolver() {
return request -> currentUser(request).getSub(); // your principal → OIDC `sub`
}

Return null for an unauthenticated or role-less caller. The adapter stays out of authentication entirely — map your Spring Security principal, a JWT claim, or a session however you already do. (You can also supply an RbacSubjectResolver bean to feed object-level scope evaluation the caller's pk, department, and so on.)

Multi-tenancy: resolveOrg

For a multi-tenant deployment, the same RbacPrincipalResolver bean has a default String resolveOrg(HttpServletRequest) method — override it to read the OIDC org claim off the validated principal. It fails closed: the default returns null, so an unresolved org denies (never silently the root org). A cross-org admin selects a specific tenant with the X-Archenstack-Org header. See Wiring multi-tenancy.

Fail-closed by default

With no RbacPrincipalResolver bean the adapter resolves every caller to no identity — and therefore no assignment and no role: authenticated routes return 401, and the app logs a loud startup WARN. It never trusts a header as identity — provide a resolver bean, or enable the built-in JWT-claims resolver below.

For a JWT resource server — the common OIDC deployment — enable the built-in resolver with archenstack-rbac.jwt-resolver.enabled=true. It reads the caller's identity off the already-validated principal in the security context: sub → subject, org → tenant, email → the member-reconciliation attribute (claim names configurable under archenstack-rbac.jwt-resolver.*), honoring the X-Archenstack-Org header for a cross-org admin's tenant selection. A platform-claim asserts cross-org platform-admin authority off the token; when that claim is a roles/groups array (e.g. roles: ["platform"]) or a space-delimited scope string (e.g. scope: "openid rbac.platform"), set archenstack-rbac.jwt-resolver.platform-value to the value that must be present — leave it empty and the claim is read as a plain boolean flag.

First-admin bootstrap. A fresh deployment has no way to create its first assignment from inside the matrix — every management route already requires rbac.manage FULL. Set archenstack-rbac.bootstrap-admin-subject to a stable OIDC sub and the starter binds it to the admin role in the default org at startup (idempotent; empty — the default — means no bootstrap). The role it binds to is archenstack-rbac.bootstrap-admin-role (default administrator): the default auto-seeds the sample catalogue when the org has no roles yet, whereas a custom admin slug must already exist in a catalogue you've seeded — a missing custom role logs a WARN and skips, so the sample never overwrites a catalogue whose admin role is named differently.

Configuration​

Everything operator-tunable lives under the archenstack-rbac.* property namespace, bound from ArchenstackRbacProperties. Thanks to Spring's relaxed binding, each is also settable via the matching ARCHENSTACK_RBAC_* environment variable (e.g. archenstack-rbac.base-path → ARCHENSTACK_RBAC_BASE_PATH).

PropertyEnv varDefaultPurpose
archenstack-rbac.base-pathARCHENSTACK_RBAC_BASE_PATH/api/v1prefix the routes mount under (before /permissions/…)
archenstack-rbac.seed-on-startupARCHENSTACK_RBAC_SEED_ON_STARTUPtrueseed the sample catalogue when the matrix is empty
archenstack-rbac.scope-owner-fieldsARCHENSTACK_RBAC_SCOPE_OWNER_FIELDSowner, created_by, userobject FK fields tried in order for the own_record scope atom
archenstack-rbac.scope-department-fieldARCHENSTACK_RBAC_SCOPE_DEPARTMENT_FIELDdepartmentobject FK field for own_department
archenstack-rbac.enforcement-modeARCHENSTACK_RBAC_ENFORCEMENT_MODEenforceshadow logs a would-be denial and lets it through instead of blocking — for staging enforcement onto a live app (enforcement mode); rbac.manage is never shadowed
archenstack-rbac.host-exception-adviceARCHENSTACK_RBAC_HOST_EXCEPTION_ADVICEfalseregister an app-wide advice that renders a ScopeAuthorizer denial thrown from your own service layer as a 403/401 envelope instead of a 500
archenstack-rbac.host-exception-advice-orderARCHENSTACK_RBAC_HOST_EXCEPTION_ADVICE_ORDERHIGHEST_PRECEDENCEthe advice's @Order; high by default so it wins over a host's generic @ExceptionHandler(Exception.class) catch-all
archenstack-rbac.tenant-contextARCHENSTACK_RBAC_TENANT_CONTEXTfalsepublish the request's active org to ArchenstackTenantContext so a @PrePersist stamp can tag new rows (write-side only; does not scope reads)
archenstack-rbac.tenant-default-orgARCHENSTACK_RBAC_TENANT_DEFAULT_ORG(empty)fallback tenant for the @PrePersist stamp when no active org is bound (a seeder/cron off a request); empty ⇒ leave null and let NOT NULL/RLS reject it
archenstack-rbac.audit-default-page-sizeARCHENSTACK_RBAC_AUDIT_DEFAULT_PAGE_SIZE50default audit-log page size
archenstack-rbac.audit-max-page-sizeARCHENSTACK_RBAC_AUDIT_MAX_PAGE_SIZE500maximum audit-log page size
archenstack-rbac.check-batch-maxARCHENSTACK_RBAC_CHECK_BATCH_MAX200max items accepted by one batch POST /check/ (over the cap → validation)
archenstack-rbac.default-orgARCHENSTACK_RBAC_DEFAULT_ORG(required, no inline default)the dev/seed/backfill org slug (e.g. root); seeds and backfills only, never a runtime fallback for a real request
archenstack-rbac.bootstrap-admin-roleARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_ROLEadministratorrole slug the first-admin bootstrap binds bootstrap-admin-subject to; the default administrator auto-seeds the sample catalogue if the org has no roles, while a custom slug that doesn't already exist logs a WARN and skips (never overwrites your catalogue). The bind only ever adds: a subject that already holds a role in the org keeps it, so the bootstrap cannot remove the last admin-capable holder
archenstack-rbac.jwt-resolver.platform-valueARCHENSTACK_RBAC_JWT_RESOLVER_PLATFORM_VALUE(empty)value the JWT resolver matches inside the platform-claim when it's a roles/groups array or a space-delimited scope string; empty ⇒ the platform claim is read as a plain boolean flag
Spec-pinned, not configurable

The management feature (rbac.manage) and its minimum level (FULL) are pinned in the core and deliberately not configurable — they're what keeps the matrix from locking every admin out of the management API.

Host-facing helpers​

Beyond the endpoints, the starter gives your own code four ways to enforce and query the matrix — all resolving through the same (role, feature) decision, so a UI hint, an annotation, a service call and a bulk query never disagree.

@Can("feature") — declarative method security. A short annotation that requires a feature on a method:

@Can("reports.view") // read (VIEW+) — the default need
@Can(value = "records.edit", need = "write") // write (PARTIAL+)
@Can(value = "rbac.manage", need = "full") // FULL
public void update(...) { ... }

need is read/view (VIEW+), write/edit/partial (PARTIAL+), or full/manage (FULL); a mis-spelled literal throws rather than denying silently. The caller's role is resolved server-side from the request, never from the annotation, so a client cannot assert its own authority. It is feature-level by design — the check runs before the target method loads any row — so per-row (object) scope stays with ScopeAuthorizer. It honours archenstack-rbac.enforcement-mode: under shadow a would-be denial is logged and passes (returns allowed) rather than blocking, so you can roll the coarse check out gradually over a live app — except the policy-admin feature rbac.manage, which is never shadowed. See enforcement mode.

For an imperative check instead of the annotation, inject the RbacPermissions bean and call can(feature, need). Enabling @Can: add @EnableMethodSecurity to a @Configuration (the starter does not turn method security on for you, and keeps spring-security-config optional); the starter registers the template-defaults bean the @Can placeholders need, so that one annotation is all it takes.

ScopeAuthorizer — imperative object enforcement. For "may this caller write this row" after you load it: authorizer.require(request, "records.edit", Map.of("owner", doc.getOwnerSubject())) (throws 403, or logs-and-proceeds under enforcement-mode=shadow). See Object scopes.

WriteScope — bulk write-scoping. The query-level twin of ScopeAuthorizer, as a Spring Data JPA Specification:

List<Document> editable = repo.findAll(writeScope.forWrite(request, "records.edit"));

FULL → all rows, PARTIAL → scope-narrowed, below → none; composes with .and(...). Writes only (reads stay unscoped). The shipped atoms translate to SQL out of the box; teach it a host domain atom by registering a ScopeAtomSqlTranslator bean (the query-path twin of a ScopeAtom). See Bulk write-scoping.

Catalogue.scope(...) — declare write scopes fluently. The seed builder can attach a feature's write scope and the matrix-wide default without a hand-written Map:

Catalogue.create()
.defaultScope("own_record")
.feature("records.edit", "Edit records").grant("staff", AccessLevel.PARTIAL).scope("own_subtree")
.build();

Write-side tenancy companion (opt in: archenstack-rbac.tenant-context=true). ArchenstackTenantContext.activeOrg() publishes the request's active org, a @PrePersist ArchenstackTenantListener stamps a TenantOwned row with it, and reads stay with database RLS. The three entity-facing types ship in a tiny Spring-free jar, io.archenstack:archenstack-rbac-tenancy (jakarta.persistence only), so a modular host can adopt them in its domain modules without dragging the starter down there; only ArchenstackTenantFilter lives in the starter. See Tenant data isolation.

Endpoints​

All routes mount under ${archenstack-rbac.base-path}/permissions. Management routes require the caller to resolve rbac.manage FULL; /me/ and /check/ require only authentication.

MethodPathPurpose
GET / PUT/matrix/read the snapshot / bulk-apply cell edits
POST/matrix/reset/clear all overrides back to defaults
GET POST/roles/ · /features/ · /groups/list / create
GET PATCH/roles/{slug}/ · /features/{key}/ · /groups/{slug}/detail / update / deactivate
POST/roles/reorder/ · /features/reorder/ · /groups/reorder/reorder
GET/me/the caller's resolved permission map
POST/check/resolve access — single or batch (see below)
GET/audit/the append-only change log
GET PATCH/orgs/ · /orgs/{slug}/list / read organizations — the multi-tenant picker source; PATCH is restricted to platform authority
POST/orgs/provision an organization — create inactive, seed, bind the first admin, activate. Requires a platform principal (an IdP-asserted platform scope, or a subject in ARCHENSTACK_RBAC_PLATFORM_SUBJECTS), never an org admin. How a standalone deployment creates tenants without a provisioning orchestrator
GET POST/orgs/{slug}/apps/list / register an org's OIDC clients (client_id ↔ org binding); register accepts the org's own admin or a platform principal

POST /check/​

The check endpoint accepts two request shapes and echoes which one it answered via the response kind:

  • Single — { "feature": "...", "object": { … } } (the object is optional and drives object-level scope evaluation). The response is kind: "policy".
  • Batch — { "checks": [ { "feature", "object"? }, … ] }. The response is kind: "policy-batch" with a positional results array: results[i] corresponds to checks[i], and results.length == checks.length.

The batch form resolves a whole list in one round-trip. It fails closed per item (an unknown feature denies rather than erroring the whole request), rejects a structurally malformed item with a validation error, and is bounded by archenstack-rbac.check-batch-max (default 200) — a batch over the cap is rejected with validation. See the specification and the wire protocol.

# single
curl -s -X POST "$B/permissions/check/" \
-H 'Authorization: Bearer manager' -H 'Content-Type: application/json' \
-d '{"feature":"invoices","object":{"owner":"manager"}}'

# batch — positional results
curl -s -X POST "$B/permissions/check/" \
-H 'Authorization: Bearer manager' -H 'Content-Type: application/json' \
-d '{"checks":[{"feature":"invoices"},{"feature":"reports"}]}'

Running the demo​

A ready-to-run Spring Boot demo lives in the separate archenstack-demo repo (spring-demo). It consumes the published io.archenstack:archenstack-rbac-spring-boot-starter, boots on in-memory H2 with a stub login, and seeds the Owner / Administrator / Manager / Staff / Supervisor sample matrix — the same catalogue every Archenstack backend seeds — so you can drive the whole API without wiring real authentication:

# in archenstack-demo/spring-demo/
cp .env.example .env # config is env-only, no fallbacks
mvn spring-boot:run

The app serves http://localhost:8903/api/v1/… (SERVER_PORT in .env). The stub login mints a signed JWT — the email local-part picks the role (manager@demo → manager; anything unrecognized logs in as the owner superuser) — which you send as a normal Bearer credential; the resource-server chain validates it and the starter's jwt-resolver reads the claims:

B=http://localhost:8903/api/v1
TOKEN=$(curl -s -X POST $B/auth/login/ -d '{"email":"administrator@demo"}' -H 'Content-Type: application/json' | sed -E 's/.*"access":"([^"]+)".*/\1/')
curl -s $B/permissions/me/ -H "Authorization: Bearer $TOKEN"

Log in as administrator (management-FULL admin), owner (superuser), manager / staff, or supervisor (an alias of manager); the archenstack-rbac-web React demo can point at this backend via its API base URL.

The demo is a real resource server

The demo shows the standard secure pattern, not a dev-header shortcut: the stub login signs a short-lived HS256 token and the resource-server chain validates it before the jwt-resolver (archenstack-rbac.jwt-resolver.enabled=true) reads the role / subject / org / email claims. In your own app, delegate login to your IdP and validate RS256 tokens against its JWKS — the resolver config is identical.

Releasing​

The publishable artifacts are the parent POM, archenstack-rbac-core, archenstack-rbac-tenancy and archenstack-rbac-spring-boot-starter. Releases go to Archenstack's GitLab Maven registry from CI: bump the version, then push an archenstack-rbac-java/vX.Y.Z tag and the pipeline deploys all four, so a consumer can resolve io.archenstack:archenstack-rbac-spring-boot-starter:1.0.0. All four are needed to resolve the starter: it names the parent POM as its <parent> and declares archenstack-rbac-tenancy as a dependency. See Installation to consume them.

Prefer a local build? mvn -pl archenstack-rbac-core,archenstack-rbac-tenancy,archenstack-rbac-spring-boot-starter install -DskipTests installs into your ~/.m2 for other local Maven/Gradle builds. Going public later swaps the target to Maven Central (POM metadata + GPG signing) — the coordinates don't change.

See also​