A fresh shop PC could never authenticate to its own engine

The agent read the engine's generated credential file once, at startup.
On a brand new install that file does not exist yet: the agent starts the
engine, and the engine writes its credential seconds later. So the agent
held an empty credential for the life of the process and every call it
makes - health, stats, camera sync, the embedding for a visit - came back
401, with a tray showing a red engine that was running perfectly.

Measured on a fresh state directory today: three 401s, no camera ever
reconciled, and the engine left running the YAML-seeded main stream
instead of the sub-stream head office holds. The install script hid this
on Windows because setup runs the engine once before the app starts.

config.Creds resolves lazily and re-reads on a rejection; the camera
client, the supervisor and the desktop app's engine client all retry once
when it changes. A configured BEHAVISION_API_USER is never re-read - an
operator who set one means it. Tests pin the actual first-run ordering.

Also adds demo/, a one-screen live console for showing the whole chain:
camera, the six steps with a measured camera-to-cloud latency, the
customer editable in place, and the raw JSON a phone and a dashboard
receive from production side by side.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KGcjxF1cNLcuwc3DAPcnfj
This commit is contained in:
2026-09-24 13:40:28 +05:30
parent 9062d2fc51
commit 16f0e69cec
10 changed files with 758 additions and 11 deletions

View File

@@ -14,6 +14,7 @@ import (
"time"
"github.com/loyaly/behavision-agent/pkg/bridge"
"github.com/loyaly/behavision-agent/pkg/config"
)
// EngineClient talks to the recognition engine on this PC's loopback.
@@ -21,7 +22,12 @@ type EngineClient struct {
Base string
User string
Password string
Client *http.Client
// Creds re-reads the engine's generated credential when one is rejected.
// Without it a fresh install is 401 for the life of the process: the agent
// starts the engine, and the engine writes its credential file seconds
// after the agent has already read (and failed to find) it.
Creds *config.Creds
Client *http.Client
}
func NewEngineClient(base, user, password string) *EngineClient {
@@ -50,14 +56,24 @@ func (e *EngineClient) do(ctx context.Context, method, path string, body, out an
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if e.User != "" {
req.SetBasicAuth(e.User, e.Password)
user, pass := e.User, e.Password
if e.Creds != nil {
user, pass = e.Creds.Get()
}
if user != "" {
req.SetBasicAuth(user, pass)
}
resp, err := e.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized && e.Creds != nil && e.Creds.Refresh() {
// The engine generated its credential after we last looked. Read it
// and try once more rather than failing for the life of the process.
resp.Body.Close()
return e.do(ctx, method, path, body, out)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// The engine's message, not just a status. "camera stored but failed to
// start: connection refused" is something an operator can act on;

View File

@@ -4,6 +4,7 @@ import (
"bufio"
"os"
"strings"
"sync"
)
// EngineCredentials reads the Basic credentials the engine generated for
@@ -60,3 +61,60 @@ func (c Config) WithEngineCredentials(path string) Config {
c.APIUser, c.APIPassword = EngineCredentials(path)
return c
}
// Creds resolves the engine's Basic credentials, re-reading the file when it
// has none.
//
// Reading once at startup is wrong on a fresh install, and that is the case
// that matters: the agent starts the engine, the engine generates its
// credential and writes the file a few seconds later, and an agent that read
// the file before that holds "" forever. Every call it makes - health, stats,
// camera sync, the embedding for a visit - then comes back 401 for the life of
// the process, on a brand new shop PC, with the tray showing a red engine that
// is running perfectly. Measured on a fresh state directory: three 401s and no
// camera ever reconciled.
//
// A configured credential is never re-read: an operator who set
// BEHAVISION_API_USER means it.
type Creds struct {
path string
mu sync.Mutex
user string
pass string
fixed bool
}
// NewCreds takes whatever the config already has. Non-empty means configured,
// and is used unchanged.
func NewCreds(path, user, password string) *Creds {
c := &Creds{path: path, user: user, pass: password}
c.fixed = user != "" || password != ""
return c
}
// Get returns the current pair, reading the file if it has nothing yet.
func (c *Creds) Get() (string, string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.user == "" && !c.fixed {
c.user, c.pass = EngineCredentials(c.path)
}
return c.user, c.pass
}
// Refresh re-reads the file after a rejection and reports whether the pair
// changed. Callers retry once when it did - which covers both the fresh-install
// race and a credential the engine regenerated under a running agent.
func (c *Creds) Refresh() bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.fixed {
return false
}
u, p := EngineCredentials(c.path)
if u == c.user && p == c.pass {
return false
}
c.user, c.pass = u, p
return u != ""
}

View File

@@ -0,0 +1,77 @@
package config
import (
"os"
"path/filepath"
"testing"
)
// The sequence on a brand new shop PC, in order:
//
// agent starts -> file does not exist yet
// agent starts the engine
// engine generates its credential and writes the file
// agent calls the engine -> must now succeed
//
// Read once at startup, the agent holds "" for the life of the process and
// every engine call is 401: health, stats, camera sync, the embedding for a
// visit. The tray shows a red engine that is running perfectly, and nothing
// says why. Measured on a fresh state directory before this existed.
func TestCredentialsArriveAfterTheAgentHasAlreadyLooked(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "api_credentials.txt")
creds := NewCreds(path, "", "") // nothing configured, file not there yet
if u, _ := creds.Get(); u != "" {
t.Fatalf("expected no credential before the engine has written one, got %q", u)
}
// the engine starts and writes its credential
if err := os.WriteFile(path, []byte("username=behavision\npassword=s3cret\n"), 0o600); err != nil {
t.Fatal(err)
}
// a 401 makes the agent look again
if !creds.Refresh() {
t.Fatal("Refresh did not pick up the credential the engine just wrote")
}
u, p := creds.Get()
if u != "behavision" || p != "s3cret" {
t.Fatalf("got %q/%q", u, p)
}
}
// An operator who set BEHAVISION_API_USER means it, and a file must never
// override them.
func TestAConfiguredCredentialIsNeverReplacedByTheFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "api_credentials.txt")
if err := os.WriteFile(path, []byte("username=generated\npassword=nope\n"), 0o600); err != nil {
t.Fatal(err)
}
creds := NewCreds(path, "chosen", "byhand")
if u, p := creds.Get(); u != "chosen" || p != "byhand" {
t.Fatalf("configured credential was replaced: %q/%q", u, p)
}
if creds.Refresh() {
t.Fatal("Refresh overrode a configured credential")
}
}
// A credential the engine regenerates under a running agent is picked up too -
// the same mechanism, and the reason paths.APICredentials says the agent reads
// the file "rather than storing a second copy".
func TestARegeneratedCredentialIsPickedUp(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "api_credentials.txt")
os.WriteFile(path, []byte("username=behavision\npassword=old\n"), 0o600)
creds := NewCreds(path, "", "")
creds.Get()
os.WriteFile(path, []byte("username=behavision\npassword=new\n"), 0o600)
if !creds.Refresh() {
t.Fatal("a regenerated password was not picked up")
}
if _, p := creds.Get(); p != "new" {
t.Fatalf("still holding %q", p)
}
}

