feat(auth): initial implementation — authmw and rbac (v1.0.0)
Introduces code.nochebuena.dev/einherjar/auth — the provider-agnostic HTTP
authentication and authorization layer of the Einherjar framework. Absorbs
two micro-lib packages (httpauth, rbac) as sub-packages, replacing the
Identity-only context model with a SecurityBag-native design and adding a
composable enrichment chain.
authmw:
- BagEnricher function type — enriches the request-scoped SecurityBag after
the base Identity is built; registered via WithBagEnricher; multiple
enrichers run in order, each receiving the bag from the previous
- IdentityEnricher interface — application-layer contract for loading user
data from uid+claims
- EnrichmentMiddleware — builds SecurityBag from uid+claims, runs enricher
chain, stores via security.SetBagInContext; 401 on missing uid, 500 on
enricher error; routes all errors through httputil.Error
- AuthzMiddleware — per-route permission gate; 401 on missing identity,
403 on provider error (fail-closed) or insufficient permissions
- EnrichOpt type + WithTenantHeader (reads TenantID from header, implemented
as a BagEnricher) + WithBagEnricher (registers custom enrichers for
hardware IDs, grant codes, or any bag attribute)
- SetTokenData / GetClaims — integration contract for auth-jwt / auth-firebase
rbac:
- NewClaimsPermissionProvider — reads flat JWT claim bitmasks from context;
wildcard "*" fallback; handles int64/float64/json.Number; zero DB calls
- NewCachedPermissionProvider — TTL cache wrapping any PermissionProvider;
default key "rbac:{uid}:{resource}" or "rbac:{tenantID}:{uid}:{resource}";
TenantID sourced from SecurityBag automatically; accepts ...CachedOpt
- CachedOpt type + WithCacheKey — overrides the key function for extra
dimensions (hardware IDs, grant codes read from bag attributes)
- NewChainPermissionProvider — tries providers in order; first non-zero wins;
errors short-circuit; typical pattern: claims → cached DB fallback
- Cache interface — pluggable backend satisfied by cache-valkey via duck typing
Compliance test (package auth_test) enforces CT-6 (≤1 exported TypeSpec/file),
compile-time interface satisfaction, and behavioural coverage across the full
middleware and provider surface: enrichment success/failure, tenant header,
custom BagEnricher, bag-in-context, authz allowed/denied/error, claims
hit/wildcard/missing/float64, cached hit/miss/error/tenant-key/custom-key,
chain first-non-zero/fallthrough/error.
Depends on contracts v1.0.0, core v1.0.0, web v1.0.0.
- identifiable.go: package-level Module variable (observability.Identifiable) for version
identification — auth is middleware-only; not registered with the launcher
This commit is contained in:
1
.gitea/CODEOWNERS
Normal file
1
.gitea/CODEOWNERS
Normal file
@@ -0,0 +1 @@
|
|||||||
|
* @einherjar/CoreDevelopers @einherjar/Agents
|
||||||
70
.gitea/pull_request_template.md
Normal file
70
.gitea/pull_request_template.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
## Summary
|
||||||
|
|
||||||
|
<!-- One or two sentences: what does this PR do and why? -->
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Type of change
|
||||||
|
|
||||||
|
- [ ] Bug fix — non-breaking change that resolves an issue
|
||||||
|
- [ ] New feature — non-breaking addition of functionality
|
||||||
|
- [ ] Breaking change — alters existing behavior or public API
|
||||||
|
- [ ] Documentation update
|
||||||
|
- [ ] Refactor — no functional change, no new API surface
|
||||||
|
- [ ] Test improvement
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Provide enough context for a reviewer who was not in the room:
|
||||||
|
- What problem does this solve?
|
||||||
|
- What approach did you choose, and why?
|
||||||
|
- Were there alternatives you considered and rejected?
|
||||||
|
- Any known limitations or follow-up work?
|
||||||
|
-->
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- [ ] I added or updated tests that cover my changes
|
||||||
|
- [ ] All tests pass locally — `go test ./...`
|
||||||
|
- [ ] No formatting issues — `gofmt -l .` produces no output
|
||||||
|
- [ ] No vet warnings — `go vet ./...` is clean
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] At most one exported type per non-test `.go` file (CT-6)
|
||||||
|
- [ ] No new external dependencies added without prior discussion in an issue
|
||||||
|
- [ ] Public API changes are reflected in `CHANGELOG.md`
|
||||||
|
- [ ] Breaking changes include a migration note in the PR description above
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contributor License Agreement
|
||||||
|
|
||||||
|
> **This PR will not be merged until the CLA comment is present.**
|
||||||
|
|
||||||
|
Before a Maintainer reviews your code, you must post the following text **as a comment on this PR** — not here in the description. PR description checkboxes can be silently toggled by anyone; a comment is a timestamped, author-attributed record that cannot be quietly removed.
|
||||||
|
|
||||||
|
**Copy and post this exact text as a PR comment:**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||||
|
> I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||||
|
> therein, including the right to relicense, and I retain ownership of my copyright.
|
||||||
|
> This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||||
|
> this account.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
First time contributing? Read [CLA.md](../CLA.md) for the full agreement before posting the comment.
|
||||||
|
|
||||||
|
If you are contributing on behalf of a company, an authorized representative of that company must post the comment.
|
||||||
|
|
||||||
|
<!-- Thank you for contributing to Einherjar. For those who come after. -->
|
||||||
38
.gitignore
vendored
Normal file
38
.gitignore
vendored
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# ── Release workflow helpers ──────────────────────────────────────────────────
|
||||||
|
COMMIT.md
|
||||||
|
PR.md
|
||||||
|
RELEASE.md
|
||||||
|
|
||||||
|
# ── Go build artifacts ────────────────────────────────────────────────────────
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
|
/dist/
|
||||||
|
/bin/
|
||||||
|
|
||||||
|
# ── Go workspace (local development only) ────────────────────────────────────
|
||||||
|
go.work
|
||||||
|
go.work.sum
|
||||||
|
|
||||||
|
# ── Dependency vendor directory ───────────────────────────────────────────────
|
||||||
|
vendor/
|
||||||
|
|
||||||
|
# ── Coverage output ───────────────────────────────────────────────────────────
|
||||||
|
coverage.out
|
||||||
|
coverage.html
|
||||||
|
*.coverprofile
|
||||||
|
|
||||||
|
# ── OS artifacts ─────────────────────────────────────────────────────────────
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# ── Editor artifacts ──────────────────────────────────────────────────────────
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
47
CHANGELOG.md
Normal file
47
CHANGELOG.md
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## v1.0.0
|
||||||
|
|
||||||
|
Initial release.
|
||||||
|
|
||||||
|
### `authmw`
|
||||||
|
|
||||||
|
- `BagEnricher` type — `func(bag security.SecurityBag, r *http.Request) security.SecurityBag`;
|
||||||
|
enriches the request-scoped SecurityBag after the base Identity is built. Register via
|
||||||
|
`WithBagEnricher`. Multiple enrichers run in registration order, each receiving the bag
|
||||||
|
returned by the previous one.
|
||||||
|
- `SetTokenData` — integration contract for provider packages (auth-jwt, auth-firebase).
|
||||||
|
Stores uid and raw claims in context via typed keys; consumed by `EnrichmentMiddleware`.
|
||||||
|
- `GetClaims` — exported accessor for raw token claims stored by `SetTokenData`. Available
|
||||||
|
to custom `IdentityEnricher` implementations and `ClaimsPermissionProvider`.
|
||||||
|
- `EnrichmentMiddleware` — builds a `security.SecurityBag` from uid+claims. Calls the
|
||||||
|
application `IdentityEnricher`, wraps the Identity in a SecurityBag, runs all registered
|
||||||
|
`BagEnricher` functions in order, then stores the bag via `security.SetBagInContext`.
|
||||||
|
Accepts `logging.Logger`; routes errors through `httputil.Error` (401 on missing token,
|
||||||
|
500 on enricher failure).
|
||||||
|
- `AuthzMiddleware` — per-route permission gate. Returns 401 on missing identity, 403 on
|
||||||
|
provider error or insufficient permissions (fail-closed).
|
||||||
|
- `IdentityEnricher` interface — implemented by the application to load user data from uid+claims.
|
||||||
|
- `EnrichOpt` type — `func(*enrichConfig)`.
|
||||||
|
- `WithTenantHeader(header string) EnrichOpt` — reads Identity.TenantID from a named request
|
||||||
|
header. Implemented as a `BagEnricher` internally.
|
||||||
|
- `WithBagEnricher(fn BagEnricher) EnrichOpt` — registers a custom enricher. Use for any
|
||||||
|
attribute beyond TenantID: hardware IDs, grant codes, etc.
|
||||||
|
|
||||||
|
### `rbac`
|
||||||
|
|
||||||
|
- `NewClaimsPermissionProvider` — reads pre-computed bitmasks from JWT claims in context.
|
||||||
|
Flat format: `claims[claimsKey][resource] = mask`. Wildcard `"*"` fallback.
|
||||||
|
Handles int64, float64, json.Number.
|
||||||
|
- `NewCachedPermissionProvider` — wraps any `security.PermissionProvider` with TTL caching.
|
||||||
|
Default cache key: `"rbac:{uid}:{resource}"` (single-tenant) or
|
||||||
|
`"rbac:{tenantID}:{uid}:{resource}"` (multi-tenant). TenantID sourced from the SecurityBag
|
||||||
|
in context automatically. Accepts `...CachedOpt` for customization.
|
||||||
|
- `CachedOpt` type — `func(*cachedConfig)`.
|
||||||
|
- `WithCacheKey(fn func(security.SecurityBag, string, string) string) CachedOpt` — overrides
|
||||||
|
the default cache key function. Use when additional bag attributes (hardware IDs, grant codes)
|
||||||
|
must be part of the key.
|
||||||
|
- `NewChainPermissionProvider` — tries providers in order; returns first non-zero mask. Errors
|
||||||
|
short-circuit.
|
||||||
|
- `Cache` interface — pluggable cache backend. Satisfied by `einherjar/cache-valkey` via duck
|
||||||
|
typing.
|
||||||
90
CLA.md
Normal file
90
CLA.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Contributor License Agreement
|
||||||
|
|
||||||
|
By contributing to any Einherjar repository, you agree to the terms of this Contributor License Agreement ("Agreement"). Please read it carefully before submitting your first Pull Request.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Definitions
|
||||||
|
|
||||||
|
| Term | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| **You** | The individual or legal entity submitting a Contribution |
|
||||||
|
| **Contribution** | Any original work — source code, documentation, tests, configuration — submitted to an Einherjar repository |
|
||||||
|
| **Project** | The Einherjar framework and all repositories under `code.nochebuena.dev/einherjar/` |
|
||||||
|
| **Maintainers** | The individuals responsible for maintaining the Project |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. You Retain Ownership
|
||||||
|
|
||||||
|
This Agreement does **not** transfer your copyright to the Maintainers. You remain the legal owner of your Contribution. What you grant here is a broad license to use it — not ownership of it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Copyright License Grant
|
||||||
|
|
||||||
|
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** license to:
|
||||||
|
|
||||||
|
- Reproduce, modify, and create derivative works of your Contribution
|
||||||
|
- Publicly display and perform your Contribution
|
||||||
|
- Distribute your Contribution and derivative works, in source or compiled form, under any terms
|
||||||
|
- Sublicense the above rights to third parties
|
||||||
|
- **Relicense** your Contribution under a different open-source or commercial license at the Maintainers' sole discretion
|
||||||
|
|
||||||
|
The Maintainers commit to keeping the Project available under at least one OSI-approved open-source license at all times.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Patent License Grant
|
||||||
|
|
||||||
|
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** patent license to make, use, sell, offer for sale, import, and distribute your Contribution — limited to patent claims you own or control that are necessarily infringed by your Contribution alone, or in combination with the Project to which you submitted it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Your Representations
|
||||||
|
|
||||||
|
By submitting a Contribution, you confirm that:
|
||||||
|
|
||||||
|
1. **Original work.** The Contribution is your original work, or you have the legal right to submit it under these terms.
|
||||||
|
2. **No infringement.** To your knowledge, the Contribution does not infringe any third-party intellectual property rights, including patents, copyrights, and trade secrets.
|
||||||
|
3. **Employer rights.** If your employer holds rights over intellectual property you create, you have obtained written permission to submit the Contribution on behalf of that employer, or your employer has explicitly waived such rights for contributions to open-source projects.
|
||||||
|
4. **No warranty implied.** You understand that your Contribution may or may not be included in the Project, and the Maintainers are under no obligation to use it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. No Support Obligation
|
||||||
|
|
||||||
|
You are not required to provide maintenance, support, or updates for your Contributions. They are accepted **"as-is"**, without any warranty of fitness for a particular purpose or correctness.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. How to Sign
|
||||||
|
|
||||||
|
Consent is given by **posting a comment** on your Pull Request with the following exact text:
|
||||||
|
|
||||||
|
```
|
||||||
|
I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||||
|
I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||||
|
therein, including the right to relicense, and I retain ownership of my copyright.
|
||||||
|
This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||||
|
this account.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why a comment and not a checkbox?**
|
||||||
|
PR description checkboxes can be silently toggled on and off by anyone with write access to the branch at any time. A comment creates a timestamped, author-attributed record in the PR activity log — it cannot be quietly retracted. If a comment is deleted, the deletion itself is visible in the activity log.
|
||||||
|
|
||||||
|
No handwritten or electronic signature is required beyond the comment above. A Maintainer will verify the comment before merging. PRs without the comment will not be merged.
|
||||||
|
|
||||||
|
If you are contributing on behalf of a company or organization, ensure that an authorized representative of that entity has reviewed and accepted these terms before submitting. The comment must be posted by the account that owns the Contribution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Governing Terms
|
||||||
|
|
||||||
|
This Agreement is intended to be simple and broadly fair. It follows the model established by widely adopted CLAs from the Apache Software Foundation, Google, and MongoDB — granting the Project the flexibility to evolve while fully preserving your ownership of what you wrote.
|
||||||
|
|
||||||
|
If any provision of this Agreement is found unenforceable, the remaining provisions continue in full effect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*For those who come after. — The Einherjar Maintainers*
|
||||||
247
CONTRIBUTING.md
Normal file
247
CONTRIBUTING.md
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
# Contributing to Einherjar
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to Einherjar. This document explains everything you need to know before sending your first Pull Request.
|
||||||
|
|
||||||
|
Einherjar is developed and maintained by **NOCHEBUENADEV**, the trade name of its founder operating as a *Persona Física con Actividad Empresarial* (PFAE) under Mexican law. Contributions are welcome and valued — but they are accepted under the terms described here, so please read this document fully before you begin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Before You Start](#1-before-you-start)
|
||||||
|
2. [Legal: CLA and Copyright](#2-legal-cla-and-copyright)
|
||||||
|
3. [Development Setup](#3-development-setup)
|
||||||
|
4. [Code Standards](#4-code-standards)
|
||||||
|
5. [Commit Messages](#5-commit-messages)
|
||||||
|
6. [Submitting a Pull Request](#6-submitting-a-pull-request)
|
||||||
|
7. [Reporting Bugs](#7-reporting-bugs)
|
||||||
|
8. [Requesting Features](#8-requesting-features)
|
||||||
|
9. [What Gets Accepted](#9-what-gets-accepted)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Before You Start
|
||||||
|
|
||||||
|
**Open an issue first for anything non-trivial.**
|
||||||
|
|
||||||
|
Before you write a line of code, open an issue describing what you want to change and why. This protects your time: a change that seems straightforward may conflict with a planned refactor, an architectural decision, or the project's direction. Getting alignment before coding means your PR will not be rejected for reasons unrelated to its quality.
|
||||||
|
|
||||||
|
Exceptions where you can skip the issue:
|
||||||
|
- Typo or documentation-only fix
|
||||||
|
- Test coverage improvement for existing behavior
|
||||||
|
- Trivially obvious bug with a clear, contained fix
|
||||||
|
|
||||||
|
**Do not submit a PR that changes the public API of any module without prior discussion.** Every Einherjar module has a stability contract. Breaking changes require a major version bump and coordinated updates across dependent modules.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Legal: CLA and Copyright
|
||||||
|
|
||||||
|
### Contributor License Agreement
|
||||||
|
|
||||||
|
Before your first PR can be merged, you must sign the Contributor License Agreement by **posting a specific comment** on your Pull Request. The required comment text and full instructions are in [CLA.md](CLA.md).
|
||||||
|
|
||||||
|
> Checkboxes in PR descriptions are not used for CLA consent — they can be silently toggled by anyone. A comment is a timestamped, author-attributed record.
|
||||||
|
|
||||||
|
### Copyright
|
||||||
|
|
||||||
|
All original code in Einherjar is copyright **NOCHEBUENADEV**. NOCHEBUENADEV is the registered trade name of its founder, a natural person operating under the Mexican *Persona Física con Actividad Empresarial* (PFAE) regime.
|
||||||
|
|
||||||
|
When you contribute, you retain ownership of what you wrote. By signing the CLA you grant NOCHEBUENADEV a perpetual, irrevocable, worldwide license to use, modify, sublicense, and redistribute your Contribution — including the right to relicense it. See [CLA.md](CLA.md) for the full terms.
|
||||||
|
|
||||||
|
### License
|
||||||
|
|
||||||
|
Einherjar is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). Your Contributions will be distributed under the same license unless the Maintainers exercise their relicensing rights under the CLA.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Development Setup
|
||||||
|
|
||||||
|
Einherjar uses a Go workspace (`go.work`) that spans all modules. You do not need to `go get` anything — local replacements are wired automatically.
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Go 1.26+
|
||||||
|
- Git
|
||||||
|
|
||||||
|
### Clone and initialize
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://code.nochebuena.dev/einherjar/<module-name>
|
||||||
|
cd <module-name>
|
||||||
|
|
||||||
|
# If working across multiple modules, clone the workspace root instead
|
||||||
|
# and all modules will resolve from disk via go.work.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verify your setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build ./... # must compile clean
|
||||||
|
go vet ./... # no warnings
|
||||||
|
go test ./... # all tests pass
|
||||||
|
gofmt -l . # no output (no unformatted files)
|
||||||
|
```
|
||||||
|
|
||||||
|
All four commands must produce clean output before a PR will be reviewed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Code Standards
|
||||||
|
|
||||||
|
These are non-negotiable. Every PR is checked against them.
|
||||||
|
|
||||||
|
### One exported type per file (CT-6)
|
||||||
|
|
||||||
|
Each non-test `.go` file may contain **at most one exported TypeSpec** (type, struct, or interface declaration). Unexported helpers, constants, and functions may coexist in the same file. `_test.go` files are exempt.
|
||||||
|
|
||||||
|
This rule exists to keep the codebase navigable: a developer who knows the type name can immediately predict the file name.
|
||||||
|
|
||||||
|
```
|
||||||
|
provider.go ← type Provider interface { ... } ✓ one exported type
|
||||||
|
component.go ← type Component interface { ... } ✓ one exported type
|
||||||
|
new.go ← func New(...) + unexported impl ✓ zero exported types
|
||||||
|
```
|
||||||
|
|
||||||
|
### Formatting
|
||||||
|
|
||||||
|
All code must be formatted with `gofmt`. No exceptions. If `gofmt -l .` produces output, the PR will not be merged.
|
||||||
|
|
||||||
|
Do not configure your editor to use `goimports` as a replacement — it may add import groups that diverge from the project style. Use `gofmt` + manual import management.
|
||||||
|
|
||||||
|
### Naming conventions
|
||||||
|
|
||||||
|
- Follow standard Go naming: `CamelCase` for exported, `camelCase` for unexported.
|
||||||
|
- Interfaces that represent a capability are named with an agent noun: `Provider`, `Sender`, `Checkable`.
|
||||||
|
- Interfaces that represent a full component are named `Component`.
|
||||||
|
- Config structs are named `Config`. One config struct per module root.
|
||||||
|
- Constructors are named `New` (main) or `NewXxx` (adapters and variants).
|
||||||
|
|
||||||
|
### Error handling
|
||||||
|
|
||||||
|
- Use `core/xerrors` for all errors returned from public API. Never return raw `errors.New` or `fmt.Errorf` from exported functions.
|
||||||
|
- Error codes must map to the gRPC canonical set defined in `xerrors`. If you need a new code, open an issue first.
|
||||||
|
- Do not swallow errors silently. Log at the appropriate level or return them.
|
||||||
|
|
||||||
|
### No comments unless necessary
|
||||||
|
|
||||||
|
Do not add comments that restate what the code already says. Only add a comment when the **why** is non-obvious: a hidden constraint, a subtle invariant, a workaround for a known upstream bug. If removing the comment would not confuse a future reader, do not write it.
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
|
|
||||||
|
Do not add new external dependencies without opening an issue and getting explicit approval first. Einherjar modules are deliberately lean. Every new dependency increases the blast radius for downstream consumers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Commit Messages
|
||||||
|
|
||||||
|
Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>(<scope>): <short description>
|
||||||
|
|
||||||
|
[optional body]
|
||||||
|
```
|
||||||
|
|
||||||
|
| Type | When to use |
|
||||||
|
|---|---|
|
||||||
|
| `feat` | New exported function, type, or behavior |
|
||||||
|
| `fix` | Bug fix in existing behavior |
|
||||||
|
| `docs` | Documentation only |
|
||||||
|
| `test` | Tests only, no production code change |
|
||||||
|
| `refactor` | Code restructure with no behavior change |
|
||||||
|
| `chore` | Build system, CI, dependency updates |
|
||||||
|
|
||||||
|
**Scope** is the module name without the `einherjar/` prefix: `core`, `web`, `db-postgres`, `cache-valkey`, etc.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
```
|
||||||
|
feat(cache-valkey): add IncrWithTTL for atomic fixed-window counters
|
||||||
|
fix(db-postgres): handle pgconn deadline exceeded as ErrDeadlineExceeded
|
||||||
|
docs(web): document rate limiter fail-open behavior
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep the subject line under 72 characters. Write in the imperative mood ("add", "fix", "remove" — not "added", "fixes", "removed").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Submitting a Pull Request
|
||||||
|
|
||||||
|
1. **Open an issue first** (see §1) unless the change is trivial.
|
||||||
|
2. Fork the repository and create a branch from `main`:
|
||||||
|
```bash
|
||||||
|
git checkout -b feat/your-feature-name
|
||||||
|
```
|
||||||
|
3. Make your changes following the standards in §4.
|
||||||
|
4. Ensure all verification commands pass (§3).
|
||||||
|
5. Open the PR against `main` using the provided PR template.
|
||||||
|
6. **Post the CLA comment** on the PR before requesting review (see §2 and [CLA.md](CLA.md)).
|
||||||
|
7. Respond to review feedback. Keep the review cycle short by addressing all comments before re-requesting review.
|
||||||
|
|
||||||
|
### Branch naming
|
||||||
|
|
||||||
|
| Prefix | Use for |
|
||||||
|
|---|---|
|
||||||
|
| `feat/` | New features |
|
||||||
|
| `fix/` | Bug fixes |
|
||||||
|
| `docs/` | Documentation changes |
|
||||||
|
| `test/` | Test additions or improvements |
|
||||||
|
| `refactor/` | Refactors without behavior change |
|
||||||
|
|
||||||
|
### PR size
|
||||||
|
|
||||||
|
Keep PRs focused. A PR that does one thing is easier to review, faster to merge, and safer to revert if needed. If your change naturally spans multiple concerns, split it into multiple PRs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Reporting Bugs
|
||||||
|
|
||||||
|
Open an issue with the following information:
|
||||||
|
|
||||||
|
- **Module** affected (`einherjar/db-postgres`, `einherjar/web`, etc.)
|
||||||
|
- **Go version** (`go version`)
|
||||||
|
- **Minimal reproduction** — the smallest code snippet that demonstrates the problem
|
||||||
|
- **Expected behavior** vs **actual behavior**
|
||||||
|
- **Error output** if applicable (sanitize any credentials or sensitive data)
|
||||||
|
|
||||||
|
Do not open a PR to fix a bug without first opening an issue. The bug may be intentional behavior, already fixed on `main`, or caused by something outside the module.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Requesting Features
|
||||||
|
|
||||||
|
Open an issue with:
|
||||||
|
|
||||||
|
- **What** you want to add and **why** it belongs in the framework (not in application code)
|
||||||
|
- **Which module** it affects, or whether it requires a new module
|
||||||
|
- **API sketch** — what the interface, function signature, or config field would look like
|
||||||
|
- **Alternative approaches** you considered
|
||||||
|
|
||||||
|
Feature requests that add a new external dependency, change a public interface, or cross module boundaries require longer discussion before approval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. What Gets Accepted
|
||||||
|
|
||||||
|
Einherjar is a **focused framework**. It covers a specific, well-defined set of infrastructure concerns. Contributions that fall outside that scope — however well-written — will not be merged.
|
||||||
|
|
||||||
|
What fits:
|
||||||
|
- Bug fixes in existing behavior
|
||||||
|
- Performance improvements with benchmarks
|
||||||
|
- Missing error mappings for existing drivers
|
||||||
|
- Documentation improvements and example corrections
|
||||||
|
- Test coverage for untested edge cases
|
||||||
|
|
||||||
|
What does not fit without prior architectural agreement:
|
||||||
|
- New modules (open an issue first)
|
||||||
|
- New external dependencies
|
||||||
|
- Changes to public interfaces in any module
|
||||||
|
- Features that belong in application code rather than the framework
|
||||||
|
|
||||||
|
If you are unsure, open an issue and ask. It costs nothing and saves everyone time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Einherjar was built for those who come after. Contributions that hold to that standard — clear, documented, tested, designed for the developer who was never in the room — are always welcome.*
|
||||||
|
|
||||||
|
— **NOCHEBUENADEV**
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
132
README.md
Normal file
132
README.md
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
# einherjar/auth
|
||||||
|
|
||||||
|
[](https://code.nochebuena.dev/einherjar/auth)
|
||||||
|
[](LICENSE)
|
||||||
|
[](https://go.dev)
|
||||||
|
|
||||||
|
> Not every warrior who knocks at the gate deserves to pass. The Valkyries choose.
|
||||||
|
|
||||||
|
Provider-agnostic HTTP authentication and authorization middleware for the Einherjar framework.
|
||||||
|
|
||||||
|
## Sub-packages
|
||||||
|
|
||||||
|
| Package | Description |
|
||||||
|
|---|---|
|
||||||
|
| [`authmw`](authmw/) | HTTP middleware: `EnrichmentMiddleware`, `AuthzMiddleware`, `SetTokenData`, `BagEnricher` |
|
||||||
|
| [`rbac`](rbac/) | Permission providers: `ClaimsPermissionProvider`, `CachedPermissionProvider`, `ChainPermissionProvider` |
|
||||||
|
|
||||||
|
## Dependency graph
|
||||||
|
|
||||||
|
```
|
||||||
|
contracts/security ──► auth/authmw ──► auth/rbac
|
||||||
|
contracts/security ──► auth/rbac
|
||||||
|
core/xerrors ──► auth/authmw
|
||||||
|
web/httputil ──► auth/authmw
|
||||||
|
```
|
||||||
|
|
||||||
|
No external dependencies.
|
||||||
|
|
||||||
|
## Wiring example
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"code.nochebuena.dev/einherjar/auth/authmw"
|
||||||
|
"code.nochebuena.dev/einherjar/auth/rbac"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Application implements IdentityEnricher to load user data.
|
||||||
|
enricher := userservice.NewIdentityEnricher(userRepo)
|
||||||
|
|
||||||
|
// Build permission resolution chain.
|
||||||
|
permissions := rbac.NewChainPermissionProvider(
|
||||||
|
rbac.NewClaimsPermissionProvider("perms"), // JWT fast-path
|
||||||
|
rbac.NewCachedPermissionProvider(dbProvider, valkeyCache, 5*time.Minute), // DB fallback
|
||||||
|
)
|
||||||
|
|
||||||
|
// Provider AuthMiddleware (from auth-jwt or auth-firebase) goes first.
|
||||||
|
// Then enrichment globally:
|
||||||
|
srv.Use(authmw.EnrichmentMiddleware(logger, enricher,
|
||||||
|
authmw.WithTenantHeader("X-Tenant-ID"),
|
||||||
|
))
|
||||||
|
|
||||||
|
// Per-route authorization:
|
||||||
|
const ReadOrders = security.Permission(0)
|
||||||
|
srv.With(authmw.AuthzMiddleware(logger, permissions, "orders", ReadOrders)).
|
||||||
|
Get("/orders", ordersHandler)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom enrichment
|
||||||
|
|
||||||
|
`BagEnricher` lets you attach any request attribute to the `SecurityBag` in context.
|
||||||
|
Permission providers read it via `bag.Get(key)` — no scattered context keys.
|
||||||
|
|
||||||
|
```go
|
||||||
|
const KeyHardwareID = "hardware_id" // owned by your package; document the value type
|
||||||
|
|
||||||
|
hwEnricher := authmw.BagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
|
||||||
|
return bag.With(KeyHardwareID, r.Header.Get("X-Hardware-ID"))
|
||||||
|
})
|
||||||
|
|
||||||
|
srv.Use(authmw.EnrichmentMiddleware(logger, enricher,
|
||||||
|
authmw.WithTenantHeader("X-Tenant-ID"),
|
||||||
|
authmw.WithBagEnricher(hwEnricher),
|
||||||
|
))
|
||||||
|
```
|
||||||
|
|
||||||
|
With a hardware-ID-bound permission model, override the cache key so the hardware ID
|
||||||
|
is included — otherwise two hardware IDs for the same user share a cache entry:
|
||||||
|
|
||||||
|
```go
|
||||||
|
cached := rbac.NewCachedPermissionProvider(dbProvider, cache, 5*time.Minute,
|
||||||
|
rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
|
||||||
|
hwID, _ := bag.Get(KeyHardwareID)
|
||||||
|
return fmt.Sprintf("rbac:%s:%s:%v:%s", bag.Identity().TenantID, uid, hwID, resource)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multi-tenant
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Read TenantID from header; CachedPermissionProvider scopes keys automatically.
|
||||||
|
srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID")))
|
||||||
|
```
|
||||||
|
|
||||||
|
- JWT carries "who are you" only — no per-tenant permission claims required
|
||||||
|
- `WithTenantHeader` populates `security.Identity.TenantID` from the request
|
||||||
|
- `CachedPermissionProvider` uses `"rbac:{tenantID}:{uid}:{resource}"` when TenantID is non-empty
|
||||||
|
|
||||||
|
## Permission model
|
||||||
|
|
||||||
|
Permissions are a 63-bit set (`security.Permission(0)` through `security.MaxPermission`).
|
||||||
|
Define application permissions as constants:
|
||||||
|
|
||||||
|
```go
|
||||||
|
const (
|
||||||
|
Read = security.Permission(0)
|
||||||
|
Write = security.Permission(1)
|
||||||
|
Delete = security.Permission(2)
|
||||||
|
Admin = security.Permission(3)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Issue tokens with embedded masks (via auth-jwt):
|
||||||
|
|
||||||
|
```go
|
||||||
|
customClaims := map[string]any{
|
||||||
|
"perms": map[string]any{
|
||||||
|
"orders": int64(security.PermissionMask(0).Grant(Read).Grant(Write)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
None. Auth middleware is wired in code, not configured via environment.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go get code.nochebuena.dev/einherjar/auth@v1.0.0
|
||||||
|
```
|
||||||
38
authmw/authz.go
Normal file
38
authmw/authz.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||||
|
"code.nochebuena.dev/einherjar/web/httputil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AuthzMiddleware gates the request against a single required permission on a named resource.
|
||||||
|
// Returns 401 if no identity is in context; 403 if the permission check fails or the
|
||||||
|
// provider returns an error (fail-closed: provider failure denies access).
|
||||||
|
func AuthzMiddleware(logger logging.Logger, provider security.PermissionProvider, resource string, required security.Permission) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
identity, ok := security.FromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
httputil.Error(logger, w, r, xerrors.Unauthorized("missing identity"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
mask, err := provider.ResolveMask(r.Context(), identity.UID, resource)
|
||||||
|
if err != nil {
|
||||||
|
httputil.Error(logger, w, r, xerrors.PermissionDenied("permission check failed").WithError(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !mask.Has(required) {
|
||||||
|
httputil.Error(logger, w, r, xerrors.PermissionDenied("insufficient permissions"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
20
authmw/bag_enricher.go
Normal file
20
authmw/bag_enricher.go
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BagEnricher enriches the request-scoped SecurityBag.
|
||||||
|
//
|
||||||
|
// Called sequentially by [EnrichmentMiddleware] after the base Identity is
|
||||||
|
// built from uid+claims. Each enricher receives the current bag and must
|
||||||
|
// return a new bag — the receiver is never modified.
|
||||||
|
//
|
||||||
|
// Typical uses: setting TenantID from a request header, attaching a hardware
|
||||||
|
// ID to the bag, injecting a grant code from an out-of-band lookup.
|
||||||
|
//
|
||||||
|
// Register enrichers via [WithBagEnricher]. [WithTenantHeader] is a
|
||||||
|
// convenience constructor for the most common single-header case.
|
||||||
|
type BagEnricher func(bag security.SecurityBag, r *http.Request) security.SecurityBag
|
||||||
44
authmw/doc.go
Normal file
44
authmw/doc.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
// Package authmw provides provider-agnostic HTTP authentication and authorization
|
||||||
|
// middleware for the Einherjar framework.
|
||||||
|
//
|
||||||
|
// The middleware chain follows a three-step pattern:
|
||||||
|
//
|
||||||
|
// 1. A provider-specific AuthMiddleware (from auth-jwt or auth-firebase) verifies
|
||||||
|
// the token and calls [SetTokenData] to store uid and claims in the request context.
|
||||||
|
//
|
||||||
|
// 2. [EnrichmentMiddleware] reads uid+claims, calls the application-provided
|
||||||
|
// [IdentityEnricher] to build a [security.Identity], wraps it in a
|
||||||
|
// [security.SecurityBag], runs any registered [BagEnricher] functions to attach
|
||||||
|
// extra attributes (tenant ID, hardware IDs, grant codes), and stores the bag
|
||||||
|
// in context via [security.SetBagInContext].
|
||||||
|
//
|
||||||
|
// 3. [AuthzMiddleware] — mounted per route — reads the identity from context and
|
||||||
|
// checks the required permission against a [security.PermissionProvider].
|
||||||
|
//
|
||||||
|
// # Typical wiring
|
||||||
|
//
|
||||||
|
// enricher := userservice.NewIdentityEnricher(userRepo)
|
||||||
|
//
|
||||||
|
// // Provider AuthMiddleware is added first (from auth-jwt or auth-firebase).
|
||||||
|
// // Then, globally:
|
||||||
|
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher))
|
||||||
|
//
|
||||||
|
// // Per route:
|
||||||
|
// const Read = security.Permission(0)
|
||||||
|
// srv.With(authmw.AuthzMiddleware(logger, permProvider, "orders", Read)).
|
||||||
|
// Get("/orders", ordersHandler)
|
||||||
|
//
|
||||||
|
// # Multi-tenant
|
||||||
|
//
|
||||||
|
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID")))
|
||||||
|
//
|
||||||
|
// # Custom bag enrichment
|
||||||
|
//
|
||||||
|
// const KeyHardwareID = "hardware_id"
|
||||||
|
//
|
||||||
|
// hwEnricher := authmw.BagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
|
||||||
|
// return bag.With(KeyHardwareID, r.Header.Get("X-Hardware-ID"))
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithBagEnricher(hwEnricher)))
|
||||||
|
package authmw
|
||||||
38
authmw/enrich_opt.go
Normal file
38
authmw/enrich_opt.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EnrichOpt configures [EnrichmentMiddleware] behaviour.
|
||||||
|
type EnrichOpt func(*enrichConfig)
|
||||||
|
|
||||||
|
// WithTenantHeader reads the TenantID from the named request header and
|
||||||
|
// applies it to the Identity inside the bag via [security.Identity.WithTenant].
|
||||||
|
//
|
||||||
|
// Equivalent to registering a [BagEnricher] that calls
|
||||||
|
// bag.WithIdentity(bag.Identity().WithTenant(r.Header.Get(header))).
|
||||||
|
// Use for multi-tenant deployments where the tenant is identified per request.
|
||||||
|
func WithTenantHeader(header string) EnrichOpt {
|
||||||
|
return WithBagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
|
||||||
|
if tenantID := r.Header.Get(header); tenantID != "" {
|
||||||
|
return bag.WithIdentity(bag.Identity().WithTenant(tenantID))
|
||||||
|
}
|
||||||
|
return bag
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithBagEnricher appends fn to the enrichment chain.
|
||||||
|
// Enrichers run in registration order after the base Identity is built.
|
||||||
|
// Each enricher receives the bag returned by the previous one.
|
||||||
|
//
|
||||||
|
// Use this for any enrichment that does not fit [WithTenantHeader]:
|
||||||
|
// attaching hardware IDs, grant codes, or any attribute that downstream
|
||||||
|
// permission providers need to read from the bag.
|
||||||
|
func WithBagEnricher(fn BagEnricher) EnrichOpt {
|
||||||
|
return func(c *enrichConfig) {
|
||||||
|
c.enrichers = append(c.enrichers, fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
56
authmw/enrichment.go
Normal file
56
authmw/enrichment.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||||
|
"code.nochebuena.dev/einherjar/web/httputil"
|
||||||
|
)
|
||||||
|
|
||||||
|
type enrichConfig struct {
|
||||||
|
enrichers []BagEnricher
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnrichmentMiddleware builds a [security.SecurityBag] from the uid and claims
|
||||||
|
// injected by an upstream provider AuthMiddleware via [SetTokenData], then runs
|
||||||
|
// all registered [BagEnricher] functions in order.
|
||||||
|
//
|
||||||
|
// Returns 401 if no uid is present in context; 500 if the application
|
||||||
|
// [IdentityEnricher] returns an error.
|
||||||
|
//
|
||||||
|
// The resulting bag is stored via [security.SetBagInContext]. Downstream
|
||||||
|
// handlers can retrieve it with [security.BagFromContext] (full bag) or
|
||||||
|
// [security.FromContext] (Identity only).
|
||||||
|
func EnrichmentMiddleware(logger logging.Logger, enricher IdentityEnricher, opts ...EnrichOpt) func(http.Handler) http.Handler {
|
||||||
|
cfg := &enrichConfig{}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uid, ok := getUID(r.Context())
|
||||||
|
if !ok {
|
||||||
|
httputil.Error(logger, w, r, xerrors.Unauthorized("missing token"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := getClaims(r.Context())
|
||||||
|
identity, err := enricher.Enrich(r.Context(), uid, claims)
|
||||||
|
if err != nil {
|
||||||
|
httputil.Error(logger, w, r, xerrors.Internal("enrichment failed").WithError(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
bag := security.NewSecurityBag(identity)
|
||||||
|
for _, fn := range cfg.enrichers {
|
||||||
|
bag = fn(bag, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := security.SetBagInContext(r.Context(), bag)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
14
authmw/identity_enricher.go
Normal file
14
authmw/identity_enricher.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IdentityEnricher is implemented by the application layer to load user data
|
||||||
|
// from token claims and return a populated security.Identity.
|
||||||
|
// Called once per request by EnrichmentMiddleware after token verification.
|
||||||
|
type IdentityEnricher interface {
|
||||||
|
Enrich(ctx context.Context, uid string, claims map[string]any) (security.Identity, error)
|
||||||
|
}
|
||||||
30
authmw/token.go
Normal file
30
authmw/token.go
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package authmw
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type ctxUIDKey struct{}
|
||||||
|
type ctxClaimsKey struct{}
|
||||||
|
|
||||||
|
// SetTokenData stores uid and token claims in context.
|
||||||
|
// Called by provider-specific AuthMiddleware (auth-jwt, auth-firebase) after
|
||||||
|
// token verification. EnrichmentMiddleware reads these values downstream.
|
||||||
|
func SetTokenData(ctx context.Context, uid string, claims map[string]any) context.Context {
|
||||||
|
ctx = context.WithValue(ctx, ctxUIDKey{}, uid)
|
||||||
|
ctx = context.WithValue(ctx, ctxClaimsKey{}, claims)
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUID(ctx context.Context) (string, bool) {
|
||||||
|
v, ok := ctx.Value(ctxUIDKey{}).(string)
|
||||||
|
return v, ok && v != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetClaims returns the raw token claims stored by SetTokenData.
|
||||||
|
// Returns nil if SetTokenData was not called on this context.
|
||||||
|
// Useful for custom IdentityEnricher implementations and ClaimsPermissionProvider.
|
||||||
|
func GetClaims(ctx context.Context) map[string]any {
|
||||||
|
v, _ := ctx.Value(ctxClaimsKey{}).(map[string]any)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func getClaims(ctx context.Context) map[string]any { return GetClaims(ctx) }
|
||||||
592
compliance_test.go
Normal file
592
compliance_test.go
Normal file
@@ -0,0 +1,592 @@
|
|||||||
|
package auth_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/auth/authmw"
|
||||||
|
"code.nochebuena.dev/einherjar/auth/rbac"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
"code.nochebuena.dev/einherjar/core/logz"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── Compile-time interface satisfaction ──────────────────────────────────────
|
||||||
|
|
||||||
|
var _ authmw.IdentityEnricher = (*mockEnricher)(nil)
|
||||||
|
var _ security.PermissionProvider = rbac.NewClaimsPermissionProvider("x", authmw.GetClaims)
|
||||||
|
var _ security.PermissionProvider = rbac.NewCachedPermissionProvider(rbac.NewClaimsPermissionProvider("x", authmw.GetClaims), &mockCache{}, time.Minute)
|
||||||
|
var _ security.PermissionProvider = rbac.NewChainPermissionProvider()
|
||||||
|
var _ rbac.Cache = (*mockCache)(nil)
|
||||||
|
|
||||||
|
// ── Structural: at most one exported TypeSpec per file ────────────────────────
|
||||||
|
|
||||||
|
func TestAtMostOneExportedTypePerFile(t *testing.T) {
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
err := filepath.WalkDir(".", func(path string, d os.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() && (d.Name() == ".git" || d.Name() == "vendor") {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(path, ".go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(path, "_test.go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if filepath.Base(path) == "doc.go" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
f, parseErr := parser.ParseFile(fset, path, nil, 0)
|
||||||
|
if parseErr != nil {
|
||||||
|
t.Errorf("%s: parse error: %v", path, parseErr)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if count := countExportedTypes(f); count > 1 {
|
||||||
|
t.Errorf("%s: has %d exported type declarations; want at most 1", path, count)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("walk error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func countExportedTypes(f *ast.File) int {
|
||||||
|
count := 0
|
||||||
|
for _, decl := range f.Decls {
|
||||||
|
gd, ok := decl.(*ast.GenDecl)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, spec := range gd.Specs {
|
||||||
|
ts, ok := spec.(*ast.TypeSpec)
|
||||||
|
if ok && ts.Name.IsExported() {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── authmw: SetTokenData ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestSetTokenData(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
claims := map[string]any{"perms": map[string]any{"orders": int64(7)}}
|
||||||
|
ctx = authmw.SetTokenData(ctx, "uid-1", claims)
|
||||||
|
|
||||||
|
got := authmw.GetClaims(ctx)
|
||||||
|
if got == nil {
|
||||||
|
t.Fatal("GetClaims returned nil after SetTokenData")
|
||||||
|
}
|
||||||
|
if _, ok := got["perms"]; !ok {
|
||||||
|
t.Error("claims key 'perms' missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── authmw: EnrichmentMiddleware ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestEnrichmentMiddlewareSuccess(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
enricher := &mockEnricher{identity: security.NewIdentity("uid-1", "Alice", "alice@example.com")}
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher)(okHandler())
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r = r.WithContext(authmw.SetTokenData(r.Context(), "uid-1", nil))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("status: got %d, want 200", w.Code)
|
||||||
|
}
|
||||||
|
if !enricher.called {
|
||||||
|
t.Error("enricher was not called")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnrichmentMiddlewareMissingUID(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
enricher := &mockEnricher{}
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher)(okHandler())
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("status: got %d, want 401", w.Code)
|
||||||
|
}
|
||||||
|
if enricher.called {
|
||||||
|
t.Error("enricher should not be called when uid is missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnrichmentMiddlewareEnricherError(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
enricher := &mockEnricher{err: errors.New("db down")}
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher)(okHandler())
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r = r.WithContext(authmw.SetTokenData(r.Context(), "uid-1", nil))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusInternalServerError {
|
||||||
|
t.Errorf("status: got %d, want 500", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnrichmentMiddlewareTenantHeader(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
enricher := &mockEnricher{identity: security.NewIdentity("uid-1", "Alice", "alice@example.com")}
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID"))(
|
||||||
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := security.FromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
t.Error("identity not in context")
|
||||||
|
}
|
||||||
|
if id.TenantID != "tenant-abc" {
|
||||||
|
t.Errorf("TenantID: got %q, want %q", id.TenantID, "tenant-abc")
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r.Header.Set("X-Tenant-ID", "tenant-abc")
|
||||||
|
r = r.WithContext(authmw.SetTokenData(r.Context(), "uid-1", nil))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("status: got %d, want 200", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEnrichmentMiddlewareBagEnricher verifies that WithBagEnricher attaches a
|
||||||
|
// custom attribute to the SecurityBag stored in context.
|
||||||
|
func TestEnrichmentMiddlewareBagEnricher(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
enricher := &mockEnricher{identity: security.NewIdentity("uid-1", "Alice", "alice@example.com")}
|
||||||
|
|
||||||
|
hwEnricher := authmw.BagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
|
||||||
|
return bag.With("hardware_id", r.Header.Get("X-Hardware-ID"))
|
||||||
|
})
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher, authmw.WithBagEnricher(hwEnricher))(
|
||||||
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
bag, ok := security.BagFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
t.Error("bag not in context")
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, ok := bag.Get("hardware_id")
|
||||||
|
if !ok {
|
||||||
|
t.Error("hardware_id not in bag")
|
||||||
|
} else if v != "hw-abc" {
|
||||||
|
t.Errorf("hardware_id: got %v, want hw-abc", v)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r.Header.Set("X-Hardware-ID", "hw-abc")
|
||||||
|
r = r.WithContext(authmw.SetTokenData(r.Context(), "uid-1", nil))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("status: got %d, want 200", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEnrichmentMiddlewareBagInContext verifies that security.BagFromContext works
|
||||||
|
// after enrichment, and that the bag carries the enriched Identity.
|
||||||
|
func TestEnrichmentMiddlewareBagInContext(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
id := security.NewIdentity("uid-1", "Alice", "alice@example.com")
|
||||||
|
enricher := &mockEnricher{identity: id}
|
||||||
|
|
||||||
|
h := authmw.EnrichmentMiddleware(logger, enricher)(
|
||||||
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
bag, ok := security.BagFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
t.Error("BagFromContext: want ok=true, got false")
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if bag.Identity() != id {
|
||||||
|
t.Errorf("bag identity: got %+v, want %+v", bag.Identity(), id)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r = r.WithContext(authmw.SetTokenData(r.Context(), "uid-1", nil))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("status: got %d, want 200", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── authmw: AuthzMiddleware ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestAuthzMiddlewareAllowed(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
const ReadOrders = security.Permission(0)
|
||||||
|
provider := &mockProvider{mask: security.PermissionMask(0).Grant(ReadOrders)}
|
||||||
|
|
||||||
|
h := authmw.AuthzMiddleware(logger, provider, "orders", ReadOrders)(okHandler())
|
||||||
|
|
||||||
|
id := security.NewIdentity("uid-1", "Alice", "alice@example.com")
|
||||||
|
ctx := security.SetInContext(context.Background(), id)
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Errorf("status: got %d, want 200", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthzMiddlewareMissingIdentity(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
provider := &mockProvider{}
|
||||||
|
|
||||||
|
h := authmw.AuthzMiddleware(logger, provider, "orders", 0)(okHandler())
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("status: got %d, want 401", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthzMiddlewarePermissionDenied(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
provider := &mockProvider{mask: 0} // no permissions
|
||||||
|
|
||||||
|
h := authmw.AuthzMiddleware(logger, provider, "orders", security.Permission(0))(okHandler())
|
||||||
|
|
||||||
|
id := security.NewIdentity("uid-1", "Alice", "alice@example.com")
|
||||||
|
ctx := security.SetInContext(context.Background(), id)
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("status: got %d, want 403", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthzMiddlewareProviderError(t *testing.T) {
|
||||||
|
logger := logz.New(logz.Config{})
|
||||||
|
provider := &mockProvider{err: errors.New("db error")}
|
||||||
|
|
||||||
|
h := authmw.AuthzMiddleware(logger, provider, "orders", security.Permission(0))(okHandler())
|
||||||
|
|
||||||
|
id := security.NewIdentity("uid-1", "Alice", "alice@example.com")
|
||||||
|
ctx := security.SetInContext(context.Background(), id)
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
if w.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("status: got %d, want 403 (fail-closed on provider error)", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── rbac: ClaimsPermissionProvider ───────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestClaimsProviderHit(t *testing.T) {
|
||||||
|
p := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
|
||||||
|
claims := map[string]any{
|
||||||
|
"perms": map[string]any{"orders": int64(7)},
|
||||||
|
}
|
||||||
|
ctx := authmw.SetTokenData(context.Background(), "uid-1", claims)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(ctx, "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 7 {
|
||||||
|
t.Errorf("mask: got %d, want 7", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClaimsProviderWildcard(t *testing.T) {
|
||||||
|
p := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
|
||||||
|
claims := map[string]any{
|
||||||
|
"perms": map[string]any{"*": int64(15)},
|
||||||
|
}
|
||||||
|
ctx := authmw.SetTokenData(context.Background(), "uid-1", claims)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(ctx, "uid-1", "products")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 15 {
|
||||||
|
t.Errorf("mask: got %d, want 15 (wildcard)", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClaimsProviderMissing(t *testing.T) {
|
||||||
|
p := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
|
||||||
|
ctx := context.Background() // no claims set
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(ctx, "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 0 {
|
||||||
|
t.Errorf("mask: got %d, want 0", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClaimsProviderFloat64(t *testing.T) {
|
||||||
|
p := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
|
||||||
|
claims := map[string]any{
|
||||||
|
"perms": map[string]any{"orders": float64(3)},
|
||||||
|
}
|
||||||
|
ctx := authmw.SetTokenData(context.Background(), "uid-1", claims)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(ctx, "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 3 {
|
||||||
|
t.Errorf("mask: got %d, want 3 (float64 cast)", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── rbac: CachedPermissionProvider ───────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestCachedProviderHit(t *testing.T) {
|
||||||
|
inner := &mockProvider{mask: 7}
|
||||||
|
cache := &mockCache{data: map[string]int64{"rbac:uid-1:orders": 99}}
|
||||||
|
p := rbac.NewCachedPermissionProvider(inner, cache, time.Minute)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 99 {
|
||||||
|
t.Errorf("mask: got %d, want 99 (from cache)", mask)
|
||||||
|
}
|
||||||
|
if inner.calls != 0 {
|
||||||
|
t.Error("inner provider should not be called on cache hit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCachedProviderMiss(t *testing.T) {
|
||||||
|
inner := &mockProvider{mask: 7}
|
||||||
|
cache := &mockCache{data: map[string]int64{}}
|
||||||
|
p := rbac.NewCachedPermissionProvider(inner, cache, time.Minute)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 7 {
|
||||||
|
t.Errorf("mask: got %d, want 7 (from inner)", mask)
|
||||||
|
}
|
||||||
|
if inner.calls != 1 {
|
||||||
|
t.Error("inner provider should be called on cache miss")
|
||||||
|
}
|
||||||
|
if cache.data["rbac:uid-1:orders"] != 7 {
|
||||||
|
t.Error("result should be stored in cache after miss")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCachedProviderCacheError(t *testing.T) {
|
||||||
|
inner := &mockProvider{mask: 5}
|
||||||
|
cache := &mockCache{getErr: errors.New("valkey down")}
|
||||||
|
p := rbac.NewCachedPermissionProvider(inner, cache, time.Minute)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 5 {
|
||||||
|
t.Errorf("mask: got %d, want 5 (fallthrough on cache error)", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCachedProviderTenantKey(t *testing.T) {
|
||||||
|
inner := &mockProvider{mask: 3}
|
||||||
|
cache := &mockCache{data: map[string]int64{}}
|
||||||
|
p := rbac.NewCachedPermissionProvider(inner, cache, time.Minute)
|
||||||
|
|
||||||
|
id := security.NewIdentity("uid-1", "Alice", "alice@example.com").WithTenant("tenant-abc")
|
||||||
|
ctx := security.SetInContext(context.Background(), id)
|
||||||
|
|
||||||
|
_, err := p.ResolveMask(ctx, "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantKey = "rbac:tenant-abc:uid-1:orders"
|
||||||
|
if _, ok := cache.data[wantKey]; !ok {
|
||||||
|
t.Errorf("expected cache key %q; got keys: %v", wantKey, cache.keys())
|
||||||
|
}
|
||||||
|
if _, ok := cache.data["rbac:uid-1:orders"]; ok {
|
||||||
|
t.Error("tenant-scoped key must not omit tenantID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWithCacheKey verifies that a custom CachedOpt key function is used instead
|
||||||
|
// of the default, enabling bag attributes (e.g. hardware ID) to be part of the key.
|
||||||
|
func TestWithCacheKey(t *testing.T) {
|
||||||
|
inner := &mockProvider{mask: 7}
|
||||||
|
cache := &mockCache{data: map[string]int64{}}
|
||||||
|
p := rbac.NewCachedPermissionProvider(inner, cache, time.Minute,
|
||||||
|
rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
|
||||||
|
hwID, _ := bag.Get("hardware_id")
|
||||||
|
return fmt.Sprintf("custom:%s:%v:%s", uid, hwID, resource)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
bag := security.NewSecurityBag(security.NewIdentity("uid-1", "Alice", "a@b.com")).
|
||||||
|
With("hardware_id", "hw-xyz")
|
||||||
|
ctx := security.SetBagInContext(context.Background(), bag)
|
||||||
|
|
||||||
|
_, err := p.ResolveMask(ctx, "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantKey = "custom:uid-1:hw-xyz:orders"
|
||||||
|
if _, ok := cache.data[wantKey]; !ok {
|
||||||
|
t.Errorf("expected custom cache key %q; got keys: %v", wantKey, cache.keys())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── rbac: ChainPermissionProvider ────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestChainProviderFirstNonZero(t *testing.T) {
|
||||||
|
first := &mockProvider{mask: 7}
|
||||||
|
second := &mockProvider{mask: 99}
|
||||||
|
p := rbac.NewChainPermissionProvider(first, second)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 7 {
|
||||||
|
t.Errorf("mask: got %d, want 7 (first non-zero)", mask)
|
||||||
|
}
|
||||||
|
if second.calls != 0 {
|
||||||
|
t.Error("second provider should not be called when first returns non-zero")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChainProviderFallthrough(t *testing.T) {
|
||||||
|
first := &mockProvider{mask: 0}
|
||||||
|
second := &mockProvider{mask: 5}
|
||||||
|
p := rbac.NewChainPermissionProvider(first, second)
|
||||||
|
|
||||||
|
mask, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if mask != 5 {
|
||||||
|
t.Errorf("mask: got %d, want 5 (fallthrough to second)", mask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChainProviderError(t *testing.T) {
|
||||||
|
first := &mockProvider{err: errors.New("provider down")}
|
||||||
|
second := &mockProvider{mask: 99}
|
||||||
|
p := rbac.NewChainPermissionProvider(first, second)
|
||||||
|
|
||||||
|
_, err := p.ResolveMask(context.Background(), "uid-1", "orders")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error, got nil")
|
||||||
|
}
|
||||||
|
if second.calls != 0 {
|
||||||
|
t.Error("second provider should not be called after error in first")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func okHandler() http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type mockEnricher struct {
|
||||||
|
identity security.Identity
|
||||||
|
err error
|
||||||
|
called bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockEnricher) Enrich(_ context.Context, _ string, _ map[string]any) (security.Identity, error) {
|
||||||
|
m.called = true
|
||||||
|
return m.identity, m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
type mockProvider struct {
|
||||||
|
mask security.PermissionMask
|
||||||
|
err error
|
||||||
|
calls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockProvider) ResolveMask(_ context.Context, _, _ string) (security.PermissionMask, error) {
|
||||||
|
m.calls++
|
||||||
|
return m.mask, m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
type mockCache struct {
|
||||||
|
data map[string]int64
|
||||||
|
getErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockCache) Get(_ context.Context, key string) (int64, bool, error) {
|
||||||
|
if m.getErr != nil {
|
||||||
|
return 0, false, m.getErr
|
||||||
|
}
|
||||||
|
v, ok := m.data[key]
|
||||||
|
return v, ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockCache) Set(_ context.Context, key string, value int64, _ time.Duration) error {
|
||||||
|
if m.data == nil {
|
||||||
|
m.data = map[string]int64{}
|
||||||
|
}
|
||||||
|
m.data[key] = value
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockCache) keys() []string {
|
||||||
|
keys := make([]string, 0, len(m.data))
|
||||||
|
for k := range m.data {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
59
doc.go
Normal file
59
doc.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// Package auth provides provider-agnostic HTTP authentication and authorization
|
||||||
|
// middleware for the Einherjar framework.
|
||||||
|
//
|
||||||
|
// auth absorbs two micro-lib packages:
|
||||||
|
// - httpauth → sub-package authmw (middleware + identity enrichment)
|
||||||
|
// - rbac → sub-package rbac (permission provider implementations)
|
||||||
|
//
|
||||||
|
// Types that cross the full dependency graph (Identity, Permission, PermissionMask,
|
||||||
|
// PermissionProvider) live in contracts/security, not here. This module provides
|
||||||
|
// implementations and middleware, not type definitions.
|
||||||
|
//
|
||||||
|
// # Sub-packages
|
||||||
|
//
|
||||||
|
// [authmw] — HTTP middleware layer. Three functions compose the full auth chain:
|
||||||
|
//
|
||||||
|
// - [authmw.SetTokenData] — integration contract called by provider packages
|
||||||
|
// (auth-jwt, auth-firebase) after token verification.
|
||||||
|
// - [authmw.EnrichmentMiddleware] — converts uid+claims into a security.Identity
|
||||||
|
// and stores it in context. The application provides the [authmw.IdentityEnricher]
|
||||||
|
// implementation that loads user data.
|
||||||
|
// - [authmw.AuthzMiddleware] — per-route permission gate. Takes a
|
||||||
|
// [security.PermissionProvider] and the required permission for the route.
|
||||||
|
//
|
||||||
|
// [rbac] — permission resolution. Three provider implementations satisfy
|
||||||
|
// [security.PermissionProvider]:
|
||||||
|
//
|
||||||
|
// - [rbac.NewClaimsPermissionProvider] — reads pre-computed bitmasks from JWT
|
||||||
|
// claims. Zero DB calls. Single-tenant fast-path.
|
||||||
|
// - [rbac.NewCachedPermissionProvider] — wraps any provider with a TTL cache.
|
||||||
|
// Cache keys are automatically scoped by TenantID when present.
|
||||||
|
// - [rbac.NewChainPermissionProvider] — tries providers in order; returns the
|
||||||
|
// first non-zero mask. Typical: claims fast-path → cached DB fallback.
|
||||||
|
//
|
||||||
|
// # Wiring Example
|
||||||
|
//
|
||||||
|
// enricher := userservice.NewIdentityEnricher(userRepo)
|
||||||
|
//
|
||||||
|
// permissions := rbac.NewChainPermissionProvider(
|
||||||
|
// rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims),
|
||||||
|
// rbac.NewCachedPermissionProvider(dbProvider, valkeyCache, 5*time.Minute),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// // After provider AuthMiddleware (from auth-jwt or auth-firebase):
|
||||||
|
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher))
|
||||||
|
//
|
||||||
|
// // Per-route authorization:
|
||||||
|
// srv.With(authmw.AuthzMiddleware(logger, permissions, "orders", security.Permission(0))).
|
||||||
|
// Get("/orders", ordersHandler)
|
||||||
|
//
|
||||||
|
// # Multi-tenant
|
||||||
|
//
|
||||||
|
// Pass the tenant identifier via a request header:
|
||||||
|
//
|
||||||
|
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID")))
|
||||||
|
//
|
||||||
|
// [authmw.WithTenantHeader] populates [security.Identity.TenantID] from the header.
|
||||||
|
// [rbac.NewCachedPermissionProvider] automatically scopes its cache keys by TenantID
|
||||||
|
// when non-empty — no additional configuration required.
|
||||||
|
package auth
|
||||||
69
docs/adr/index.md
Normal file
69
docs/adr/index.md
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
# Architecture Decision Records — `einherjar/auth`
|
||||||
|
|
||||||
|
## ADR-001: No root factory
|
||||||
|
|
||||||
|
**Status:** Accepted
|
||||||
|
|
||||||
|
**Context:** Previous starters (`web`) expose a root `New(logger, ...Config)` factory that pre-wires a complete, opinionated stack for the common case. The same pattern was evaluated for `auth`.
|
||||||
|
|
||||||
|
**Decision:** `auth` exposes no root factory. The module is composition-only.
|
||||||
|
|
||||||
|
**Rationale:** `web.New` works because the right middleware stack is always the same (Recover → RequestID → RequestLogger → CORS). Auth has no equivalent universal default:
|
||||||
|
- The auth provider is application-specific (JWT vs Firebase vs custom)
|
||||||
|
- The `IdentityEnricher` is always application code
|
||||||
|
- `AuthzMiddleware` is per-route, not global
|
||||||
|
- The `PermissionProvider` chain depends on the application's permission model
|
||||||
|
|
||||||
|
A root factory would either be a thin wrapper (adds no value) or force premature architectural choices on the caller.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ADR-002: Logger added to both middleware functions
|
||||||
|
|
||||||
|
**Status:** Accepted
|
||||||
|
|
||||||
|
**Context:** micro-lib's `EnrichmentMiddleware` and `AuthzMiddleware` were logger-free — errors were written as HTTP responses with no log emission.
|
||||||
|
|
||||||
|
**Decision:** Both middleware functions accept `logging.Logger` and route all errors through `httputil.Error(logger, w, r, err)`.
|
||||||
|
|
||||||
|
**Rationale:**
|
||||||
|
- An `IdentityEnricher` returning a 500 is a server-side failure. It must be logged — silent 500s are invisible in production.
|
||||||
|
- `httputil.Error` is the single error-processing point for the framework. Using it in auth keeps error response shape, log levels, and field enrichment identical to application handlers.
|
||||||
|
- 401 (missing token) and 403 (permission denied) log at Warn — client errors, not operator alerts.
|
||||||
|
- Log level routing is already handled by `httputil.Error`; no per-middleware logic needed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ADR-003: auth depends on web for httputil.Error
|
||||||
|
|
||||||
|
**Status:** Accepted
|
||||||
|
|
||||||
|
**Context:** auth error responses could be written independently (custom JSON write, like micro-lib's `WriteJSONError`) to avoid a dependency on `web`.
|
||||||
|
|
||||||
|
**Decision:** `auth` depends on `code.nochebuena.dev/einherjar/web` solely for `httputil.Error`.
|
||||||
|
|
||||||
|
**Rationale:**
|
||||||
|
- Consistent error shape across the entire API surface — auth errors and handler errors are indistinguishable to clients.
|
||||||
|
- `httputil.Error` handles log level routing, error code extraction, and platform code inclusion. Duplicating this in `auth` would create two implementations that drift over time.
|
||||||
|
- The dependency is one-directional: `web` does not depend on `auth`. The dependency graph remains acyclic.
|
||||||
|
|
||||||
|
**Trade-off accepted:** `auth` cannot be used without `web`. This is acceptable — `auth` is an HTTP middleware layer and `web` is the HTTP layer. Separating them was never a goal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ADR-004: BagEnricher chain over arbitrary context injection
|
||||||
|
|
||||||
|
**Status:** Accepted
|
||||||
|
|
||||||
|
**Context:** The original design used `WithTenantHeader` as the sole enrichment option, storing additional attributes via arbitrary `context.WithValue` calls. This made enrichment opaque — permission providers had no structured way to access request attributes like hardware IDs or grant codes without knowing the exact context key used elsewhere.
|
||||||
|
|
||||||
|
**Decision:** Enrichment is modeled as a chain of `BagEnricher` functions that transform a `security.SecurityBag`. `EnrichmentMiddleware` creates the bag from the base Identity, runs all registered `BagEnricher` functions in order, and stores the final bag via `security.SetBagInContext`. Permission providers retrieve the bag once with `security.BagFromContext(ctx)` and have access to all enriched attributes via `bag.Get(key)`.
|
||||||
|
|
||||||
|
**Rationale:**
|
||||||
|
- Single structured object per request instead of scattered `context.WithValue` entries; easier to reason about what's in the security context at any point in the chain.
|
||||||
|
- Permission providers access any bag attribute in one call rather than knowing which context key to look up.
|
||||||
|
- `WithCacheKey` on `CachedPermissionProvider` receives the full bag — no new parameters needed to include extra dimensions (hardware IDs, grant codes) in the cache key.
|
||||||
|
- `WithTenantHeader` is now a thin wrapper over `WithBagEnricher`, so the same extension point covers all enrichment use cases.
|
||||||
|
- Framework-owned attributes remain typed fields on `Identity`. Only application-defined attributes go into the bag's string-keyed map. Callers define their own key constants to maintain compile-time safety at the type-assertion call site.
|
||||||
|
|
||||||
|
**Trade-off accepted:** Bag attributes are `any` — type assertions are required at read sites. This is inherent to a string-keyed heterogeneous map. The contract is: the package that writes an attribute owns the constant and documents the type; callers that read it perform the assertion.
|
||||||
20
go.mod
Normal file
20
go.mod
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
module code.nochebuena.dev/einherjar/auth
|
||||||
|
|
||||||
|
go 1.26
|
||||||
|
|
||||||
|
require (
|
||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0
|
||||||
|
code.nochebuena.dev/einherjar/core v1.0.0
|
||||||
|
code.nochebuena.dev/einherjar/web v1.0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
golang.org/x/crypto v0.46.0 // indirect
|
||||||
|
golang.org/x/sys v0.39.0 // indirect
|
||||||
|
golang.org/x/text v0.32.0 // indirect
|
||||||
|
)
|
||||||
32
go.sum
Normal file
32
go.sum
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0 h1:hRudEtOIqU7vwedYLsCh8+9q5dCnKb61qX+zibqImRU=
|
||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
||||||
|
code.nochebuena.dev/einherjar/core v1.0.0 h1:AueZgfjp3+rQmDKOxmJQ945TTh+sqC1l/xJdTOdbr9w=
|
||||||
|
code.nochebuena.dev/einherjar/core v1.0.0/go.mod h1:0IywfRnJXX9xXQO6iPVaq2QDlXbbpXrB8A4T7gO8nE4=
|
||||||
|
code.nochebuena.dev/einherjar/web v1.0.0 h1:OaHfDP2vNlnPTsWfmf1GRvl5EWMhCgIxHkEwYg8qH3Y=
|
||||||
|
code.nochebuena.dev/einherjar/web v1.0.0/go.mod h1:2dbELcS5G1T1+YDAUt4hfn3wg+EmbJ7HOrKSo01CRQE=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||||
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||||
|
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
32
identifiable.go
Normal file
32
identifiable.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Module identifies this package to observability systems.
|
||||||
|
// auth is middleware-only — it is not registered with the launcher as a lifecycle
|
||||||
|
// component. Register Module manually with any version registry if needed.
|
||||||
|
var Module observability.Identifiable = &moduleID{}
|
||||||
|
|
||||||
|
type moduleID struct{}
|
||||||
|
|
||||||
|
const modulePath = "code.nochebuena.dev/einherjar/auth"
|
||||||
|
|
||||||
|
func (m *moduleID) ModulePath() string { return modulePath }
|
||||||
|
|
||||||
|
func (m *moduleID) ModuleVersion() string {
|
||||||
|
if info, ok := debug.ReadBuildInfo(); ok {
|
||||||
|
for _, dep := range info.Deps {
|
||||||
|
if dep.Path == modulePath {
|
||||||
|
return dep.Version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if info.Main.Path == modulePath {
|
||||||
|
return info.Main.Version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "(devel)"
|
||||||
|
}
|
||||||
16
rbac/cache.go
Normal file
16
rbac/cache.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package rbac
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cache is the pluggable caching backend for [NewCachedPermissionProvider].
|
||||||
|
// Satisfied by einherjar/cache-valkey via Go duck typing — no import of auth/rbac needed.
|
||||||
|
//
|
||||||
|
// Get returns (value, true, nil) on hit; (0, false, nil) on miss; (0, false, err) on error.
|
||||||
|
// Set errors are silently ignored by the provider — cache is best-effort.
|
||||||
|
type Cache interface {
|
||||||
|
Get(ctx context.Context, key string) (int64, bool, error)
|
||||||
|
Set(ctx context.Context, key string, value int64, ttl time.Duration) error
|
||||||
|
}
|
||||||
26
rbac/cached_opt.go
Normal file
26
rbac/cached_opt.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package rbac
|
||||||
|
|
||||||
|
import "code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
|
||||||
|
// CachedOpt configures [NewCachedPermissionProvider] behaviour.
|
||||||
|
type CachedOpt func(*cachedConfig)
|
||||||
|
|
||||||
|
// WithCacheKey overrides the default cache key function.
|
||||||
|
//
|
||||||
|
// fn receives the full [security.SecurityBag], uid, and resource name and
|
||||||
|
// returns the cache key string. Use when the default key format
|
||||||
|
// ("rbac:{uid}:{resource}" or "rbac:{tenantID}:{uid}:{resource}") is
|
||||||
|
// insufficient — for example when hardware IDs, grant codes, or other bag
|
||||||
|
// attributes must be part of the key to prevent cross-context cache pollution.
|
||||||
|
//
|
||||||
|
// rbac.NewCachedPermissionProvider(inner, cache, ttl,
|
||||||
|
// rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
|
||||||
|
// hwID, _ := bag.Get(KeyHardwareID)
|
||||||
|
// return fmt.Sprintf("rbac:%s:%s:%v:%s", bag.Identity().TenantID, uid, hwID, resource)
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
func WithCacheKey(fn func(security.SecurityBag, string, string) string) CachedOpt {
|
||||||
|
return func(c *cachedConfig) {
|
||||||
|
c.keyFn = fn
|
||||||
|
}
|
||||||
|
}
|
||||||
72
rbac/cached_provider.go
Normal file
72
rbac/cached_provider.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package rbac
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ security.PermissionProvider = (*cachedPermissionProvider)(nil)
|
||||||
|
|
||||||
|
type cachedConfig struct {
|
||||||
|
keyFn func(security.SecurityBag, string, string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
type cachedPermissionProvider struct {
|
||||||
|
inner security.PermissionProvider
|
||||||
|
cache Cache
|
||||||
|
ttl time.Duration
|
||||||
|
cfg cachedConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCachedPermissionProvider wraps any PermissionProvider with a TTL cache.
|
||||||
|
//
|
||||||
|
// Default cache key format:
|
||||||
|
// - "rbac:{uid}:{resource}" — single-tenant (no TenantID in bag)
|
||||||
|
// - "rbac:{tenantID}:{uid}:{resource}" — multi-tenant (TenantID non-empty)
|
||||||
|
//
|
||||||
|
// TenantID is read automatically from the [security.SecurityBag] in context —
|
||||||
|
// no API change required. Use [WithCacheKey] to override the key function when
|
||||||
|
// additional bag attributes (hardware IDs, grant codes) must be part of the key.
|
||||||
|
//
|
||||||
|
// Cache errors are silently swallowed — falls through to the inner provider.
|
||||||
|
// Set errors are ignored (cache is best-effort).
|
||||||
|
func NewCachedPermissionProvider(inner security.PermissionProvider, cache Cache, ttl time.Duration, opts ...CachedOpt) security.PermissionProvider {
|
||||||
|
cfg := cachedConfig{}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&cfg)
|
||||||
|
}
|
||||||
|
return &cachedPermissionProvider{inner: inner, cache: cache, ttl: ttl, cfg: cfg}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *cachedPermissionProvider) ResolveMask(ctx context.Context, uid, resource string) (security.PermissionMask, error) {
|
||||||
|
var key string
|
||||||
|
if p.cfg.keyFn != nil {
|
||||||
|
bag, _ := security.BagFromContext(ctx)
|
||||||
|
key = p.cfg.keyFn(bag, uid, resource)
|
||||||
|
} else {
|
||||||
|
key = p.defaultKey(ctx, uid, resource)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cached, ok, err := p.cache.Get(ctx, key); err == nil && ok {
|
||||||
|
return security.PermissionMask(cached), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mask, err := p.inner.ResolveMask(ctx, uid, resource)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = p.cache.Set(ctx, key, int64(mask), p.ttl)
|
||||||
|
return mask, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *cachedPermissionProvider) defaultKey(ctx context.Context, uid, resource string) string {
|
||||||
|
bag, ok := security.BagFromContext(ctx)
|
||||||
|
if ok && bag.Identity().TenantID != "" {
|
||||||
|
return fmt.Sprintf("rbac:%s:%s:%s", bag.Identity().TenantID, uid, resource)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("rbac:%s:%s", uid, resource)
|
||||||
|
}
|
||||||
39
rbac/chain_provider.go
Normal file
39
rbac/chain_provider.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package rbac
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ security.PermissionProvider = (*chainPermissionProvider)(nil)
|
||||||
|
|
||||||
|
type chainPermissionProvider struct {
|
||||||
|
providers []security.PermissionProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewChainPermissionProvider tries providers in order, returning the first non-zero mask.
|
||||||
|
// Errors short-circuit the chain immediately.
|
||||||
|
//
|
||||||
|
// Typical pattern: JWT claims fast-path → cached DB fallback:
|
||||||
|
//
|
||||||
|
// rbac.NewChainPermissionProvider(
|
||||||
|
// rbac.NewClaimsPermissionProvider("perms"),
|
||||||
|
// rbac.NewCachedPermissionProvider(dbProvider, cache, 5*time.Minute),
|
||||||
|
// )
|
||||||
|
func NewChainPermissionProvider(providers ...security.PermissionProvider) security.PermissionProvider {
|
||||||
|
return &chainPermissionProvider{providers: providers}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *chainPermissionProvider) ResolveMask(ctx context.Context, uid, resource string) (security.PermissionMask, error) {
|
||||||
|
for _, p := range c.providers {
|
||||||
|
mask, err := p.ResolveMask(ctx, uid, resource)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if mask != 0 {
|
||||||
|
return mask, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
75
rbac/claims_provider.go
Normal file
75
rbac/claims_provider.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package rbac
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ security.PermissionProvider = (*claimsPermissionProvider)(nil)
|
||||||
|
|
||||||
|
type claimsPermissionProvider struct {
|
||||||
|
claimsKey string
|
||||||
|
getClaims func(context.Context) map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClaimsPermissionProvider returns a PermissionProvider that reads
|
||||||
|
// pre-computed permission bitmasks from JWT claims stored in context.
|
||||||
|
//
|
||||||
|
// claimsKey is the top-level claim key whose value is a map[resource]int64.
|
||||||
|
// Falls back to wildcard key "*" if the specific resource is absent.
|
||||||
|
// Zero DB calls — fastest permission resolution for read-heavy APIs.
|
||||||
|
//
|
||||||
|
// getClaims is the function used to retrieve claims from context.
|
||||||
|
// Pass authmw.GetClaims when using the authmw middleware chain.
|
||||||
|
//
|
||||||
|
// Flat claims format: claims["perms"]["orders"] = 7
|
||||||
|
// For multi-tenant permission isolation, use [NewCachedPermissionProvider]
|
||||||
|
// wrapping a DB lookup — it automatically scopes cache keys per tenant.
|
||||||
|
func NewClaimsPermissionProvider(claimsKey string, getClaims func(context.Context) map[string]any) security.PermissionProvider {
|
||||||
|
return &claimsPermissionProvider{claimsKey: claimsKey, getClaims: getClaims}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *claimsPermissionProvider) ResolveMask(ctx context.Context, _, resource string) (security.PermissionMask, error) {
|
||||||
|
claims := p.getClaims(ctx)
|
||||||
|
if claims == nil {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, ok := claims[p.claimsKey]
|
||||||
|
if !ok {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
resourceMap, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mask := extractMask(resourceMap, resource)
|
||||||
|
if mask == 0 {
|
||||||
|
mask = extractMask(resourceMap, "*")
|
||||||
|
}
|
||||||
|
return security.PermissionMask(mask), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractMask(m map[string]any, key string) int64 {
|
||||||
|
v, ok := m[key]
|
||||||
|
if !ok {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
switch n := v.(type) {
|
||||||
|
case int64:
|
||||||
|
return n
|
||||||
|
case float64:
|
||||||
|
return int64(n)
|
||||||
|
case json.Number:
|
||||||
|
i, err := n.Int64()
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
43
rbac/doc.go
Normal file
43
rbac/doc.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
// Package rbac provides permission provider implementations for the Einherjar
|
||||||
|
// authorization system. All constructors return [security.PermissionProvider]
|
||||||
|
// from contracts/security — no new types are defined here.
|
||||||
|
//
|
||||||
|
// # Permission providers
|
||||||
|
//
|
||||||
|
// Three strategies compose into a complete authorization pipeline:
|
||||||
|
//
|
||||||
|
// // Fast-path: reads pre-computed bitmasks from JWT claims in context.
|
||||||
|
// // Pass authmw.GetClaims so rbac does not import authmw directly.
|
||||||
|
// claims := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
|
||||||
|
//
|
||||||
|
// // DB + cache: wraps any provider with TTL caching. Cache key is
|
||||||
|
// // automatically scoped by TenantID for multi-tenant deployments.
|
||||||
|
// cached := rbac.NewCachedPermissionProvider(dbProvider, valkeyCache, 5*time.Minute)
|
||||||
|
//
|
||||||
|
// // Chain: tries claims first, falls through to DB on miss.
|
||||||
|
// chain := rbac.NewChainPermissionProvider(claims, cached)
|
||||||
|
//
|
||||||
|
// # Cache key customization
|
||||||
|
//
|
||||||
|
// When additional bag attributes must be part of the cache key (e.g. hardware IDs):
|
||||||
|
//
|
||||||
|
// const KeyHardwareID = "hardware_id"
|
||||||
|
//
|
||||||
|
// cached := rbac.NewCachedPermissionProvider(dbProvider, cache, 5*time.Minute,
|
||||||
|
// rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
|
||||||
|
// hwID, _ := bag.Get(KeyHardwareID)
|
||||||
|
// return fmt.Sprintf("rbac:%s:%s:%v:%s", bag.Identity().TenantID, uid, hwID, resource)
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// # Cache interface
|
||||||
|
//
|
||||||
|
// [Cache] is satisfied by einherjar/cache-valkey via Go duck typing.
|
||||||
|
// No import of auth/rbac is needed by the cache implementation.
|
||||||
|
//
|
||||||
|
// # Multi-tenant
|
||||||
|
//
|
||||||
|
// [NewCachedPermissionProvider] automatically includes TenantID in the cache key
|
||||||
|
// when [security.Identity.TenantID] is non-empty in the request bag.
|
||||||
|
// Populate TenantID via [authmw.WithTenantHeader] in EnrichmentMiddleware.
|
||||||
|
package rbac
|
||||||
Reference in New Issue
Block a user