Files
archie/internal/infrastructure/access/live.go
T

156 lines
5.7 KiB
Go

package access
import (
"context"
"log/slog"
"sync"
"sync/atomic"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// versionTimeout bounds one check of the version and the policies. The
// Authorizer contract carries no context, so the check owns its deadline:
// without one a hung State Store would hang every decision in the process
// instead of refusing.
const versionTimeout = 5 * time.Second
// Live is an engine rebuilt from the stored policies whenever their version
// moves, so a policy edit is enforced by the next decision rather than by a
// reload interval. A check that cannot read the store refuses: the chain it
// holds may predate the edit, and standing on it would be exactly the allow
// the edit meant to remove.
type Live struct {
// ctx is the process lifetime: no request's context reaches a check.
//
//nolint:containedctx // The Authorizer contract carries no context, so the check has nothing but the process's own to derive a deadline from.
ctx context.Context
version func(context.Context) (int64, error)
load func(context.Context) ([]access.Policy, error)
log *slog.Logger
engine atomic.Pointer[Engine]
// mu serialises rebuilds, so a burst of edits costs one rebuild per
// version observed rather than one per decision.
mu sync.Mutex
stamp atomic.Int64
}
// NewPending returns a chain whose engine refuses every request until the
// stored policies load, so a process that starts before its State Store is
// closed rather than opened.
//
// The loader is called as the service, never as a principal: a list scoped to
// one org would cache that org's policies under the instance-wide version, and
// every other org's policies would stay missing for as long as the version
// holds.
func NewPending(ctx context.Context, version func(context.Context) (int64, error), load func(context.Context) ([]access.Policy, error), log *slog.Logger) *Live {
l := &Live{
ctx: ctx,
version: version,
load: func(ctx context.Context) ([]access.Policy, error) {
return load(access.WithoutPrincipal(ctx))
},
log: log,
}
l.engine.Store(pendingEngine)
// No version has been read yet, so the first decision loads even if the
// store reports zero.
l.stamp.Store(-1)
return l
}
// Ready reports whether the stored policies have loaded.
func (l *Live) Ready() bool { return l.engine.Load().Ready() }
// Reload rebuilds the engine from the store now, without waiting for a
// decision, so a process can report a store it could not read at start. It
// holds the same deadline a decision does: a decision that waits on a rebuild
// must not wait forever on a store that never answers.
func (l *Live) Reload(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, versionTimeout)
defer cancel()
l.mu.Lock()
defer l.mu.Unlock()
version, err := l.version(ctx)
if err != nil {
return err
}
return l.apply(ctx, version)
}
// current returns the engine for the version the store reports, rebuilding it
// when the version moved since the engine was built. A check that cannot read
// the store returns the pending engine, which refuses everything.
func (l *Live) current() *Engine {
ctx, cancel := context.WithTimeout(l.ctx, versionTimeout)
defer cancel()
// The version before the list, never after and never in the same
// transaction: stamped with a version read first, a rebuilt engine can only
// be newer than its stamp, which costs one more rebuild. The other order
// lets an engine hold content from before an edit while stamped as current,
// and no later check would ever see a version it had not already applied.
version, err := l.version(ctx)
if err != nil {
l.log.Warn("access policy version unavailable; refusing until it is readable", "err", err)
return pendingEngine
}
if version == l.stamp.Load() {
return l.engine.Load()
}
l.mu.Lock()
defer l.mu.Unlock()
// A decision that waited on the lock has already rebuilt for this version.
if version == l.stamp.Load() {
return l.engine.Load()
}
if err := l.apply(ctx, version); err != nil {
l.log.Warn("access policies not reloaded; refusing until they load", "err", err)
return pendingEngine
}
return l.engine.Load()
}
// apply loads the policies and swaps in the engine they describe, stamped with
// the version read before them. The caller holds mu.
func (l *Live) apply(ctx context.Context, version int64) error {
stored, err := l.load(ctx)
if err != nil {
return err
}
engine := New(stored)
for _, problem := range engine.Problems() {
l.log.ErrorContext(ctx, "stored access policy is invalid and denies its level",
"policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err)
}
// The engine before the stamp: a check that reads the stamp must find the
// engine it names.
l.engine.Store(engine)
l.stamp.Store(version)
return nil
}
func (l *Live) Authorize(p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision {
return l.current().Authorize(p, a, r, c)
}
func (l *Live) AuthorizeDelivery(orgID org.OrgID, sourcePath, addr string) access.Decision {
return l.current().AuthorizeDelivery(orgID, sourcePath, addr)
}
// Problems reports the current engine's invalid policies.
func (l *Live) Problems() []Problem { return l.engine.Load().Problems() }
// StartLive loads the stored policies through list and keeps them current as
// they change.
func StartLive(ctx context.Context, list func(context.Context) ([]access.Policy, error), version func(context.Context) (int64, error), log *slog.Logger) *Live {
live := NewPending(ctx, version, list, log)
if err := live.Reload(ctx); err != nil {
log.WarnContext(ctx, "access policies not loaded; requests are refused until they load", "err", err)
}
return live
}