Skip to content

v0.27.0 Authorization

Choose a tag to compare

@marcgrue marcgrue released this 06 Dec 11:45
· 25 commits to main since this release

Molecule now includes a comprehensive authorization system that integrates security directly into your domain model. Define authorization rules once in your domain structure, and Molecule enforces them automatically across all queries and transactions.

What is Authorization in Molecule?

Authorization moves the security boundary from your application endpoints to the data layer itself. Instead of scattering permission checks throughout endpoints and your business logic, you declare them once in your domain structure definition.

object MyDomain extends DomainStructure {
  // Define roles with their baseline capabilities
  trait Guest extends Role with query
  trait Member extends Role with query with save
  trait Admin extends Role with query with save with insert with update with delete

  // Apply roles to entities
  trait Post extends Member with Admin {
    val content = oneString
    val draft   = oneBoolean.only[Admin] // Only admins can see draft status
  }
}

Once defined, authorization is automatically enforced:

// After user authentication by your app
implicit val conn = baseConn.withAuth(userId, "Member")

// All operations check authorization automatically
Post.content.query.get // ✓ Allowed
Post.content("Hello").save.transact // ✓ Allowed
Post(id).content("Updated").update.transact // ✗ Denied - Member lacks update
Post.draft.query.get // ✗ Denied - Member can't see draft field

The 4-Layer Authorization Model

Authorization in Molecule is built on 4 progressive layers:

Layer 1: Roles

Define which roles have access to entities and their baseline capabilities:

trait Post extends Member with Admin {
...
}

Layer 2: Action Grants

Add specific action capabilities to roles at entity level:

trait Post extends Member with Admin
  with updating[Member] { // Grant Member update capability
  val content = oneString
}

Layer 3: Attribute Restrictions

Restrict which roles can access specific attributes:

val draft = oneBoolean.only[Admin] // Only Admin can access
val views = oneInt.exclude[Guest] // All except Guest

Layer 4: Attribute Update Grants

Grant update capability for specific attributes to roles that lack general update:

val tags = manyString.updating[Member] // Member can update tags only

Core Actions

Molecule provides 5 core CRUD actions and 2 raw SQL actions:

trait query extends Action // Read data via queries
trait save extends Action // Create single entity
trait insert extends Action // Batch insert multiple entities
trait update extends Action // Modify existing data
trait delete extends Action // Remove data

trait rawQuery extends Action // Raw SQL SELECT queries
trait rawTransact extends Action // Raw SQL mutations (use sparingly!)

Compile-time Validation

When you run sbt moleculeGen, Molecule validates your authorization rules at compile time:

  • All 5 core actions must be covered for role-restricted entities
  • At least one role can query
  • At least one role can save
  • Action grants reference valid entity roles
  • Attribute restrictions reference valid entity roles
  • No conflicting permissions

This catches authorization errors before your code runs, not at runtime in production.

Key Features

Entity-level and attribute-level control - Restrict access to entire entities or fine-tune permissions per field

Public entities - Entities without roles are freely accessible without authentication

Additive grants - Start with baseline role capabilities, then add specific permissions where needed

Fast runtime checks - Authorization uses highly optimized bit masking for minimal overhead — no string comparisons!

Clear error messages - When authorization fails, you get precise messages about what role tried to do what action

One role per user - Users authenticate with a single role per connection, keeping permission logic simple

No magic roles - Admin isn't special; all roles follow the same consistent rules

Migration Notes

Authorization is opt-in and backwards compatible:

  • Entities without roles remain fully public and accessible
  • Existing code continues to work unchanged
  • Add roles progressively as needed

To start using authorization:

  1. Define roles with their actions in your domain structure
  2. Add role extensions to entities you want to protect
  3. Run sbt moleculeGen to validate and generate boilerplate
  4. Provide user role in your connection: baseConn.withAuth(userId, roleName)

See the Authorization documentation for complete details and examples.

Philosophy: Security at the Data Layer

Authorization in Molecule follows a key principle: security belongs with the data, not scattered across endpoints.

Traditional approaches put permission checks in controllers, resolvers, and business logic. This leads to:

  • Duplicate permission logic across endpoints
  • Easy to forget checks in new code paths
  • Hard to audit what's actually protected
  • Testing requires hitting every endpoint

With Molecule's authorization:

  • Define permissions once in the domain model
  • Automatically enforced everywhere data is accessed
  • Impossible to bypass (short of raw SQL)
  • Single source of truth for security rules

This approach makes your security model explicit, auditable, and maintainable.

Updated Dependencies

"org.scalamolecule" %% "molecule-db-postgres" % "0.27.0"
"org.scalamolecule" %% "molecule-db-sqlite" % "0.27.0"
"org.scalamolecule" %% "molecule-db-mysql" % "0.27.0"
"org.scalamolecule" %% "molecule-db-mariadb" % "0.27.0"
"org.scalamolecule" %% "molecule-db-h2" % "0.27.0"

Also update sbt-molecule:

addSbtPlugin("org.scalamolecule" % "sbt-molecule" % "1.22.0")