View File

@@ -25,6 +25,8 @@ import (
"strconv"
"strings"
"sync"
"github.com/loyaly/behavision-agent/pkg/config"
"time"
)
@@ -59,6 +61,9 @@ type Options struct {
// no captured output is undiagnosable, which on a customer site means a
// site visit.
LogWriter io.Writer
// Creds re-reads the engine's generated credential when one is rejected,
// which is the ordinary case on a first run.
Creds *config.Creds
// HealthURL, StatsURL, User, Password address the engine's own API.
HealthURL string
StatsURL string
@@ -409,14 +414,24 @@ func (s *Supervisor) getJSON(ctx context.Context, url string, out any) error {
if err != nil {
return err
}
if s.opts.User != "" {
req.SetBasicAuth(s.opts.User, s.opts.Password)
user, pass := s.opts.User, s.opts.Password
if s.opts.Creds != nil {
user, pass = s.opts.Creds.Get()
}
if user != "" {
req.SetBasicAuth(user, pass)
}
resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized && s.opts.Creds != nil && s.opts.Creds.Refresh() {
// See cameras.EngineClient: on a fresh install the engine writes its
// credential after the agent has already read for one.
resp.Body.Close()
return s.getJSON(ctx, url, out)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s returned %s", url, resp.Status)
}