
Ein flexibles, zusammensetzbares Autorisierungs-Framework für Kit (inspiriert von Action Policy)
# kit-policy
Ein flexibles, kombinierbares Autorisierungsframework für Kit, inspiriert von Rubys [Action Policy](https://actionpolicy.evilmartians.io/).
---
[TOC]
---
## Dateien
| Datei | Beschreibung |
|------|-------------|
| [`.editorconfig`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.editorconfig) | Editor-Formatierungskonfiguration |
| [`.gitignore`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.gitignore) | Git-Ignore-Regeln für Build-Artefakte und Abhängigkeiten |
| [`.tool-versions`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/.tool-versions) | asdf-Toolversionen (Zig, Kit) |
| [`LICENSE`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/LICENSE) | MIT-Lizenzdatei |
| [`README.md`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/README.md) | Diese Datei |
| [`examples/blog-policy.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/examples/blog-policy.kit) | Blog-Autorisierungsbeispiel |
| [`kit.toml`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/kit.toml) | Paketmanifest mit Metadaten, Aufgaben und Lint-Konfiguration |
| [`src/core.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/core.kit) | Kern-Autorisierungshilfsfunktionen |
| [`src/error.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/error.kit) | Autorisierungsfehler, Ergebnistypen und Fehlerursachen |
| [`src/main.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/main.kit) | Paket-Wurzelmodul |
| [`src/scope.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/src/scope.kit) | Bereichs-, Prädikats- und Paginierungshilfsfunktionen |
| [`tests/policy.test.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/tests/policy.test.kit) | End-to-End-Policy-Verhaltenstests |
| [`tests/types.test.kit`](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/tests/types.test.kit) | Policy-Typ- und Hilfsfunktionstests |
## Abhängigkeiten
_Keine Kit-Paketabhängigkeiten._
## Installation
```console
kit add gitlab.com/kit-lang/packages/kit-policy.git
```
## Verwendung
```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-Übersicht
### Policy.Core
Kern-Hilfsfunktionen für Policy-Funktionen, die `Result Bool PolicyError` zurückgeben.
```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
```
Vorabprüfungs-Hilfsfunktionen geben `Option Bool` zurück: `Some true` erlaubt, `Some false` verweigert und `None` fährt mit der Hauptregel fort.
```kit
PolicyCore.admin-bypass is-admin? ctx
PolicyCore.owner-check is-owner? resource ctx
PolicyCore.first-pre-check [check1, check2, check3]
```
Aktionshilfsfunktionen stellen gängige Aktionsgruppen und Aliase bereit.
```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-Kombinationshilfsfunktionen kombinieren mehrere Autorisierungsergebnisse.
```kit
PolicyCore.all-allowed? [result1, result2, result3]
PolicyCore.any-allowed? [result1, result2, result3]
```
### Policy.Scope
Bereichshilfsfunktionen filtern Sammlungen, bevor Daten an einen Aufrufer zurückgegeben werden.
```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
```
Prädikat-Kombinatoren sind nützlich, um wiederverwendbare Bereichsprüfungen zu erstellen.
```kit
PolicyScope.both? pred1 pred2 item
PolicyScope.either? pred1 pred2 item
PolicyScope.not-matching? pred item
```
Paginierungshilfsfunktionen sind 1-indexiert.
```kit
page1 = PolicyScope.paginate 1 10 items
pages = PolicyScope.total-pages 10 items
info = PolicyScope.pagination-info 1 10 items
```
### Policy.Error
Fehler- und Ergebnistypen für Autorisierungsfehler.
```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
```
Hilfsfunktionen werden aus dem Modul exportiert, sodass sie bei Import als `PolicyError` als Modulfunktionen aufgerufen werden.
```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-Notizen
- Policies sind einfache Funktionen, daher leicht zu testen und zu kombinieren.
- Autorisierung ist explizit: Hilfsfunktionen geben `Result Bool PolicyError` zurück, anstatt Ausnahmen zu werfen.
- Bereiche sind von Policy-Prüfungen getrennt, sodass das Filtern von Listen vor dem Rendern oder Serialisieren erfolgen kann.
- Übliche Aktionen verwenden Schlüsselwörter wie `:index`, `:show`, `:create`, `:update` und `:destroy`.
- Das Paket ist framework-agnostisch und kann in jedem Kit-Anwendungscode verwendet werden.
## Entwicklung
### Beispiele ausführen
Führen Sie das Blog-Policy-Beispiel mit dem Interpreter aus:
```console
kit run examples/blog-policy.kit
```
Kompilieren Sie das Beispiel in ein natives Binary:
```console
kit build examples/blog-policy.kit && ./blog-policy
```
### Tests ausführen
Führen Sie die Testsammlung aus:
```console
kit test
```
Führen Sie die Testsammlung mit Coverage aus:
```console
kit test --coverage
```
### Kit dev ausführen
Führen Sie den standardmäßigen Entwicklungsworkflow aus (Formatieren, Prüfen, Testen):
```console
kit dev
```
Dies wird:
1. Quelldateien in `src/` formatieren und prüfen
2. Beispiele in `examples/` typüberprüfen
3. Tests in `tests/` mit Coverage ausführen
### Interpreter/Compiler-Parität prüfen
Führen Sie Paritätsprüfungen für Beispiele durch:
```console
kit parity --failures-only
```
### Dokumentation generieren
Generieren Sie API-Dokumentation aus Dokumentationskommentaren:
```console
kit doc
```
**Hinweis**: Kit-Quellen mit Dokumentationskommentaren (`##`) generieren HTML-Dokumente in `docs/*.html`.
### Build-Artefakte bereinigen
Entfernen Sie generierte Dateien, Caches und Build-Artefakte:
```console
kit task clean
```
**Hinweis**: Definiert in [kit.toml](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/kit.toml).
## Lokale Installation
Um dieses Paket lokal für die Entwicklung zu installieren:
```console
kit install
```
Dies installiert das Paket nach `~/.kit/packages/@kit/policy/` und macht es für den Import als `Kit.Policy` in anderen Projekten verfügbar.
## Lizenz
Dieses Paket wird unter der MIT-Lizenz veröffentlicht – siehe [LICENSE](https://gitlab.com/kit-lang/packages/kit-policy/-/blob/main/LICENSE) für Details.