Harden NoActor check with runtime environment guard

Add Mix.env() check to match?/3 for defense in depth.
Document NoActor pattern in CODE_GUIDELINES.md.
This commit is contained in:
Moritz 2026-01-22 21:36:09 +01:00
parent 5506b5b2dc
commit 93216f3ee6
3 changed files with 128 additions and 1 deletions

View file

@ -1664,6 +1664,65 @@ case Ash.read(Mv.Membership.Member, actor: actor) do
end
```
### 5.1a NoActor Pattern - Test Environment Only
**IMPORTANT:** The `Mv.Authorization.Checks.NoActor` check is **ONLY for test environment**. It must NEVER be used in production.
**What NoActor Does:**
- Allows CRUD operations without an actor in **test environment only**
- Denies all operations without an actor in **production/dev** (fail-closed)
- Uses both compile-time and runtime guards to prevent accidental production use
**Security Guards:**
```elixir
# Compile-time guard
@allow_no_actor_bypass Mix.env() == :test
# Runtime guard (double-check)
def match?(nil, _context, _opts) do
if @allow_no_actor_bypass and Mix.env() == :test do
true # Only in test
else
false # Production/dev - fail-closed
end
end
```
**Why This Pattern Exists:**
- Test fixtures often need to create resources without an actor
- Production operations MUST always have an actor for security
- The double guard (compile-time + runtime) prevents config drift
**NEVER Use NoActor in Production:**
```elixir
# ❌ BAD - Don't do this in production code
Ash.create!(Member, attrs) # No actor - will fail in prod
# ✅ GOOD - Use admin actor for system operations
admin_user = get_admin_user()
Ash.create!(Member, attrs, actor: admin_user)
```
**Alternative: System Actor Pattern**
For production system operations, use the System Actor Pattern (see Section 3.3) instead of NoActor:
```elixir
# System operations in production
system_actor = get_system_actor()
Ash.create!(Member, attrs, actor: system_actor)
```
**Testing:**
- NoActor tests verify both compile-time and runtime guards
- Tests ensure NoActor returns `false` in non-test environments
- See `test/mv/authorization/checks/no_actor_test.exs`
### 5.2 Password Security
**Use bcrypt for Password Hashing:**