Install and uninstall apps on Base's account
Installer claims an app, writes the four BASE_APP_* variables, creates the instance, probes /api/version, then marks it installed or failed with a short message. Uninstall deletes the instance, then the row. KeySet is the one place the kid is computed. main wires it in, installs defaults at boot, and runs with installs disabled when Platform settings are missing.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3 files changed,
+432
−2
cmd/base/main.go+20 −2internal/install/install.go+172 −0internal/install/install_test.go+240 −0
diff --git a/cmd/base/main.go b/cmd/base/main.go| index d072a03..90eadb5 100644 |
| --- a/cmd/base/main.go |
| +++ b/cmd/base/main.go |
| @@ -5,6 +5,7 @@ import ( |
| "log/slog" |
| "net/http" |
| "os" |
| + "time" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/db" |
| @@ -13,6 +14,8 @@ import ( |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/install" |
| + "amadan.net/carlos/base/internal/platform" |
| "amadan.net/carlos/base/internal/store" |
| "amadan.net/carlos/base/internal/web" |
| ) |
| @@ -47,8 +50,23 @@ func run(logger *slog.Logger) error { |
| if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil { |
| return err |
| } |
| + var installer web.Installer = noInstaller{} |
| + if cfg.PlatformConsole == "" || cfg.PlatformAccount == "" || cfg.InstanceToken == "" || cfg.OperateToken == "" || cfg.AssertionKey == nil || cfg.AppsDomain == "" { |
| + logger.Warn("installs are disabled: set BASE_PLATFORM_CONSOLE, BASE_PLATFORM_ACCOUNT, BASE_PLATFORM_INSTANCE_TOKEN, BASE_PLATFORM_OPERATE_TOKEN, BASE_APPS_DOMAIN and BASE_ASSERTION_KEY to enable them") |
| + } else { |
| + hc := &http.Client{Timeout: 30 * time.Second} |
| + in := install.New(d.Writer(), cfg, platform.NewHTTP(cfg.PlatformConsole, cfg.PlatformAccount, cfg.InstanceToken, cfg.OperateToken, hc), install.ProbeVersion(hc), logger) |
| + installer = in |
| + bg, stop := context.WithCancel(context.Background()) |
| + defer stop() |
| + go func() { |
| + if err := in.EnsureDefaults(bg); err != nil { |
| + logger.Error("installing default apps", "err", err) |
| + } |
| + }() |
| + } |
| // Static files are served by the app itself. |
| - handler, err := web.App(d, cfg, mail.FromEnv("CARLOS", logger), noInstaller{}, logger) |
| + handler, err := web.App(d, cfg, mail.FromEnv("CARLOS", logger), installer, logger) |
| if err != nil { |
| return err |
| } |
| @@ -60,7 +78,7 @@ func run(logger *slog.Logger) error { |
| return rastrillo.Serve(opts) |
| } |
| -// noInstaller stands in until the Store's installer lands. |
| +// noInstaller stands in when Platform settings are missing (local development). |
| type noInstaller struct{} |
| func (noInstaller) Install(context.Context, string) error { return nil } |
diff --git a/internal/install/install.go b/internal/install/install.go| new file mode 100644 |
| index 0000000..faeb187 |
| --- /dev/null |
| +++ b/internal/install/install.go |
| @@ -0,0 +1,172 @@ |
| +// Package install puts catalogue apps onto the CARLOS Platform account Base |
| +// runs on, and takes them off again. |
| +package install |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log/slog" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + |
| + "amadan.net/carlos/base/internal/catalog" |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/platform" |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +const ( |
| + probeEvery = 2 * time.Second |
| + probeTimeout = 5 * time.Minute |
| +) |
| + |
| +// Installer installs and uninstalls apps. It satisfies web.Installer. |
| +type Installer struct { |
| + db *sql.DB |
| + cfg config.Config |
| + pc platform.Client |
| + probe func(ctx context.Context, origin string) error |
| + logger *slog.Logger |
| +} |
| + |
| +// New returns an Installer. db must be the writer handle. probe waits until |
| +// a new instance answers at origin. |
| +func New(db *sql.DB, cfg config.Config, pc platform.Client, probe func(ctx context.Context, origin string) error, logger *slog.Logger) *Installer { |
| + return &Installer{db: db, cfg: cfg, pc: pc, probe: probe, logger: logger} |
| +} |
| + |
| +// HostFor returns the instance's host label (also its config environment |
| +// name) and full host. |
| +func HostFor(cfg config.Config, app string) (label, host string) { |
| + label = cfg.Slug + "-" + app |
| + return label, label + "." + cfg.AppsDomain |
| +} |
| + |
| +// KeySet returns the key id and public key an app uses to verify Base's |
| +// assertions. The kid is the lowercase hex SHA-256 of the 65-byte SignPub. |
| +func KeySet(kp *crypto.Keypair) (kid string, pub []byte) { |
| + pub = kp.SignPub() |
| + sum := sha256.Sum256(pub) |
| + return hex.EncodeToString(sum[:]), pub |
| +} |
| + |
| +// AppVars returns the four variables every installed app reads. |
| +func AppVars(cfg config.Config, app, origin string) map[string]string { |
| + kid, pub := KeySet(cfg.AssertionKey) |
| + keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)}) |
| + return map[string]string{ |
| + "BASE_APP_ORIGIN": origin, |
| + "BASE_APP_ISSUER": cfg.Origin, |
| + "BASE_APP_CONSUMER_ID": app, |
| + "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys), |
| + } |
| +} |
| + |
| +// Install claims app, configures and creates its instance, waits for it to |
| +// answer, and records the result. It blocks until then. If the app is |
| +// already installed or being installed it does nothing and returns nil. |
| +// A failure is recorded as a short message on the install row; the returned |
| +// error carries the same text. |
| +func (in *Installer) Install(ctx context.Context, app string) error { |
| + if _, ok := catalog.Get(app); !ok { |
| + return fmt.Errorf("unknown app %q", app) |
| + } |
| + if in.cfg.AssertionKey == nil { |
| + return errors.New("BASE_ASSERTION_KEY is not set") |
| + } |
| + label, host := HostFor(in.cfg, app) |
| + claimed, err := store.ClaimInstall(ctx, in.db, app, host) |
| + if err != nil { |
| + return err |
| + } |
| + if !claimed { |
| + return nil |
| + } |
| + origin := "https://" + host |
| + if err := in.pc.SetEnv(ctx, app, label, AppVars(in.cfg, app, origin)); err != nil { |
| + return in.fail(ctx, app, "Platform refused the app settings", err) |
| + } |
| + if err := in.pc.CreateInstance(ctx, app, host, label); err != nil { |
| + return in.fail(ctx, app, "Platform refused to create the instance", err) |
| + } |
| + if err := in.probe(ctx, origin); err != nil { |
| + return in.fail(ctx, app, "The app did not start answering", err) |
| + } |
| + return store.SetInstallState(ctx, in.db, app, "installed", "") |
| +} |
| + |
| +// fail records a short message (never the underlying error text, which may |
| +// carry a response body) and logs the detail. |
| +func (in *Installer) fail(ctx context.Context, app, msg string, cause error) error { |
| + in.logger.Error("install failed", "app", app, "err", cause) |
| + // The caller's context may be what failed; record the state regardless. |
| + if err := store.SetInstallState(context.WithoutCancel(ctx), in.db, app, "failed", msg); err != nil { |
| + in.logger.Error("recording install failure", "app", app, "err", err) |
| + } |
| + return errors.New(msg) |
| +} |
| + |
| +// Uninstall removes the instance's route, then forgets the install. The |
| +// app's data is kept by Platform. |
| +func (in *Installer) Uninstall(ctx context.Context, app string) error { |
| + _, host := HostFor(in.cfg, app) |
| + if err := in.pc.DeleteInstance(ctx, app, host); err != nil { |
| + in.logger.Error("uninstall failed", "app", app, "err", err) |
| + return errors.New("Platform refused to remove the instance") |
| + } |
| + return store.DeleteInstall(ctx, in.db, app) |
| +} |
| + |
| +// EnsureDefaults installs every default catalogue app that is not already |
| +// installed. Apps that fail are retried on the next call; the first error |
| +// is returned after every default has been tried. |
| +func (in *Installer) EnsureDefaults(ctx context.Context) error { |
| + var first error |
| + for _, e := range catalog.All() { |
| + if !e.Default { |
| + continue |
| + } |
| + if err := in.Install(ctx, e.ID); err != nil && first == nil { |
| + first = err |
| + } |
| + } |
| + return first |
| +} |
| + |
| +// ProbeVersion polls GET {origin}/api/version every 2 s until it gets a 200, |
| +// and gives up after 5 minutes. |
| +func ProbeVersion(hc *http.Client) func(ctx context.Context, origin string) error { |
| + return probeVersion(hc, probeEvery, probeTimeout) |
| +} |
| + |
| +func probeVersion(hc *http.Client, every, timeout time.Duration) func(context.Context, string) error { |
| + return func(ctx context.Context, origin string) error { |
| + ctx, cancel := context.WithTimeout(ctx, timeout) |
| + defer cancel() |
| + for { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+"/api/version", nil) |
| + if err != nil { |
| + return err |
| + } |
| + if resp, err := hc.Do(req); err == nil { |
| + resp.Body.Close() |
| + if resp.StatusCode == http.StatusOK { |
| + return nil |
| + } |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("no answer from %s: %w", origin, ctx.Err()) |
| + case <-time.After(every): |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/install/install_test.go b/internal/install/install_test.go| new file mode 100644 |
| index 0000000..e97bc4f |
| --- /dev/null |
| +++ b/internal/install/install_test.go |
| @@ -0,0 +1,240 @@ |
| +package install |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/platform" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/web" |
| +) |
| + |
| +var _ web.Installer = (*Installer)(nil) |
| + |
| +var template = dbtest.FromSet(store.BootSchema) |
| + |
| +func TestMain(m *testing.M) { |
| + code := m.Run() |
| + template.Remove() |
| + os.Exit(code) |
| +} |
| + |
| +func setup(t *testing.T, probe func(context.Context, string) error) (*Installer, *platform.Fake, *sql.DB, config.Config) { |
| + t.Helper() |
| + kp, err := crypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := config.Config{Origin: "https://base.example.com", Name: "Acme", Slug: "acme", AppsDomain: "bab.oncarlos.com", AssertionKey: kp} |
| + db := template.Open(t) |
| + pf := platform.NewFake() |
| + if probe == nil { |
| + probe = func(context.Context, string) error { return nil } |
| + } |
| + return New(db, cfg, pf, probe, slog.New(slog.NewTextHandler(io.Discard, nil))), pf, db, cfg |
| +} |
| + |
| +func state(t *testing.T, db *sql.DB, app string) store.Install { |
| + t.Helper() |
| + all, err := store.Installs(context.Background(), db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, i := range all { |
| + if i.App == app { |
| + return i |
| + } |
| + } |
| + return store.Install{} |
| +} |
| + |
| +func TestInstallWritesEnvThenCreates(t *testing.T) { |
| + in, pf, db, cfg := setup(t, nil) |
| + if err := in.Install(context.Background(), "scratchpad"); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := pf.Calls() |
| + if len(calls) != 2 || calls[0].Method != "SetEnv" || calls[1].Method != "CreateInstance" { |
| + t.Fatalf("calls = %+v", calls) |
| + } |
| + label := "acme-scratchpad" |
| + kid, pub := KeySet(cfg.AssertionKey) |
| + keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)}) |
| + want := map[string]string{ |
| + "BASE_APP_ORIGIN": "https://acme-scratchpad.bab.oncarlos.com", |
| + "BASE_APP_ISSUER": cfg.Origin, |
| + "BASE_APP_CONSUMER_ID": "scratchpad", |
| + "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys), |
| + } |
| + if calls[0].Environment != label || len(calls[0].Vars) != 4 { |
| + t.Fatalf("setenv = %+v", calls[0]) |
| + } |
| + for k, v := range want { |
| + if calls[0].Vars[k] != v { |
| + t.Errorf("%s = %q, want %q", k, calls[0].Vars[k], v) |
| + } |
| + } |
| + if c := calls[1]; c.App != "scratchpad" || c.Host != label+".bab.oncarlos.com" || c.Environment != label { |
| + t.Errorf("create = %+v", c) |
| + } |
| + if s := state(t, db, "scratchpad"); s.State != "installed" || s.Host != label+".bab.oncarlos.com" { |
| + t.Errorf("row = %+v", s) |
| + } |
| +} |
| + |
| +func TestKeySetIsHexSHA256OfSignPub(t *testing.T) { |
| + kp, _ := crypto.Generate() |
| + kid, pub := KeySet(kp) |
| + if len(kid) != 64 || len(pub) != 65 { |
| + t.Fatalf("kid %q pub %d", kid, len(pub)) |
| + } |
| +} |
| + |
| +func TestInstallTwiceIsOneInstance(t *testing.T) { |
| + var n atomic.Int32 |
| + gate := make(chan struct{}) |
| + in, pf, _, _ := setup(t, func(context.Context, string) error { n.Add(1); <-gate; return nil }) |
| + var wg sync.WaitGroup |
| + for range 2 { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); _ = in.Install(context.Background(), "scratchpad") }() |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + close(gate) |
| + wg.Wait() |
| + creates := 0 |
| + for _, c := range pf.Calls() { |
| + if c.Method == "CreateInstance" { |
| + creates++ |
| + } |
| + } |
| + if creates != 1 || n.Load() != 1 { |
| + t.Fatalf("creates %d probes %d", creates, n.Load()) |
| + } |
| +} |
| + |
| +func TestInstallCreateRefusedMarksFailed(t *testing.T) { |
| + in, pf, db, _ := setup(t, nil) |
| + pf.Fail("CreateInstance", errors.New("platform said no: secret body")) |
| + if err := in.Install(context.Background(), "scratchpad"); err == nil { |
| + t.Error("want an error") |
| + } |
| + s := state(t, db, "scratchpad") |
| + if s.State != "failed" || s.Error == "" { |
| + t.Fatalf("row = %+v", s) |
| + } |
| + pf.Fail("CreateInstance", nil) |
| + if err := in.Install(context.Background(), "scratchpad"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := state(t, db, "scratchpad"); s.State != "installed" { |
| + t.Errorf("after retry: %+v", s) |
| + } |
| +} |
| + |
| +func TestInstallNeverAnswersMarksFailed(t *testing.T) { |
| + in, _, db, _ := setup(t, func(context.Context, string) error { return context.DeadlineExceeded }) |
| + _ = in.Install(context.Background(), "scratchpad") |
| + if s := state(t, db, "scratchpad"); s.State != "failed" || s.Error == "" { |
| + t.Fatalf("row = %+v", s) |
| + } |
| +} |
| + |
| +func TestInstallUnknownApp(t *testing.T) { |
| + in, pf, _, _ := setup(t, nil) |
| + if err := in.Install(context.Background(), "nope"); err == nil { |
| + t.Error("want error") |
| + } |
| + if len(pf.Calls()) != 0 { |
| + t.Error("platform called") |
| + } |
| +} |
| + |
| +func TestUninstallDeletesInstanceKeepsNothingInBase(t *testing.T) { |
| + in, pf, db, _ := setup(t, nil) |
| + if err := in.Install(context.Background(), "scratchpad"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := in.Uninstall(context.Background(), "scratchpad"); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := pf.Calls() |
| + last := calls[len(calls)-1] |
| + if last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" || last.App != "scratchpad" { |
| + t.Errorf("last = %+v", last) |
| + } |
| + if s := state(t, db, "scratchpad"); s.App != "" { |
| + t.Errorf("row remains: %+v", s) |
| + } |
| +} |
| + |
| +func TestEnsureDefaultsInstallsWelcomeOnce(t *testing.T) { |
| + in, pf, db, _ := setup(t, nil) |
| + for range 2 { |
| + if err := in.EnsureDefaults(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + creates := 0 |
| + for _, c := range pf.Calls() { |
| + if c.Method == "CreateInstance" { |
| + creates++ |
| + if c.App != "welcome" { |
| + t.Errorf("app = %s", c.App) |
| + } |
| + } |
| + } |
| + if creates != 1 { |
| + t.Errorf("creates = %d", creates) |
| + } |
| + if s := state(t, db, "welcome"); s.State != "installed" { |
| + t.Errorf("row = %+v", s) |
| + } |
| + if s := state(t, db, "scratchpad"); s.App != "" { |
| + t.Error("scratchpad installed") |
| + } |
| +} |
| + |
| +func TestProbeVersion(t *testing.T) { |
| + var hits atomic.Int32 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/api/version" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if hits.Add(1) < 3 { |
| + w.WriteHeader(http.StatusBadGateway) |
| + return |
| + } |
| + })) |
| + defer srv.Close() |
| + p := probeVersion(srv.Client(), 5*time.Millisecond, 2*time.Second) |
| + if err := p(context.Background(), srv.URL); err != nil || hits.Load() != 3 { |
| + t.Fatalf("err %v hits %d", err, hits.Load()) |
| + } |
| +} |
| + |
| +func TestProbeVersionGivesUp(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(502) })) |
| + defer srv.Close() |
| + p := probeVersion(srv.Client(), 5*time.Millisecond, 50*time.Millisecond) |
| + if err := p(context.Background(), srv.URL); err == nil { |
| + t.Fatal("want error") |
| + } |
| +} |