Authorization & Policy Gates

Katal provides a comprehensive, policy-based authorization system inspired by Laravel Gates and Policies. Policies are evaluated against the authenticated user, the request context, and optional domain entity resources.


1. Core Architecture

The authorization subsystem is managed by the Authorization service and exposed through the Application facade. It supports: - Named Gates: Closure-based permission checks (e.g., 'view-admin', 'manage-billing'). - Class-Based Resource Policies: Grouping authorization logic by domain model (e.g., PostPolicy, OrderPolicy). - Global before Hooks: Universal interceptors for bypasses (e.g., granting Super Admins all abilities). - Rich GateResponse Objects: Returning fine-grained error messages and machine-readable error codes instead of simple booleans. - Route Middleware: Protecting routes declaratively via ['auth', 'can:ability']. - Controller Programmatic Inspection: Inspecting abilities inside controllers with full contextual reasons.

                      Incoming Request
                             │
                             ▼
                    ┌─────────────────┐
                    │ Auth Middleware │  (Populates ctx.user)
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ can:ability Gate│
                    └────────┬────────┘
                             │
            ┌────────────────┴────────────────┐
            ▼                                 ▼
   ┌─────────────────┐               ┌─────────────────┐
   │  before() Hook  │ (Super Admin) │  Resource/Gate  │
   │  Returns allow? │               │  Callback Run   │
   └────────┬────────┘               └────────┬────────┘
            │                                 │
     (Allow / Deny)                    (Allow / Deny)
            │                                 │
            └────────────────┬────────────────┘
                             │
                  ┌──────────┴──────────┐
                  ▼                     ▼
          HTTP 403 Forbidden    Proceed to Controller

2. Defining Named Gates

Register named gates directly on the Application instance:

import { Application, GateResponse } from "katal";

const app = new Application({ port: 3000 });

// 1. Simple boolean check
app.definePolicy("admin", (user) => {
    return user.role === "admin";
});

// 2. Gate with RequestContext inspection
app.definePolicy("edit-profile", (user, resource, ctx) => {
    // Users can edit their own profile, or admins can edit any profile
    return user.id === ctx?.params.id || user.role === "admin";
});

// 3. Gate returning a rich GateResponse with message and diagnostic code
app.definePolicy("publish-article", (user) => {
    if (user.role !== "editor" && user.role !== "admin") {
        return GateResponse.deny(
            "You must be an editor or admin to publish articles.",
            "INSUFFICIENT_ROLE"
        );
    }
    if (!user.isEmailVerified) {
        return GateResponse.deny(
            "Your email address must be verified before publishing.",
            "EMAIL_UNVERIFIED"
        );
    }
    return GateResponse.allow();
});

Batch Definition

Register multiple named policies simultaneously using definePolicies:

app.definePolicies({
    "view-dashboard": (user) => ["admin", "analyst", "manager"].includes(user.role),
    "manage-users": (user) => user.role === "admin",
    "export-reports": (user) => user.role === "admin" || user.permissions?.includes("reports.export"),
});

3. Global before Hooks (Super Admin Bypass)

Use before() hooks to intercept all authorization checks before individual gates run. If a before callback returns true, the action is immediately authorized. If it returns false, it is immediately denied. If it returns null or undefined, execution falls through to the specific gate:

import { Authorization } from "katal";

const authz = app.resolve<Authorization>("authorization");

// Grant Super Admins unconditional access across the entire application
authz.before((user, ability, resource) => {
    if (user.role === "superadmin") {
        return true; // Bypass all gates
    }
    if (user.isSuspended) {
        return false; // Universal deny for suspended accounts
    }
    // Fall through to specific gate callback
});

4. Class-Based Resource Policies

For complex domain entities (like Blog Posts, Invoices, or E-Commerce Orders), encapsulate logic in dedicated policy classes:

import { GateResponse } from "katal";

export class Article {
    constructor(
        public readonly id: string,
        public readonly authorId: string,
        public readonly isPublished: boolean,
        public readonly organizationId: string
    ) {}
}

