269 lines
7.0 KiB
Go
269 lines
7.0 KiB
Go
package inspection
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"pageswiki/internal/geduldh"
|
|
)
|
|
|
|
var (
|
|
ErrUnavailable = errors.New("inspection engine unavailable or changed")
|
|
ErrExternal = errors.New("external inspection is not permitted")
|
|
ErrBusy = errors.New("inspection capacity exhausted")
|
|
ErrInput = errors.New("inspection input invalid or too large")
|
|
ErrEngine = errors.New("inspection engine failed")
|
|
)
|
|
|
|
type Manifest struct {
|
|
Engine Engine
|
|
External bool
|
|
}
|
|
|
|
// Scanner implementations are trusted, registered by application code. A
|
|
// manifest is not permission to run a command, import code or connect a URL.
|
|
// Inspect must honor ctx; in-process plugins are NOT a process sandbox.
|
|
// The reader is valid only during Inspect and contains no Path or credential.
|
|
type Scanner interface {
|
|
Inspect(context.Context, io.Reader) (State, error)
|
|
}
|
|
type registration struct {
|
|
manifest Manifest
|
|
scanner Scanner
|
|
enabled bool
|
|
epoch uint64
|
|
}
|
|
type Registry struct {
|
|
mu sync.RWMutex
|
|
entries map[string]registration
|
|
}
|
|
|
|
func NewRegistry() *Registry { return &Registry{entries: map[string]registration{}} }
|
|
|
|
// Register always starts disabled. Changing a definition version requires a
|
|
// new registry registration/application lifecycle, never an in-place mutation.
|
|
func (r *Registry) Register(m Manifest, scanner Scanner) error {
|
|
if !m.Engine.valid() || scanner == nil {
|
|
return ErrPolicy
|
|
}
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
if _, ok := r.entries[m.Engine.ID]; ok {
|
|
return ErrPolicy
|
|
}
|
|
if len(r.entries) >= 64 {
|
|
return ErrPolicy
|
|
}
|
|
if r.entries == nil {
|
|
r.entries = map[string]registration{}
|
|
}
|
|
r.entries[m.Engine.ID] = registration{manifest: m, scanner: scanner}
|
|
return nil
|
|
}
|
|
func (r *Registry) SetEnabled(id string, enabled bool) error {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
e, ok := r.entries[id]
|
|
if !ok {
|
|
return ErrUnavailable
|
|
}
|
|
if e.enabled != enabled {
|
|
e.epoch++
|
|
e.enabled = enabled
|
|
r.entries[id] = e
|
|
}
|
|
return nil
|
|
}
|
|
func (r *Registry) Active() []Engine {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
var out []Engine
|
|
for _, e := range r.entries {
|
|
if e.enabled {
|
|
out = append(out, e.manifest.Engine)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
|
return out
|
|
}
|
|
func (r *Registry) acquire(engine Engine) (registration, error) {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
e, ok := r.entries[engine.ID]
|
|
if !ok || !e.enabled || e.manifest.Engine != engine {
|
|
return registration{}, ErrUnavailable
|
|
}
|
|
return e, nil
|
|
}
|
|
|
|
type Limits struct {
|
|
Workers int
|
|
MaxBytes int64
|
|
Timeout time.Duration
|
|
ResultTTL time.Duration
|
|
}
|
|
type Metrics struct {
|
|
Running int64
|
|
Completed uint64
|
|
Failed uint64
|
|
BytesVerified uint64
|
|
DurationNS uint64
|
|
}
|
|
type Runner struct {
|
|
registry *Registry
|
|
limits Limits
|
|
slots chan struct{}
|
|
running atomic.Int64
|
|
completed atomic.Uint64
|
|
failed atomic.Uint64
|
|
bytes atomic.Uint64
|
|
duration atomic.Uint64
|
|
}
|
|
|
|
func NewRunner(registry *Registry, limits Limits) (*Runner, error) {
|
|
if registry == nil || limits.Workers < 1 || limits.Workers > 4 || limits.MaxBytes < 1 || limits.MaxBytes > 256<<20 || limits.Timeout <= 0 || limits.Timeout > time.Minute || limits.ResultTTL <= 0 || limits.ResultTTL > 24*time.Hour {
|
|
return nil, ErrPolicy
|
|
}
|
|
return &Runner{registry: registry, limits: limits, slots: make(chan struct{}, limits.Workers)}, nil
|
|
}
|
|
func (r *Runner) Metrics() Metrics {
|
|
return Metrics{r.running.Load(), r.completed.Load(), r.failed.Load(), r.bytes.Load(), r.duration.Load()}
|
|
}
|
|
|
|
// Recheck reloads current job ownership, policy generation, topology and
|
|
// external-transmission consent. It runs before opening bytes and again before
|
|
// returning a report. The persistence layer must still CAS the lease/generation
|
|
// on commit; this callback is not an atomic database transaction.
|
|
type Recheck func(context.Context, Key) error
|
|
|
|
// Run is for a background worker, never a synchronous HTTP request. Capacity
|
|
// exhaustion returns immediately so the existing scheduler can defer the job.
|
|
// Documents must satisfy Geduldh's immutable Store contract. Verify before
|
|
// handing bytes to a scanner (especially an external service).
|
|
func (r *Runner) Run(ctx context.Context, documents geduldh.Store, key Key, allowExternal bool, recheck Recheck) (report Report, err error) {
|
|
if !key.valid() || documents == nil || recheck == nil {
|
|
return Report{}, ErrInput
|
|
}
|
|
if err = ctx.Err(); err != nil {
|
|
return Report{}, err
|
|
}
|
|
entry, err := r.registry.acquire(key.Engine)
|
|
if err != nil {
|
|
return Report{}, err
|
|
}
|
|
if entry.manifest.External && !allowExternal {
|
|
return Report{}, ErrExternal
|
|
}
|
|
select {
|
|
case r.slots <- struct{}{}:
|
|
default:
|
|
return Report{}, ErrBusy
|
|
}
|
|
start := time.Now()
|
|
r.running.Add(1)
|
|
defer func() {
|
|
// Never leak a plugin panic or diagnostic (which may contain payloads).
|
|
if recover() != nil {
|
|
report = Report{}
|
|
err = ErrEngine
|
|
}
|
|
r.running.Add(-1)
|
|
<-r.slots
|
|
r.duration.Add(uint64(time.Since(start)))
|
|
if err != nil {
|
|
report = Report{}
|
|
r.failed.Add(1)
|
|
} else {
|
|
r.completed.Add(1)
|
|
}
|
|
}()
|
|
ctx, cancel := context.WithTimeout(ctx, r.limits.Timeout)
|
|
defer cancel()
|
|
check := func() error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
current, err := r.registry.acquire(key.Engine)
|
|
if err != nil || current.epoch != entry.epoch {
|
|
return ErrUnavailable
|
|
}
|
|
if recheck(ctx, key) != nil {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
return ErrUnavailable
|
|
}
|
|
return nil
|
|
}
|
|
if err = check(); err != nil {
|
|
return Report{}, err
|
|
}
|
|
info, err := documents.Stat(ctx, key.Hash)
|
|
if ctx.Err() != nil {
|
|
return Report{}, ctx.Err()
|
|
}
|
|
if err != nil || info.Hash != key.Hash || info.Size < 0 || info.Size > r.limits.MaxBytes {
|
|
return Report{}, ErrInput
|
|
}
|
|
reader, err := documents.Open(ctx, key.Hash)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return Report{}, ctx.Err()
|
|
}
|
|
return Report{}, ErrInput
|
|
}
|
|
defer reader.Close()
|
|
hash := sha256.New()
|
|
n, err := io.Copy(hash, io.LimitReader(contextReader{ctx, reader}, info.Size+1))
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return Report{}, ctx.Err()
|
|
}
|
|
return Report{}, ErrInput
|
|
}
|
|
if n != info.Size || hex.EncodeToString(hash.Sum(nil)) != key.Hash {
|
|
return Report{}, ErrInput
|
|
}
|
|
r.bytes.Add(uint64(n))
|
|
if _, err = reader.Seek(0, io.SeekStart); err != nil {
|
|
return Report{}, ErrInput
|
|
}
|
|
if err = check(); err != nil {
|
|
return Report{}, err
|
|
}
|
|
state, err := entry.scanner.Inspect(ctx, io.LimitReader(contextReader{ctx, reader}, info.Size))
|
|
if ctx.Err() != nil {
|
|
return Report{}, ctx.Err()
|
|
}
|
|
if err != nil {
|
|
return Report{}, ErrEngine
|
|
}
|
|
if state != Clean && state != Suspicious && state != Malicious {
|
|
return Report{}, ErrEngine
|
|
}
|
|
if err = check(); err != nil {
|
|
return Report{}, err
|
|
}
|
|
now := time.Now()
|
|
return Report{Key: key, State: state, Finished: now, Expires: now.Add(r.limits.ResultTTL)}, nil
|
|
}
|
|
|
|
type contextReader struct {
|
|
ctx context.Context
|
|
reader io.Reader
|
|
}
|
|
|
|
func (r contextReader) Read(b []byte) (int, error) {
|
|
if err := r.ctx.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
return r.reader.Read(b)
|
|
}
|