Files
pages/internal/inspection/policy.go
T

296 lines
8.7 KiB
Go

// Package inspection implements file inspection contracts, not authorization
// or a malware scanner. No HTTP route, worker or external service is enabled
// by importing it. Callers must load complete, trusted policy snapshots.
package inspection
import (
"encoding/hex"
"errors"
"path"
"sort"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
var ErrPolicy = errors.New("invalid inspection policy")
type Mode string
const (
Inherit Mode = "inherit"
Disabled Mode = "disabled"
Monitor Mode = "monitor"
Required Mode = "required"
)
type State string
const (
Pending State = "pending"
Clean State = "clean"
Suspicious State = "suspicious"
Malicious State = "malicious"
Error State = "error"
Expired State = "expired"
)
// Engine identifies both the executable and its signature/model definitions.
// Definitions must change when the engine's detection data changes.
type Engine struct {
ID string `json:"id"`
Version string `json:"version"`
Definitions string `json:"definitions"`
}
func (e Engine) valid() bool {
return label(e.ID) && label(e.Version) && label(e.Definitions)
}
func label(s string) bool {
return s != "" && len(s) <= 128 && utf8.ValidString(s) && strings.TrimSpace(s) == s && strings.IndexFunc(s, unicode.IsControl) < 0
}
func validUUID(s string) bool {
id, err := uuid.Parse(s)
return err == nil && id.String() == s && id != uuid.Nil
}
func validHash(s string) bool {
if len(s) != 64 || strings.ToLower(s) != s {
return false
}
_, err := hex.DecodeString(s)
return err == nil
}
// Paths are already-decoded semantic Paths. Literal '%' and '+' are valid;
// never percent-decode a second time. Scope tests use segment boundaries.
func canonical(p string) bool {
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p && !strings.Contains(p, "\\") && strings.IndexFunc(p, unicode.IsControl) < 0
}
func under(p, root string) bool {
return root == "/" || p == root || strings.HasPrefix(p, root+"/")
}
type Rule struct {
Path string `json:"path"`
Mode Mode `json:"mode"`
Engines []Engine `json:"engines"`
}
// Policy is a Domain-local snapshot. Generation must change on policy OR
// relevant topology/engine-enable changes. Rules come from authorized locality settings,
// not from uploader-controlled data. External consent is Domain-admin owned.
type Policy struct {
Domain string `json:"domain"`
Generation string `json:"generation"`
AllowExternal bool `json:"allow_external"`
Rules []Rule `json:"rules"`
}
type Effective struct {
Domain string
Generation string
Mode Mode
AllowExternal bool
Engines []Engine
}
func rank(m Mode) int {
switch m {
case Inherit, Disabled:
return 0
case Monitor:
return 1
case Required:
return 2
default:
return -1
}
}
// Resolve never weakens an ancestor's mode or drops ancestor engines. A lower
// rule can add engines but cannot replace an inherited engine's version.
func (p Policy) Resolve(logicalPath string) (Effective, error) {
out := Effective{Domain: p.Domain, Generation: p.Generation, Mode: Disabled, AllowExternal: p.AllowExternal}
if !validUUID(p.Domain) || !validUUID(p.Generation) || !canonical(logicalPath) || len(p.Rules) > 128 {
return Effective{}, ErrPolicy
}
rules := append([]Rule(nil), p.Rules...)
sort.Slice(rules, func(i, j int) bool { return len(rules[i].Path) < len(rules[j].Path) })
seen := map[string]bool{}
engines := map[string]Engine{}
for _, r := range rules {
if !canonical(r.Path) || seen[r.Path] || rank(r.Mode) < 0 || len(r.Engines) > 16 || ((r.Mode == Inherit || r.Mode == Disabled) && len(r.Engines) > 0) {
return Effective{}, ErrPolicy
}
seen[r.Path] = true
local := map[string]bool{}
for _, e := range r.Engines {
if !e.valid() || local[e.ID] {
return Effective{}, ErrPolicy
}
local[e.ID] = true
}
if !under(logicalPath, r.Path) {
continue
}
if rank(r.Mode) > rank(out.Mode) {
out.Mode = r.Mode
}
for _, e := range r.Engines {
if old, ok := engines[e.ID]; ok && old != e {
return Effective{}, ErrPolicy
}
engines[e.ID] = e
}
}
if len(engines) > 16 || (out.Mode != Disabled && len(engines) == 0) {
return Effective{}, ErrPolicy
}
for _, e := range engines {
out.Engines = append(out.Engines, e)
}
sort.Slice(out.Engines, func(i, j int) bool { return out.Engines[i].ID < out.Engines[j].ID })
return out, nil
}
// Key is the minimum cache/job identity. Never reuse a result across Domains,
// policy generations, content hashes, or engine/definition versions.
type Key struct {
Domain string `json:"domain"`
Generation string `json:"generation"`
Hash string `json:"sha256"`
Engine Engine `json:"engine"`
}
func (k Key) valid() bool {
return validUUID(k.Domain) && validUUID(k.Generation) && validHash(k.Hash) && k.Engine.valid()
}
// Report is trusted worker output, never supplied by an uploader. Publication
// must additionally CAS the job lease/generation when persisting this record.
type Report struct {
Key Key
State State
Finished time.Time
Expires time.Time
}
type Decision struct {
Allowed bool
State State
Reason string
}
// Decide is an ADDITIONAL gate. accessAllowed is the application's existing
// ACL/publication decision; an inspection result can never grant that access.
// active is a fresh snapshot of enabled engines, not the queued job's snapshot.
func Decide(accessAllowed bool, p Effective, hash string, reports []Report, active []Engine, now time.Time) Decision {
if !accessAllowed {
return Decision{Reason: "access_denied"}
}
if !validUUID(p.Domain) || !validUUID(p.Generation) || !validHash(hash) || now.IsZero() || rank(p.Mode) < 0 || p.Mode == Inherit || len(p.Engines) > 16 || len(reports) > 64 || len(active) > 64 {
return Decision{State: Error, Reason: "invalid_policy"}
}
if p.Mode == Disabled {
return Decision{Allowed: true, Reason: "inspection_disabled"}
}
if len(p.Engines) == 0 {
return Decision{State: Error, Reason: "missing_engine"}
}
status, reason := Clean, "inspection_clean"
seen := map[string]bool{}
for _, e := range p.Engines {
if !e.valid() || seen[e.ID] {
return Decision{State: Error, Reason: "invalid_policy"}
}
seen[e.ID] = true
key := Key{p.Domain, p.Generation, hash, e}
state, why := Pending, "inspection_pending"
enabled := false
for _, a := range active {
if a == e {
enabled = true
}
}
var matches []Report
for _, r := range reports {
if r.Key == key {
matches = append(matches, r)
}
}
if !enabled {
state, why = Error, "engine_unavailable"
} else if len(matches) > 1 {
state, why = Error, "ambiguous_result"
} else if len(matches) == 1 {
r := matches[0]
switch r.State {
case Pending, Error, Expired:
state, why = r.State, "inspection_"+string(r.State)
case Clean, Suspicious, Malicious:
if r.Finished.IsZero() || r.Finished.After(now) || !r.Expires.After(r.Finished) {
state, why = Error, "invalid_result"
} else if !r.Expires.After(now) {
state, why = Expired, "inspection_expired"
} else {
state, why = r.State, "inspection_"+string(r.State)
}
default:
state, why = Error, "invalid_result"
}
}
if severity(state) > severity(status) {
status, reason = state, why
}
}
return Decision{Allowed: p.Mode == Monitor || status == Clean, State: status, Reason: reason}
}
func severity(s State) int {
switch s {
case Clean:
return 0
case Pending:
return 1
case Expired:
return 2
case Error:
return 3
case Suspicious:
return 4
case Malicious:
return 5
}
return 3
}
// DecidePaths evaluates all supplied current bindings, not just the requested
// alias. The caller must load a complete Domain-local binding snapshot, including
// source/dependency policy when appropriate. An empty/truncated set cannot stand
// for an unrestricted UUID/Asset. Cross-Domain bindings need a separate decision
// per Domain. This method performs no lookup and is not a routing middleware.
func DecidePaths(accessAllowed bool, p Policy, bindings []string, hash string, reports []Report, active []Engine, now time.Time) Decision {
if !accessAllowed {
return Decision{Reason: "access_denied"}
}
if len(bindings) == 0 || len(bindings) > 128 {
return Decision{State: Error, Reason: "incomplete_bindings"}
}
decision := Decision{Allowed: true, Reason: "inspection_disabled"}
for _, binding := range bindings {
effective, err := p.Resolve(binding)
if err != nil {
return Decision{State: Error, Reason: "invalid_policy"}
}
next := Decide(true, effective, hash, reports, active, now)
if !next.Allowed {
return next
}
if next.State != "" && (decision.State == "" || severity(next.State) > severity(decision.State)) {
decision = next
}
}
return decision
}