export class ArticlePolicy {
    // Can user view the article?
    view(user: any, article: Article): boolean {
        if (article.isPublished) return true;
        return user.id === article.authorId || user.organizationId === article.organizationId;
    }

    // Can user update the article?
    update(user: any, article: Article): GateResponse | boolean {
        if (user.id !== article.authorId) {
            return GateResponse.deny("You do not own this article.", "NOT_AUTHOR");
        }
        if (article.isPublished && user.role !== "admin") {
            return GateResponse.deny("Published articles can only be edited by admins.", "LOCKED");
        }
        return GateResponse.allow();
    }

    // Can user delete the article?
    delete(user: any, article: Article): boolean {
        return user.id === article.authorId || user.role === "admin";
    }
}

// Register policy with the entity constructor
authz.registerPolicy(Article, new ArticlePolicy());

5. Protecting Routes Declaratively

Attach authorization checks to routes using the can:<ability> middleware string. Always position can: after auth middleware so that ctx.user is already authenticated and available:

const router = app.getRouter();

// 1. Single gate on route
router.get("/admin/metrics", MetricsController, {
    middleware: ["auth", "can:admin"],
});

// 2. Chained gates on sensitive endpoints
router.post("/articles", CreateArticleController, {
    middleware: ["auth", "can:publish-article"],
});

// 3. Protecting entire route groups
router.group("/api/v1/billing", (r) => {
    r.get("/invoices", ListInvoicesController);
    r.post("/charge", ChargeCreditCardController);
}, { middleware: ["auth", "can:manage-billing"] });

6. Programmatic Controller Authorization

Inside controllers, evaluate abilities programmatically using authz.can() or authz.inspect():

import { Controller } from "katal";
import type { RequestContext } from "katal";
import { Authorization, GateResponse } from "katal";
import { Article } from "./models/Article";

export class UpdateArticleController extends Controller {
    constructor(
        private readonly authz: Authorization,
        private readonly articleRepo: ArticleRepository
    ) {
        super();
    }

    async handle(ctx: RequestContext) {
        const article = await this.articleRepo.findById(ctx.params.id);
        if (!article) {
            return this.notFound("Article not found.");
        }

        // 1. Inspect ability on the resource instance
        const response: GateResponse = await this.authz.inspect("update", article, ctx);

        if (!response.allowed) {
            return this.forbidden(response.message ?? "Action unauthorized.");
        }

        // 2. Proceed with domain mutation
        await this.articleRepo.update(article.id, ctx.body);
        return this.success({ updated: true });
    }
}

7. Error Responses (RFC 7807 / 9457)

When authorization fails, Katal automatically outputs RFC-compliant Problem Details (application/problem+json):

Missing Authentication (401)

{
  "type": "https://tools.ietf.org/html/rfc9457",
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required to access this resource."
}

Policy Denied (403)

{
  "type": "https://tools.ietf.org/html/rfc9457",
  "title": "Forbidden",
  "status": 403,
  "detail": "You must be an editor or admin to publish articles."
}

8. Unit Testing Policies

Because Katal's policies are standard functions or classes, testing them is completely deterministic with zero mock servers:

import { describe, it, expect } from "bun:test";
import { Article, ArticlePolicy } from "./ArticlePolicy";

describe("ArticlePolicy", () => {
    const policy = new ArticlePolicy();

    it("allows authors to update their unpublished draft", () => {
        const user = { id: "user-1", role: "author" };
        const article = new Article("art-1", "user-1", false, "org-1");

        const result = policy.update(user, article);
        expect(result.allowed).toBe(true);
    });

    it("denies non-authors from updating someone else's draft", () => {
        const user = { id: "user-2", role: "author" };
        const article = new Article("art-1", "user-1", false, "org-1");

        const result = policy.update(user, article);
        expect(result.allowed).toBe(false);
        expect(result.code).toBe("NOT_AUTHOR");
    });
});

See Also