package hostedctl import ( "context" "errors" "fmt" "sync" "time" ) // AuditMaxAge is how old, in controller time, the last passing network audit // may be for a launch or a replay that could create a VM to go ahead. const AuditMaxAge = 5 * time.Minute // ErrNetworkAudit: no network audit has passed in the last AuditMaxAge, so // nothing may create a VM. var ErrNetworkAudit = errors.New("hostedctl: no passing network audit in the last 5 minutes") // auditState is the last network audit result, held in memory only (ruling // R2). A fresh controller has none, so launches fail closed until the first // audit passes. type auditState struct { mu sync.Mutex ran bool passed bool at T // controller time when the audit began reason string // why it failed; empty when it passed } // RunAudit reads the provider's network settings through the auditor, checks // them against Config.Egress, and records the result with the controller // time at which the audit began. It returns the failure, or nil when the // audit passes. The reaper (Task 13) calls it every pass and alerts; RunAudit // itself only records. func (c *Controller) RunAudit(ctx context.Context) error { at := c.store.Clock().Now() a, err := c.auditor.AuditNetwork(ctx) var kinds []string if err != nil { kinds = auditCallKinds(err) err = fmt.Errorf("hostedctl: network audit: %w", err) } else if err = a.OK(c.cfg.Egress); err != nil { kinds = auditKinds(a, c.cfg.Egress) } c.audit.record(at, err) if err != nil { c.logAuditFailed(at, kinds) } return err } // record keeps the result of the audit that began at at, unless an audit // that began later has already been recorded. func (s *auditState) record(at T, err error) { s.mu.Lock() defer s.mu.Unlock() if s.ran && at < s.at { return } s.ran, s.at, s.passed, s.reason = true, at, err == nil, "" if err != nil { s.reason = err.Error() } } // check returns nil only when the last audit passed and began at most // AuditMaxAge before now. Otherwise it returns ErrNetworkAudit, wrapped with // the reason. func (s *auditState) check(now T) error { s.mu.Lock() defer s.mu.Unlock() if !s.ran { return fmt.Errorf("%w: none has run yet", ErrNetworkAudit) } if !s.passed { return fmt.Errorf("%w: the last one failed: %s", ErrNetworkAudit, s.reason) } if age := time.Duration(now - s.at); age > AuditMaxAge { return fmt.Errorf("%w: the last pass is %v old", ErrNetworkAudit, age) } return nil }