package provision import ( "bytes" "context" "encoding/base64" "errors" "io" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "time" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/console/fakeconsole" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/alta/homeop/fakehome" family "amadan.net/rastrillo/rastrillo/crypto" ) const ( ownerCanary = "till-owner-canary@lagged.test" credOrigin = "https://id.oficina.works" dirOrigin = "https://oficina.works" account = "bds" ) type harness struct { t *testing.T now time.Time home *fakehome.Home dir *httptest.Server cred *httptest.Server con *fakeconsole.Console key *family.Keypair pre string path string store *Store tokens map[string]string logs *bytes.Buffer } func newHarness(t *testing.T) *harness { t.Helper() h := &harness{t: t, now: time.Unix(2_000_000_000, 0), logs: &bytes.Buffer{}} var err error if h.key, err = family.Generate(); err != nil { t.Fatal(err) } h.pre = homeop.Token() h.home = fakehome.New(h.key.SignPub(), h.pre, credOrigin, dirOrigin, h.clock) h.home.AddPerson(ownerCanary) h.dir = httptest.NewServer(h.home.Handler(homeop.Directory)) h.cred = httptest.NewServer(h.home.Handler(homeop.Credential)) t.Cleanup(h.dir.Close) t.Cleanup(h.cred.Close) h.con = fakeconsole.New(account, "alta") t.Cleanup(h.con.Close) h.tokens = map[string]string{} for _, a := range Apps { h.tokens[a.Slug] = h.con.Mint(a.Slug) h.con.Versions[a.Slug] = "0123456789abcdef0123456789abcdef01234567" h.con.MailPrefix[a.Slug] = a.MailPrefixes[0] } h.con.Relay["calls"] = true h.path = filepath.Join(t.TempDir(), "alta.db") db, err := OpenDB(h.path) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) if h.store, err = NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), h.clock); err != nil { t.Fatal(err) } return h } func (h *harness) clock() time.Time { return h.now } func (h *harness) tick(d time.Duration) { h.now = h.now.Add(d) } func (h *harness) ctx() context.Context { return context.Background() } func (h *harness) engine(hook func(string) error) *Engine { roles := map[string]homeop.Role{} for _, r := range []string{homeop.Credential, homeop.Directory} { p := h.home.Pins(r) origin, url := credOrigin, h.cred.URL if r == homeop.Directory { origin, url = dirOrigin, h.dir.URL } roles[r] = homeop.Role{Name: r, Origin: origin, URL: url, Installation: p.Installation, Registry: p.Registry, Device: p.Device} } hc := &homeop.Client{Key: h.key, Prefilter: h.pre, Roles: roles, Now: h.clock} cc := &console.Client{Base: h.con.URL(), Account: account, Tokens: h.tokens, Guard: Guard{Store: h.store, Account: account}} return New(Config{Store: h.store, Home: hc, Console: cc, Public: &http.Client{Transport: h.con.Transport()}, HomeCfg: HomeConfig{Issuer: credOrigin, Directory: dirOrigin, KeysBase64: "eyJrMSI6IkJBPT0ifQ==", Provisioner: h.home.ProvisioningPublic()}, Account: account, Now: h.clock, Logger: slog.New(slog.NewTextHandler(h.logs, nil)), AfterAct: hook, Debug: func(err error) { h.t.Logf("transient: %v", err) }}) } // confirm is Paul on Home's confirm pages, directory first. func (h *harness) confirm(kind string) { h.t.Helper() if err := h.home.Confirm(homeop.Directory, ""); err != nil { h.t.Fatal(err) } if kind == homeop.KindInitialize { return } owner := "" if kind == homeop.KindCreateTeam { owner = ownerCanary } if err := h.home.Confirm(homeop.Credential, owner); err != nil { h.t.Fatal(err) } } // drive advances run until it is done, failed, or stuck for rounds, // letting the walks run and time pass a little between passes. func (h *harness) drive(e *Engine, run int64, rounds int) Run { h.t.Helper() var r Run for i := 0; i < rounds; i++ { if err := e.Advance(h.ctx(), run); err != nil && !errors.Is(err, errCrash) { var fl *Fail if !errors.As(err, &fl) { h.t.Fatalf("advance: %v", err) } } var err error if r, err = h.store.Run(h.ctx(), run); err != nil { h.t.Fatal(err) } if r.State == "done" || r.State == "failed" { return r } h.con.Walk() h.tick(5 * time.Second) } return r } // initialized runs the first production run, initialize, and lets its // window expire so the next plan can be confirmed. func (h *harness) initialized() { h.t.Helper() e := h.engine(nil) run, err := e.StartInitialize(h.ctx(), InitializeAttestation) if err != nil { h.t.Fatal(err) } h.confirm(homeop.KindInitialize) if r := h.drive(e, run, 3); r.State != "done" { h.t.Fatalf("initialize: %s %s", r.State, r.Code) } h.tick(homeop.WindowLifetime * time.Second) } var allApps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} func (h *harness) createLagged(e *Engine) int64 { h.t.Helper() run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Lagged", Owner: ownerCanary, Apps: allApps}) if err != nil { h.t.Fatal(err) } h.confirm(homeop.KindCreateTeam) return run } // scan reports whether needle is anywhere in Alta's database files. func (h *harness) scan(needle string) bool { h.t.Helper() for _, suffix := range []string{"", "-wal", "-shm"} { f, err := os.Open(h.path + suffix) if err != nil { continue } b, _ := io.ReadAll(f) f.Close() if bytes.Contains(b, []byte(needle)) { return true } } return false } func b64(s string) []byte { b, _ := base64.StdEncoding.DecodeString(s) return b } type fakeVar = fakeconsole.Var func sealFor(t *testing.T, h *harness, app, value string) string { t.Helper() e, err := console.Seal(h.con.SecretsPub(), "", app, []byte(value)) if err != nil { t.Fatal(err) } return e }