
A flexible, composable authorization framework for Kit (inspired by Action Policy)
# kit-policy
A flexible, composable authorization framework for Kit, inspired by Ruby's [Action Policy](https://actionpolicy.evilmartians.io/).
---
[TOC]
---
## Files
| File | Description |
|------|-------------|
| [`.editorconfig`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.editorconfig) | Editor formatting configuration |
| [`.gitignore`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.gitignore) | Git ignore rules for build artifacts and dependencies |
| [`.tool-versions`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.tool-versions) | asdf tool versions (Zig, Kit) |
| [`LICENSE`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/LICENSE) | MIT license file |
| [`README.md`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/README.md) | This file |
| [`examples/blog-policy.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/examples/blog-policy.kit) | Blog authorization example |
| [`kit.toml`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/kit.toml) | Package manifest with metadata, tasks, and lint configuration |
| [`src/core.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/core.kit) | Core authorization helpers |
| [`src/error.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/error.kit) | Authorization errors, result types, and failure reasons |
| [`src/main.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/main.kit) | Package root module |
| [`src/scope.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/scope.kit) | Scope, predicate, and pagination helpers |
| [`tests/policy.test.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/tests/policy.test.kit) | End-to-end policy behavior tests |
| [`tests/types.test.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/tests/types.test.kit) | Policy type and helper tests |
## Dependencies
_No Kit package dependencies._
## Installation
```console
kit add gitlab.com/kit-lang/packages/kit-policy.git
```
## Usage
```kit
import Kit.Policy.Core as PolicyCore
import Kit.Policy.Error as PolicyError
import Kit.Policy.Scope as PolicyScope
type Post = {id: Int, author-id: Int, published?: Bool, title: String}
type User = {id: Int, admin?: Bool}
type AuthContext = {user: User}
post-policy = fn(post, ctx, action) =>
if ctx.user.admin? then
PolicyCore.allow
else
match PolicyCore.resolve-alias action
| :show -> PolicyCore.allow-if post.published?
| :update -> PolicyCore.allow-if (ctx.user.id == post.author-id)
| :destroy -> PolicyCore.allow-if (ctx.user.id == post.author-id)
| _ -> PolicyCore.no-rule action
post-scope = fn(posts, ctx) =>
if ctx.user.admin? then
posts
else
posts |>> List.filter (fn(post) => post.published?)
main = fn =>
user = {id: 1, admin?: false}
ctx = {user: user}
post = {id: 1, author-id: 1, published?: true, title: "Hello"}
posts = [post]
if PolicyCore.can-with? post-policy post ctx :update then
println "Can update post"
else
println "Cannot update post"
visible-posts = PolicyScope.scope-with post-scope posts ctx
page = PolicyScope.paginate 1 10 visible-posts
info = PolicyScope.pagination-info 1 10 visible-posts
println "Visible posts: ${page}"
println "Pages: ${info.pages}"
err = PolicyError.not-authorized "Post" :update "not the author"
println (PolicyError.message err)
main
```
## API Overview
### Policy.Core
Core helpers for policy functions that return `Result Bool PolicyError`.
```kit
PolicyCore.can-with? policy resource context action
PolicyCore.may-with? policy resource context action
PolicyCore.allow
PolicyCore.deny
PolicyCore.allow-if condition
PolicyCore.deny-if condition
PolicyCore.no-rule action
PolicyCore.allow-or-deny condition resource-name reason action
```
Pre-check helpers return `Option Bool`: `Some true` allows, `Some false` denies, and `None` continues to the main rule.
```kit
PolicyCore.admin-bypass is-admin? ctx
PolicyCore.owner-check is-owner? resource ctx
PolicyCore.first-pre-check [check1, check2, check3]
```
Action helpers provide common action groups and aliases.
```kit
PolicyCore.crud-actions
PolicyCore.read-actions
PolicyCore.write-actions
PolicyCore.read-action? action
PolicyCore.write-action? action
PolicyCore.resolve-alias :new # :create
PolicyCore.resolve-alias :edit # :update
PolicyCore.resolve-alias :delete # :destroy
PolicyCore.resolve-alias :view # :show
```
Policy composition helpers combine several authorization results.
```kit
PolicyCore.all-allowed? [result1, result2, result3]
PolicyCore.any-allowed? [result1, result2, result3]
```
### Policy.Scope
Scope helpers filter collections before returning data to a caller.
```kit
PolicyScope.scope-with scope-fn items ctx
PolicyScope.filter-by predicate items
PolicyScope.is-owned-by? get-owner-id get-user-id item ctx
PolicyScope.is-published? get-published item
PolicyScope.is-in-state? get-state target-state item
PolicyScope.is-admin-or? check-admin fallback-check ctx item
```
Predicate combinators are useful for building reusable scope checks.
```kit
PolicyScope.both? pred1 pred2 item
PolicyScope.either? pred1 pred2 item
PolicyScope.not-matching? pred item
```
Pagination helpers are 1-indexed.
```kit
page1 = PolicyScope.paginate 1 10 items
pages = PolicyScope.total-pages 10 items
info = PolicyScope.pagination-info 1 10 items
```
### Policy.Error
Error and result types for authorization failures.
```kit
type PolicyError =
| NotAuthorized {resource: String, action: Keyword, reason: String}
| RuleNotFound {action: Keyword}
| ContextMissing {field: String}
| PolicyNotFound {resource-type: String}
| CustomError String
type FailureReason = FailureReason {
policy: String,
action: Keyword,
details: String
}
type AuthResult =
| Allowed
| Denied String
```
Helper functions are exported from the module, so when imported as `PolicyError` they are called as module functions.
```kit
PolicyError.not-authorized resource action reason
PolicyError.rule-not-found action
PolicyError.context-missing field
PolicyError.policy-not-found resource-type
PolicyError.custom message
PolicyError.message err
PolicyError.kind err
PolicyError.is-not-authorized? err
PolicyError.is-rule-not-found? err
PolicyError.new policy action
PolicyError.with-details policy action details
PolicyError.policy reason
PolicyError.action reason
PolicyError.details reason
PolicyError.format reason
PolicyError.allowed
PolicyError.denied reason
PolicyError.is-allowed? result
PolicyError.is-denied? result
PolicyError.reason result
PolicyError.to-result resource-name action result
```
## Design Notes
- Policies are plain functions, so they are easy to test and compose.
- Authorization is explicit: helpers return `Result Bool PolicyError` instead of throwing exceptions.
- Scopes are separate from policy checks so list filtering can happen before rendering or serialization.
- Common actions use keywords such as `:index`, `:show`, `:create`, `:update`, and `:destroy`.
- The package is framework-agnostic and can be used with any Kit application code.
## Development
### Running Examples
Run the blog policy example with the interpreter:
```console
kit run examples/blog-policy.kit
```
Compile the example to a native binary:
```console
kit build examples/blog-policy.kit && ./blog-policy
```
### Running Tests
Run the test suite:
```console
kit test
```
Run the test suite with coverage:
```console
kit test --coverage
```
### Running kit dev
Run the standard development workflow (format, check, test):
```console
kit dev
```
This will:
1. Format and check source files in `src/`
2. Type check examples in `examples/`
3. Run tests in `tests/` with coverage
### Checking Interpreter/Compiler Parity
Run parity checks for examples:
```console
kit parity --failures-only
```
### Generating Documentation
Generate API documentation from doc comments:
```console
kit doc
```
**Note**: Kit sources with doc comments (`##`) will generate HTML documents in `docs/*.html`.
### Cleaning Build Artifacts
Remove generated files, caches, and build artifacts:
```console
kit task clean
```
**Note**: Defined in [kit.toml](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/kit.toml).
## Local Installation
To install this package locally for development:
```console
kit install
```
This installs the package to `~/.kit/packages/@kit/policy/`, making it available for import as `Kit.Policy` in other projects.
## License
This package is released under the MIT License - see [LICENSE](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/LICENSE) for details.