From a3c409f28185d6aa74c7c7a9ec9de8c2d90cc3a0 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 00:51:23 -0800 Subject: [PATCH 01/15] Manage fresh-install payment infrastructure and keyless Node lifecycle --- README.md | 1 + api/cmd/controlcenter/main.go | 2 +- api/cmd/controlcenter/main_test.go | 41 ++ api/config.example.toml | 4 +- api/internal/controlplane/assignments.go | 4 +- api/internal/controlplane/config.go | 34 +- api/internal/controlplane/config_test.go | 9 +- .../controlplane/machine_credentials.go | 7 + api/internal/controlplane/machineconfig.go | 6 + .../controlplane/machineconfig/apps.go | 13 + .../controlplane/machineconfig/bundle.go | 22 + .../controlplane/machineconfig/connector.go | 2 +- .../controlplane/machineconfig/manager.go | 23 +- .../machineconfig/observations.go | 22 + .../controlplane/machineconfig/payment.go | 90 ++++ .../machineconfig/payment_test.go | 128 +++++ .../controlplane/machineconfig/reports.go | 5 +- .../controlplane/machineconfig/rollout.go | 95 +++- .../controlplane/machineconfig/runtime.go | 10 + .../controlplane/machineconfig/system.go | 3 + .../controlplane/machineconfig/system_test.go | 4 +- .../templates/system/node/orchestrator.yaml | 2 +- .../controlplane/machineconfig/types.go | 8 + .../controlplane/migrations/001_initial.sql | 24 + .../migrations/007_runtime_retirement.sql | 2 + api/internal/controlplane/observed_state.go | 59 +++ .../controlplane/payment_credentials.go | 207 ++++++++ api/internal/controlplane/payment_settings.go | 303 +++++++++++ api/internal/controlplane/payment_test.go | 479 ++++++++++++++++++ api/internal/controlplane/payments/store.go | 31 ++ api/internal/controlplane/registry.go | 10 +- api/internal/controlplane/registry_store.go | 23 +- api/internal/controlplane/registry_test.go | 15 +- api/internal/controlplane/server.go | 2 + .../controlplane/tunnel/endpoints_test.go | 2 +- deploy/Caddyfile | 20 +- deploy/README.md | 11 +- deploy/compose.paid.yaml | 28 + deploy/config.example.toml | 5 +- deploy/payments.example.json | 23 + deploy/redeemer.example.toml | 10 + docs/app-registry.md | 16 +- docs/paid-operation.md | 165 ++++++ go.mod | 2 +- runtime/appreconciler/controller.go | 17 +- runtime/appreconciler/input.go | 41 ++ runtime/appreconciler/payment_test.go | 80 +++ runtime/bootstrap-livepeer.sh | 4 +- runtime/cmd/livepeer-runtime/main.go | 13 +- runtime/connector/identity.go | 3 + runtime/contract/contract.go | 68 +-- runtime/httpsource/source.go | 11 + runtime/lib/credentials.sh | 4 +- runtime/management/sockets.go | 9 +- runtime/management/sockets_test.go | 10 +- runtime/manifests/bootstrap/rbac.yaml | 2 +- runtime/orchestrator/integration.go | 192 +++++++ runtime/orchestrator/integration_test.go | 192 +++++++ runtime/orchestrator/observation.go | 139 +++++ runtime/orchestrator/process.go | 116 +++++ runtime/payment/config.go | 176 +++++++ runtime/payment/config_test.go | 27 + runtime/services/Dockerfile.node | 8 + runtime/services/Dockerfile.node.dockerignore | 2 + runtime/transport/client.go | 7 +- runtime/transport/client_test.go | 3 + schema/validate.go | 6 +- ui/src/catalog.tsx | 15 +- ui/src/machine-status.tsx | 18 +- ui/tests/machine-status.spec.ts | 16 + 70 files changed, 3003 insertions(+), 148 deletions(-) create mode 100644 api/internal/controlplane/machineconfig/payment.go create mode 100644 api/internal/controlplane/machineconfig/payment_test.go create mode 100644 api/internal/controlplane/payment_credentials.go create mode 100644 api/internal/controlplane/payment_settings.go create mode 100644 api/internal/controlplane/payment_test.go create mode 100644 api/internal/controlplane/payments/store.go create mode 100644 deploy/compose.paid.yaml create mode 100644 deploy/payments.example.json create mode 100644 deploy/redeemer.example.toml create mode 100644 docs/paid-operation.md create mode 100644 runtime/appreconciler/payment_test.go create mode 100644 runtime/orchestrator/integration.go create mode 100644 runtime/orchestrator/integration_test.go create mode 100644 runtime/orchestrator/observation.go create mode 100644 runtime/orchestrator/process.go create mode 100644 runtime/payment/config.go create mode 100644 runtime/payment/config_test.go create mode 100644 runtime/services/Dockerfile.node create mode 100644 runtime/services/Dockerfile.node.dockerignore diff --git a/README.md b/README.md index 593a99a..c061e43 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ flowchart TB ## Documentation +- [Managed paid operation](docs/paid-operation.md): configure fresh deployments and inspect payment readiness. - [App registry](docs/app-registry.md): publish app definitions and assign revisions to machines. - [Fleet discovery](docs/fleet-discovery.md): expose managed orchestrators through an aggregate inventory. - [Machine status](docs/machine-status.md): inspect rollout, configured health, registration, discovery and cleanup evidence. diff --git a/api/cmd/controlcenter/main.go b/api/cmd/controlcenter/main.go index 4e2e1a0..06a08bb 100644 --- a/api/cmd/controlcenter/main.go +++ b/api/cmd/controlcenter/main.go @@ -34,7 +34,7 @@ func command() *cobra.Command { func(ctx context.Context, raw string, _ bool) (*sql.DB, error) { return controlplane.OpenDB(ctx, raw, database.PGPassword) }) - root := boa.Cmd[boa.NoParams]{Use: "controlcenter", Short: "Livepeer machine control plane", SubCmds: []*cobra.Command{serve, migrate}}.ToCobra() + root := boa.Cmd[boa.NoParams]{Use: "controlcenter", Short: "Livepeer machine control plane", SubCmds: []*cobra.Command{serve, migrate, controlplane.PaymentsCommand()}}.ToCobra() root.SilenceUsage, root.SilenceErrors = true, true return root } diff --git a/api/cmd/controlcenter/main_test.go b/api/cmd/controlcenter/main_test.go index 7d0ef43..828481e 100644 --- a/api/cmd/controlcenter/main_test.go +++ b/api/cmd/controlcenter/main_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "os" + "path/filepath" "strings" "testing" ) @@ -52,3 +53,43 @@ func TestMigrationConfig(t *testing.T) { t.Fatal("migration must load database settings without reading application secrets", err) } } + +func TestPaymentCommandHelpDoesNotExposeSecrets(t *testing.T) { + cmd := command() + var out bytes.Buffer + cmd.SetOut(&out) + cmd.SetErr(&out) + cmd.SetArgs([]string{"payments", "apply", "--help"}) + if e := cmd.Execute(); e != nil { + t.Fatal(e) + } + for _, flag := range []string{"--file", "--expected-revision", "--config"} { + if !strings.Contains(out.String(), flag) { + t.Fatal("missing flag", flag) + } + } + for _, secret := range []string{"--payment-webhook-secret ", "--pg-password "} { + if strings.Contains(out.String(), secret) { + t.Fatal("secret CLI flag exposed") + } + } +} + +func TestPaymentInputRejectsUnknownPricingAndDuplicateFields(t *testing.T) { + t.Setenv("PG_CONNSTR", "postgres://unused.invalid/no-network") + for _, body := range []string{ + `{"version":1,"machines":{"lp-aaaaaaaaaaaaaaaa":{"version":1,"mode":"offchain","price":"1"}}}`, + `{"version":1,"version":1,"machines":{}}`, + `{"version":2,"machines":{}}`, + } { + path := filepath.Join(t.TempDir(), "payments.json") + if e := os.WriteFile(path, []byte(body), 0600); e != nil { + t.Fatal(e) + } + cmd := command() + cmd.SetArgs([]string{"payments", "apply", "--config=", "--file", path, "--expected-revision", "0"}) + if e := cmd.Execute(); e == nil || e.Error() != "invalid payment infrastructure document" { + t.Fatal("invalid input was not rejected before database access", e) + } + } +} diff --git a/api/config.example.toml b/api/config.example.toml index affdc80..5a3134f 100644 --- a/api/config.example.toml +++ b/api/config.example.toml @@ -28,7 +28,6 @@ PublicAPIURL = "http://localhost:41932" ConfigReconcileInterval = "1m" # Registry price validation only; actual Node payment configuration is separate. -RegistryPaymentMode = "offchain" # Machine ingress is opt-in. See docs/machine-tunnels.md before enabling it. CloudflareEnabled = false @@ -57,3 +56,6 @@ RuntimeNodeDrainTimeout = "12h" # 0-12h; 0s ends work immediately # TunnelStatusTTL = "" # at least 2m; longer than both poll loops # TunnelDrainTimeout = "" # TunnelNodeAddresses = [""] # complete fleet inventory + +# PaymentSecretsDir = "/run/payment-rpc" # immutable owner-only versioned files +# PaymentWebhookSecretFile = "/run/secrets/payment-webhook-auth" diff --git a/api/internal/controlplane/assignments.go b/api/internal/controlplane/assignments.go index 45ec152..f26f95f 100644 --- a/api/internal/controlplane/assignments.go +++ b/api/internal/controlplane/assignments.go @@ -181,7 +181,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if target.Generation != 0 && (target.Desired != "absent" || target.CompletedAt == nil) { return AdminChange{}, problem(409, "target_assigned", "Target must be unassigned or fully removed.") } - revision, e := revisionForBinding(ctx, tx, nil, ref, s.registryMode()) + revision, e := revisionForBinding(ctx, tx, nil, ref, node) if e != nil { return AdminChange{}, e } @@ -284,7 +284,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if old.Desired == "present" { current = &old.RevisionRef } - if _, e = revisionForBinding(ctx, tx, current, ref, s.registryMode()); e != nil { + if _, e = revisionForBinding(ctx, tx, current, ref, node); e != nil { return AdminChange{}, e } if e = machineapps.Append(ctx, tx, node, in.Epoch, u.ID, a); e != nil { diff --git a/api/internal/controlplane/config.go b/api/internal/controlplane/config.go index 0da0f3e..f0721ac 100644 --- a/api/internal/controlplane/config.go +++ b/api/internal/controlplane/config.go @@ -31,22 +31,24 @@ type Params struct { DatabaseParams TunnelParams DiscoveryParams - Listen string `env:"LISTEN_ADDR" default:"localhost:41932" descr:"HTTP listen address"` - PublicAPIURL string `env:"PUBLIC_API_URL" default:"http://localhost:41932" pattern:"^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*/?$" descr:"API URL reachable from runtime hosts and pods"` - SupabaseURL string `env:"SUPABASE_URL" min:"1" descr:"Supabase project URL"` - SupabasePublishableKey string `env:"SUPABASE_PUBLISHABLE_KEY" min:"1" descr:"Supabase browser-safe publishable key"` - RegistryPaymentMode string `env:"REGISTRY_PAYMENT_MODE" default:"offchain" alts:"offchain,onchain" descr:"Registry pricing policy; does not configure Node payments"` - DefaultAdminEmail string `env:"DEFAULT_ADMIN_EMAIL" optional:"true" descr:"Seed a pending administrator email only when no active grants exist"` - JWTSigningSecret string `env:"JWT_SIGNING_SECRET" secret:"true" min:"32" descr:"Persistent enrollment signing secret (at least 32 bytes)"` - JWTSigningSecretFile string `env:"JWT_SIGNING_SECRET_FILE" secretfor:"JWTSigningSecret" basepath:"source" descr:"File containing the enrollment signing secret"` - MachineTokenSecret string `env:"MACHINE_TOKEN_SECRET" secret:"true" min:"32" descr:"Persistent machine credential secret (at least 32 bytes)"` - MachineTokenSecretFile string `env:"MACHINE_TOKEN_SECRET_FILE" secretfor:"MachineTokenSecret" basepath:"source" descr:"File containing the machine credential secret"` - ConfigReconcileInterval time.Duration `env:"CONFIG_RECONCILE_INTERVAL" default:"1m" descr:"Desired configuration reconciliation interval"` - RuntimeImage string `env:"RUNTIME_IMAGE" descr:"Digest-pinned Go Runtime distribution for system services"` - RuntimeConnectorImage string `env:"RUNTIME_CONNECTOR_IMAGE" optional:"true" descr:"Digest-pinned Runtime connector image"` - RuntimeNodeImage string `env:"RUNTIME_NODE_IMAGE" optional:"true" descr:"Digest-pinned compatible Node image; empty keeps the bundled image"` - RuntimeNodeDrainTimeout time.Duration `env:"RUNTIME_NODE_DRAIN_TIMEOUT" default:"12h" descr:"Node app drain timeout, from zero to 12h"` - AppStopSignals bool `env:"APP_STOP_SIGNALS" default:"false" descr:"Render explicit stop signals only after enabling ContainerStopSignals on the host"` + Listen string `env:"LISTEN_ADDR" default:"localhost:41932" descr:"HTTP listen address"` + PublicAPIURL string `env:"PUBLIC_API_URL" default:"http://localhost:41932" pattern:"^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*/?$" descr:"API URL reachable from runtime hosts and pods"` + SupabaseURL string `env:"SUPABASE_URL" min:"1" descr:"Supabase project URL"` + SupabasePublishableKey string `env:"SUPABASE_PUBLISHABLE_KEY" min:"1" descr:"Supabase browser-safe publishable key"` + PaymentSecretsDir string `optional:"true" descr:"Owner-only immutable RPC secret versions directory"` + PaymentWebhookSecret string `secret:"true" optional:"true"` + PaymentWebhookSecretFile string `secretfor:"PaymentWebhookSecret" basepath:"source"` + DefaultAdminEmail string `env:"DEFAULT_ADMIN_EMAIL" optional:"true" descr:"Seed a pending administrator email only when no active grants exist"` + JWTSigningSecret string `env:"JWT_SIGNING_SECRET" secret:"true" min:"32" descr:"Persistent enrollment signing secret (at least 32 bytes)"` + JWTSigningSecretFile string `env:"JWT_SIGNING_SECRET_FILE" secretfor:"JWTSigningSecret" basepath:"source" descr:"File containing the enrollment signing secret"` + MachineTokenSecret string `env:"MACHINE_TOKEN_SECRET" secret:"true" min:"32" descr:"Persistent machine credential secret (at least 32 bytes)"` + MachineTokenSecretFile string `env:"MACHINE_TOKEN_SECRET_FILE" secretfor:"MachineTokenSecret" basepath:"source" descr:"File containing the machine credential secret"` + ConfigReconcileInterval time.Duration `env:"CONFIG_RECONCILE_INTERVAL" default:"1m" descr:"Desired configuration reconciliation interval"` + RuntimeImage string `env:"RUNTIME_IMAGE" descr:"Digest-pinned Go Runtime distribution for system services"` + RuntimeConnectorImage string `env:"RUNTIME_CONNECTOR_IMAGE" optional:"true" descr:"Digest-pinned Runtime connector image"` + RuntimeNodeImage string `env:"RUNTIME_NODE_IMAGE" optional:"true" descr:"Digest-pinned compatible Node image; empty keeps the bundled image"` + RuntimeNodeDrainTimeout time.Duration `env:"RUNTIME_NODE_DRAIN_TIMEOUT" default:"12h" descr:"Node app drain timeout, from zero to 12h"` + AppStopSignals bool `env:"APP_STOP_SIGNALS" default:"false" descr:"Render explicit stop signals only after enabling ContainerStopSignals on the host"` } var passwordPlaceholder = regexp.MustCompile(`(?i)\[(?:your[-_])?password\]|\[PG_PASSWORD\]`) diff --git a/api/internal/controlplane/config_test.go b/api/internal/controlplane/config_test.go index 9fc6929..187844b 100644 --- a/api/internal/controlplane/config_test.go +++ b/api/internal/controlplane/config_test.go @@ -77,16 +77,13 @@ DefaultAdminEmail = "first@example.invalid" if p.SupabaseURL != "https://auth.example" || p.SupabasePublishableKey != "public-key" || p.ConfigReconcileInterval != 75*time.Second || p.PublicAPIURL != "https://public.example" || p.Listen != "localhost:43000" { t.Fatal("configuration fields were not loaded") } - if p.RegistryPaymentMode != "offchain" { - t.Fatal("registry mode default missing") - } + if p.DefaultAdminEmail != "first@example.invalid" { t.Fatal("default admin config missing") } t.Setenv("DEFAULT_ADMIN_EMAIL", "environment@example.invalid") - t.Setenv("REGISTRY_PAYMENT_MODE", "onchain") p = Params{} - if err := (boa.Cmd[Params]{Params: &p, RawArgs: []string{"--config", filepath.Join(dir, "config.toml")}}).Validate(); err != nil || p.DefaultAdminEmail != "environment@example.invalid" || p.RegistryPaymentMode != "onchain" { + if err := (boa.Cmd[Params]{Params: &p, RawArgs: []string{"--config", filepath.Join(dir, "config.toml")}}).Validate(); err != nil || p.DefaultAdminEmail != "environment@example.invalid" { t.Fatal("admin environment override", err) } } @@ -94,7 +91,6 @@ DefaultAdminEmail = "first@example.invalid" func clearConfigEnv(t *testing.T) { t.Helper() t.Setenv("DEFAULT_ADMIN_EMAIL", "") - t.Setenv("REGISTRY_PAYMENT_MODE", "") for _, name := range []string{"CONTROL_CENTER_CONFIG", "PG_CONNSTR", "PG_CONNSTR_FILE", "PG_PASSWORD", "PG_PASSWORD_FILE", "LISTEN_ADDR", "PUBLIC_API_URL", "SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "JWT_SIGNING_SECRET", "JWT_SIGNING_SECRET_FILE", "MACHINE_TOKEN_SECRET", "MACHINE_TOKEN_SECRET_FILE", "CONFIG_RECONCILE_INTERVAL", "RUNTIME_IMAGE"} { t.Setenv(name, "") } @@ -134,7 +130,6 @@ func TestConfigValidation(t *testing.T) { {func(p *Params) { p.JWTSigningSecret, p.MachineTokenSecret = "", "" }, "missing required param 'jwt-signing-secret'"}, {func(p *Params) { p.SupabaseURL = "" }, "missing required param 'supabase-url'"}, {func(p *Params) { p.DefaultAdminEmail = "Name " }, "single email address"}, - {func(p *Params) { p.RegistryPaymentMode = "invalid" }, "registry-payment-mode"}, } { p := testParams() p.SupabaseURL = "https://auth.example" diff --git a/api/internal/controlplane/machine_credentials.go b/api/internal/controlplane/machine_credentials.go index 9df0f2c..a92aa79 100644 --- a/api/internal/controlplane/machine_credentials.go +++ b/api/internal/controlplane/machine_credentials.go @@ -13,6 +13,7 @@ import ( "net/http" "strconv" "strings" + "time" "uuid" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" @@ -243,6 +244,12 @@ func (s *Server) machineStatus(w http.ResponseWriter, r *http.Request) { } return } + if report.Component == "runtime" && !report.ClockUncertain && !report.ObservedAt.Before(time.Now().Add(-2*time.Minute)) { + if e := s.observePaymentGrant(r.Context(), m, report.Payment, report.ConfigDigest); e != nil { + s.databaseError(w, e) + return + } + } if wake { s.requestReconcile() } diff --git a/api/internal/controlplane/machineconfig.go b/api/internal/controlplane/machineconfig.go index 742576c..b37b8e2 100644 --- a/api/internal/controlplane/machineconfig.go +++ b/api/internal/controlplane/machineconfig.go @@ -1,7 +1,10 @@ package controlplane import ( + "context" "encoding/json" + "github.com/livepeer/control-center/api/internal/controlplane/payments" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" "github.com/livepeer/control-center/api/internal/controlplane/tunnel" @@ -13,6 +16,9 @@ func exposure(r tunnel.RoutingState) *machineconfig.Exposure { func (s *Server) newConfigurationManager() *machineconfig.Manager { p := s.params return machineconfig.New(machineconfig.Config{APIURL: p.PublicAPIURL, DrainTimeout: p.TunnelDrainTimeout, StatusTTL: p.TunnelStatusTTL, RuntimeImage: p.RuntimeImage, NodeImage: p.RuntimeNodeImage, NodeDrainTimeout: &p.RuntimeNodeDrainTimeout, StopSignals: p.AppStopSignals, Connector: machineconfig.ConnectorConfig{Image: p.RuntimeConnectorImage, NodeAddresses: p.TunnelNodeAddresses}}, machineconfig.Dependencies{DB: s.db, Logger: s.logger, + Payment: func(ctx context.Context, m machineconfig.Machine) (payment.Config, error) { + return payments.Load(ctx, s.db, m.NodeID) + }, Exposure: func(raw json.RawMessage) (*machineconfig.Exposure, error) { var r tunnel.RoutingState err := json.Unmarshal(raw, &r) diff --git a/api/internal/controlplane/machineconfig/apps.go b/api/internal/controlplane/machineconfig/apps.go index ed51ac1..bd8e077 100644 --- a/api/internal/controlplane/machineconfig/apps.go +++ b/api/internal/controlplane/machineconfig/apps.go @@ -30,6 +30,16 @@ func (s *Manager) prepareApps(ctx context.Context, m *Desired, lookupErr error) } p := appbundle.Unavailable() err := lookupErr + if err == nil && m.Apps != nil { + for _, a := range m.Apps.Entries { + if a.Revision != nil && a.Desired == "present" { + if e := m.Payment.Compatible(a.Revision.Definition); e != nil { + err = e + break + } + } + } + } if err == nil && m.Apps != nil { p, err = appbundle.Render(*m.Apps, appbundle.Options{StopSignals: m.StopSignals}) } @@ -112,6 +122,9 @@ func addManagedApps(files map[string][]byte, m Desired) error { } if prior, e := transport.ReadMetadata(m.RetainedFiles["runtime.json"]); e == nil { metadata.ConfigDigest = prior.ConfigDigest + metadata.Payment = prior.Payment + metadata.PaymentCredentialsRef = prior.PaymentCredentialsRef + metadata.PaymentActive = false // Retained connectors may restart while the backend still authorizes app cleanup. metadata.TunnelID, metadata.TokenGeneration, metadata.ProviderVersion, metadata.ConnectorTokenRef = prior.TunnelID, prior.TokenGeneration, prior.ProviderVersion, prior.ConnectorTokenRef files["runtime.json"], err = json.Marshal(metadata) diff --git a/api/internal/controlplane/machineconfig/bundle.go b/api/internal/controlplane/machineconfig/bundle.go index fa6777d..c6d6669 100644 --- a/api/internal/controlplane/machineconfig/bundle.go +++ b/api/internal/controlplane/machineconfig/bundle.go @@ -3,8 +3,10 @@ package machineconfig import ( "bytes" "embed" + "encoding/json" "fmt" "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/payment" "io/fs" "strings" "time" @@ -20,6 +22,26 @@ func Build(m Desired) ([]byte, string, error) { if m.NodeImage != "" && !ValidConnectorImage(m.NodeImage) { return nil, "", fmt.Errorf("Node image is not pinned") } + if m.PaymentError != nil { + return nil, "", m.PaymentError + } + if m.Payment.Version == 0 { + m.Payment = payment.Offchain() + } + if m.State.HeldOrchestrator != "" && m.State.HeldPayment != "" { + var held payment.Config + if json.Unmarshal([]byte(m.State.HeldPayment), &held) != nil { + return nil, "", fmt.Errorf("invalid held payment identity") + } + if held.Version != 0 { + if err := held.Validate(); err != nil { + return nil, "", err + } + } + } + if err := m.Payment.Validate(); err != nil { + return nil, "", err + } files := map[string][]byte{} err := fs.WalkDir(templates, "templates", func(path string, entry fs.DirEntry, err error) error { if err != nil { diff --git a/api/internal/controlplane/machineconfig/connector.go b/api/internal/controlplane/machineconfig/connector.go index 5ef092c..b3dc765 100644 --- a/api/internal/controlplane/machineconfig/connector.go +++ b/api/internal/controlplane/machineconfig/connector.go @@ -82,7 +82,7 @@ spec: - from: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: flux-system}} podSelector: {matchLabels: {app: livepeer-app-reconciler}} - ports: [{protocol: TCP, port: 8935}] + ports: [{protocol: TCP, port: 8935}, {protocol: TCP, port: 8936}] - from: - podSelector: {matchLabels: {livepeer.io/runner-control: 'true'}} ports: [{protocol: TCP, port: 8935}] diff --git a/api/internal/controlplane/machineconfig/manager.go b/api/internal/controlplane/machineconfig/manager.go index 7fa52f6..a3159cb 100644 --- a/api/internal/controlplane/machineconfig/manager.go +++ b/api/internal/controlplane/machineconfig/manager.go @@ -7,6 +7,7 @@ import ( "errors" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/schema" "log/slog" "time" @@ -23,6 +24,7 @@ type Config struct { } type Dependencies struct { + Payment func(context.Context, Machine) (payment.Config, error) DB *sql.DB Logger *slog.Logger Exposure func(json.RawMessage) (*Exposure, error) @@ -51,7 +53,22 @@ func (s *Manager) Desired(m Machine, state State, exposure *Exposure) Desired { if s.config.Connector.Image != "" { connector.Image = s.config.Connector.Image } - return Desired{Machine: m, State: state, Exposure: exposure, Connector: connector, ControlAPIURL: s.config.APIURL, RuntimeImage: s.config.RuntimeImage, NodeImage: s.config.NodeImage, NodeDrainTimeout: s.config.NodeDrainTimeout, StopSignals: s.config.StopSignals, DrainTimeout: s.drainTimeout()} + p := payment.Offchain() + var err error + if s.deps.Payment != nil { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + p, err = s.deps.Payment(ctx, m) + cancel() + } + + d := Desired{Payment: p, PaymentError: err, Machine: m, State: state, Exposure: exposure, Connector: connector, ControlAPIURL: s.config.APIURL, RuntimeImage: s.config.RuntimeImage, NodeImage: s.config.NodeImage, NodeDrainTimeout: s.config.NodeDrainTimeout, StopSignals: s.config.StopSignals, DrainTimeout: s.drainTimeout()} + if p.Paid() && s.store.DB != nil { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + r, at, e := s.store.Report(ctx, m, "runtime") + cancel() + d.PaymentReady = e == nil && !r.ClockUncertain && time.Since(ObservationTime(r, at)) <= s.config.StatusTTL && r.Ready && r.Payment != nil && r.Payment.Ready && r.Payment.Applied && r.Payment.Generation == p.Generation && r.ConfigDigest == Digest(d) + } + return d } func (s *Manager) drainTimeout() time.Duration { if s.config.DrainTimeout <= 0 { @@ -199,6 +216,7 @@ func (s *Manager) planManagement(ctx context.Context, m Machine, record *Record) } record.State = before record.HeldOrchestrator = manifest + record.HeldPayment = paymentJSON(old.Payment) s.holdUpgrade(ctx, m, &record.State) record.RolloutReason = "lifecycle_observation_failed" if old.IngressDigest != "" { @@ -223,11 +241,12 @@ func (s *Manager) plan(ctx context.Context, m Machine, record *Record) (*Exposur return exposure, false, nil } if (record.Lifecycle == "draining" || record.Target != "") && record.HeldOrchestrator == "" { - _, manifest, e := s.applied(ctx, m) + old, manifest, e := s.applied(ctx, m) if e != nil { return nil, false, e } record.HeldOrchestrator = manifest + record.HeldPayment = paymentJSON(old.Payment) } if record.Lifecycle == "draining" { done, e := s.removalComplete(ctx, m, &record.State) diff --git a/api/internal/controlplane/machineconfig/observations.go b/api/internal/controlplane/machineconfig/observations.go index 952b7af..5905003 100644 --- a/api/internal/controlplane/machineconfig/observations.go +++ b/api/internal/controlplane/machineconfig/observations.go @@ -19,6 +19,28 @@ func validCode(s string) bool { return s == "" || statusCode.MatchString(s) } func optionalID(s string) bool { return s == "" || statusID.MatchString(s) } func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) error { + if p := r.Payment; p != nil { + if r.Component != "runtime" || (p.Mode != "paid" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || p.Unsettled < 0 || p.Unsettled > 10000000 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { + return ErrStaleStatus + } + if p.Applied { + meta, _, err := s.applied(ctx, m) + if err != nil || r.ConfigDigest != meta.ConfigDigest || p.Generation != meta.Payment.Generation || p.Mode != meta.Payment.Mode || p.PodUID == "" { + return ErrStaleStatus + } + if p.Mode == "paid" { + var known bool + err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.payment_grants WHERE grant_id::text=$1 AND node_id=$2 AND epoch=$3 AND payment_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, m.Epoch, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) + if err != nil { + return err + } + if !known { + return ErrStaleStatus + } + } + } + } + if !optionalID(r.ObserverID) { return ErrStaleStatus } diff --git a/api/internal/controlplane/machineconfig/payment.go b/api/internal/controlplane/machineconfig/payment.go new file mode 100644 index 0000000..21d0662 --- /dev/null +++ b/api/internal/controlplane/machineconfig/payment.go @@ -0,0 +1,90 @@ +package machineconfig + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "fmt" + "net/url" + "strings" + + "github.com/BurntSushi/toml" + "github.com/livepeer/control-center/runtime/payment" +) + +func effectivePayment(m Desired) payment.Config { + c := m.Payment + if m.State.HeldOrchestrator != "" && m.State.HeldPayment != "" { + c = payment.Config{} + _ = json.Unmarshal([]byte(m.State.HeldPayment), &c) + } + if c.Version == 0 { + c = payment.Offchain() + } + return c +} +func specializePayment(raw string, m Desired) string { + if !strings.Contains(raw, " orchestrator.toml: |\n") { + return raw + } + // The Service remains a private route to a live process during dependency loss. + raw = strings.Replace(raw, "spec:\n selector:\n app: orchestrator", "spec:\n publishNotReadyAddresses: true\n selector:\n app: orchestrator", 1) + c := m.Payment + if !c.Paid() { + return raw + } + endpoint, _ := url.Parse(c.RedeemerURL) + meta, _ := json.Marshal(c) + hash := sha256.Sum256(meta) + raw = strings.Replace(raw, "livepeer.io/config-sha256:", fmt.Sprintf("livepeer.io/payment-sha256: '%x'\n livepeer.io/config-sha256:", hash), 1) + settings := map[string]any{"Network": c.Network, "ChainID": c.ChainID, "Controller": c.Controller, "OrchestratorAddress": c.Recipient, "RPCURLFile": "/run/payment/private/rpc", "RedeemerGrants": c.RedeemerGrants, "RedeemerHeadersFile": "/run/payment/private/headers", "RedeemerDB": "/data/payments.sqlite", "TicketFaceValue": c.TicketFaceValue, "TicketWinProb": c.TicketWinProb, "MaxPendingTickets": c.MaxPendingTickets, "MaxTicketsPerRecipient": c.MaxTicketsPerRecipient} + if c.WeiPerUSD != "" { + settings["WeiPerUSD"] = c.WeiPerUSD + } else { + settings["ETHUSDFeed"] = c.ETHUSDFeed + settings["PriceMaxAge"] = c.PriceMaxAge + } + var b bytes.Buffer + if toml.NewEncoder(&b).Encode(settings) != nil { + return raw + } + text := strings.TrimSuffix(b.String(), "\n") + text = " " + strings.ReplaceAll(text, "\n", "\n ") + raw = strings.Replace(raw, ` Network = "offchain"`, text, 1) + // Node's URL field is a TOML table. Keep it last so subsequent global + // settings are not accidentally decoded as URL fields. + b.Reset() + _ = toml.NewEncoder(&b).Encode(map[string]any{"RedeemerURL": map[string]string{"Scheme": endpoint.Scheme, "Host": endpoint.Host, "Path": endpoint.Path}}) + text = " " + strings.ReplaceAll(strings.TrimSuffix(b.String(), "\n"), "\n", "\n ") + const marker = " orchestrator.toml: |\n" + head, config, _ := strings.Cut(raw, marker) + body, tail, _ := strings.Cut(config, "\n---") + raw = head + marker + body + "\n" + text + "\n---" + tail + raw = strings.Replace(raw, " args:\n", ` command: [/usr/local/bin/livepeer-runtime, orchestrator-start] + env: + - {name: POD_NAME, valueFrom: {fieldRef: {fieldPath: metadata.name}}} + - {name: POD_UID, valueFrom: {fieldRef: {fieldPath: metadata.uid}}} + args: +`, 1) + // The wrapper executes /usr/local/bin/livepeer with these same Node arguments. + raw = strings.Replace(raw, " - name: config\n mountPath:", " - {name: payment, mountPath: /run/payment}\n - {name: management, mountPath: /management, readOnly: true}\n - name: config\n mountPath:", 1) + raw = strings.Replace(raw, " volumes:\n", fmt.Sprintf(" volumes:\n - name: payment\n emptyDir: {medium: Memory, sizeLimit: 1Mi}\n - name: management\n hostPath: {path: '%s/volumes/management-sockets/orchestrator', type: Directory}\n", m.InstallDir), 1) + raw = strings.Replace(raw, " readinessProbe:\n httpGet:\n path: /readyz\n port: metrics", " readinessProbe:\n timeoutSeconds: 5\n periodSeconds: 5\n exec:\n command: [/usr/local/bin/livepeer-runtime, orchestrator-probe]", 1) + return raw +} + +func paymentNetwork(c payment.Config) string { + var b strings.Builder + for _, g := range append(append([]string{}, c.RPCGrants...), c.RedeemerGrants...) { + a, p, e := payment.Grant(g) + if e != nil { + continue + } + bits := 128 + if a.Is4() { + bits = 32 + } + fmt.Fprintf(&b, " - to: [{ipBlock: {cidr: '%s/%d'}}]\n ports: [{protocol: TCP, port: %d}]\n", a, bits, p) + } + return b.String() +} diff --git a/api/internal/controlplane/machineconfig/payment_test.go b/api/internal/controlplane/machineconfig/payment_test.go new file mode 100644 index 0000000..ce72b59 --- /dev/null +++ b/api/internal/controlplane/machineconfig/payment_test.go @@ -0,0 +1,128 @@ +package machineconfig + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/transport" + "go.yaml.in/yaml/v3" +) + +func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { + c := payment.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} + m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} + b, d, e := Build(m) + if e != nil { + t.Fatal(e) + } + again, dd, e := Build(m) + if e != nil || d != dd || !bytes.Equal(b, again) { + t.Fatal("unstable bundle", e) + } + files, e := artifact.Read(b) + if e != nil { + t.Fatal(e) + } + for name, body := range files { + if !strings.HasSuffix(name, ".yaml") { + continue + } + decoder := yaml.NewDecoder(bytes.NewReader(body)) + for { + var document map[string]any + if e := decoder.Decode(&document); e == io.EOF { + break + } else if e != nil { + t.Fatal("invalid paid manifest", name, e) + } + } + } + node := string(files["system/node/orchestrator.yaml"]) + if binary := os.Getenv("NODE_BINARY"); binary != "" { + dir := t.TempDir() + config := configurationFromManifest(node) + for key, value := range map[string]string{"/run/payment/private/rpc": "https://rpc.example", "/run/payment/private/headers": "Authorization: Bearer test-only", "/credentials/secret": "bootstrap-test-only"} { + file := filepath.Join(dir, filepath.Base(key)) + if e := os.WriteFile(file, []byte(value), 0600); e != nil { + t.Fatal(e) + } + config = strings.ReplaceAll(config, key, file) + } + config = strings.ReplaceAll(config, `"/data`, `"`+filepath.Join(dir, "data")) + path := filepath.Join(dir, "orchestrator.toml") + os.WriteFile(path, []byte(config), 0600) + if output, e := exec.Command(binary, "--config", path, "--print-config").CombinedOutput(); e != nil { + t.Fatal("actual Node rejected paid configuration", e, string(output)) + } + } + for _, want := range []string{"orchestrator-start", "orchestrator-probe", "publishNotReadyAddresses: true", "fsGroupChangePolicy: OnRootMismatch", "RPCURLFile", "RedeemerHeadersFile", "/data/payments.sqlite", "medium: Memory"} { + if !strings.Contains(node, want) { + t.Fatal("missing", want) + } + } + if strings.Contains(node, "rpc-v1") || strings.Contains(node, "KeystorePassword") { + t.Fatal("credential value/reference in Node config") + } + if !strings.Contains(string(files["management/app-reconciler.yaml"]), "10.0.0.3/32") { + t.Fatal("missing private endpoint policy") + } + original := Digest(m) + m.Payment.Generation++ + m.Payment.CredentialRevision++ + if Digest(m) == original { + t.Fatal("credential generation failed to restart Node") + } + m.State.HeldOrchestrator = node + m.State.HeldPayment = paymentJSON(c) + meta := DesiredRuntime(m) + if meta.Payment.Generation != c.Generation || meta.ConfigDigest != original { + t.Fatal("held workload borrowed desired payment identity", meta) + } + var parsed Runtime + if json.Unmarshal(files["runtime.json"], &parsed) != nil || parsed.Payment.Recipient != c.Recipient { + t.Fatal("payment metadata absent") + } + // Fields omitted by a held offchain identity must not survive from the + // desired paid configuration while the existing workload drains. + free := m + free.State.HeldOrchestrator, free.State.HeldPayment = "", "" + free.Payment = payment.Offchain() + freeBundle, _, e := Build(free) + if e != nil { + t.Fatal(e) + } + freeFiles, _ := artifact.Read(freeBundle) + m.State.HeldOrchestrator = string(freeFiles["system/node/orchestrator.yaml"]) + m.State.HeldPayment = paymentJSON(payment.Offchain()) + b, _, e = Build(m) + if e != nil { + t.Fatal(e) + } + files, _ = artifact.Read(b) + parsed, e = transport.ReadMetadata(files["runtime.json"]) + if e != nil || parsed.Payment.Paid() || parsed.Payment.Recipient != "" || parsed.Payment.RPCSecret != "" { + t.Fatal("held offchain workload inherited desired paid inputs", parsed.Payment, e) + } +} + +func TestPaymentLookupFailureDoesNotBeginWithdrawal(t *testing.T) { + manager := New(Config{}, Dependencies{}) + state := State{Lifecycle: "active", Generation: 4, ApprovedConfigDigest: strings.Repeat("a", 64)} + before := state + desired := Desired{PaymentError: fmt.Errorf("payment lookup unavailable")} + if _, e := manager.Gate(t.Context(), Machine{}, &state, desired); e == nil || state != before { + t.Fatal("failed lookup changed rollout", e, state) + } + if _, e := manager.StageTarget(t.Context(), Machine{}, &state, desired, "endpoint"); e == nil || state != before { + t.Fatal("failed lookup changed target", e, state) + } +} diff --git a/api/internal/controlplane/machineconfig/reports.go b/api/internal/controlplane/machineconfig/reports.go index 534e4d5..63d08ab 100644 --- a/api/internal/controlplane/machineconfig/reports.go +++ b/api/internal/controlplane/machineconfig/reports.go @@ -47,7 +47,7 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b return false, ErrStaleStatus } } - reasons := map[string]bool{"ready": true, "applying": true, "offline": true, "failed": true, "drain_pending": true, "removed": true, "tls_pending": true} + reasons := map[string]bool{"payment_not_ready": true, "ready": true, "applying": true, "offline": true, "failed": true, "drain_pending": true, "removed": true, "tls_pending": true} if !reasons[report.Reason] { report.Reason = "failed" } @@ -95,7 +95,8 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b if previous.Drained && previous.Generation == report.Generation && previous.Evidence != nil && report.Evidence != nil && previous.Evidence.Target == report.Evidence.Target && time.Now().Before(previous.Evidence.ExpiresAt) { drainWake = false } - return drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil + paymentWake := report.Component == "runtime" && report.Payment != nil && (record.RolloutReason == "payment_drain_pending" || (report.Payment.Mode == "paid" && record.ApprovedConfigDigest != report.ConfigDigest)) + return paymentWake || drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil } func validDrainEvidence(m Machine, state State, report Report, now time.Time) bool { diff --git a/api/internal/controlplane/machineconfig/rollout.go b/api/internal/controlplane/machineconfig/rollout.go index 5a770b8..9db8ef1 100644 --- a/api/internal/controlplane/machineconfig/rollout.go +++ b/api/internal/controlplane/machineconfig/rollout.go @@ -3,9 +3,11 @@ package machineconfig import ( "context" "database/sql" + "encoding/json" "errors" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/payment" "time" ) @@ -24,6 +26,12 @@ func (s *Manager) applied(ctx context.Context, m Machine) (Runtime, string, erro // Gate holds the applied workload until a fresh report completes its drain. // The caller saves this state under the enrollment's lease before publication. func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Desired) (bool, error) { + if desired.PaymentError != nil { + return false, desired.PaymentError + } + if desired.Payment.Paid() { + state.PaymentSettled = false + } old, manifest, err := s.applied(ctx, m) if err != nil { return false, err @@ -32,6 +40,19 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des desired.State.HeldOrchestrator = "" desired.State.HeldUpgradePlan = "" digest := Digest(desired) + // Admission has never opened for this paid target. Its image or rendering + // can be repaired without asking the failed process to drain again, while + // retaining the exact payment/storage binding and the admission freeze. + frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested && !state.PaymentDrainAfter.IsZero() + initial := state.ApplyingConfigDigest == "" && state.ApprovedConfigDigest == "" + if old.ConfigDigest != digest && old.Payment.Paid() && !old.PaymentActive && state.ApprovedConfigDigest != old.ConfigDigest && paymentJSON(old.Payment) == paymentJSON(desired.Payment) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { + state.HeldOrchestrator, state.HeldUpgradePlan = "", "" + state.ApplyingConfigDigest = digest + state.ApplyingUpgradeVersion = upgradeVersion(desired) + state.PendingConfigDigest = digest + state.RolloutReason = "rollout_pending" + return false, nil + } if state.ApplyingConfigDigest != "" { if state.ApplyingConfigDigest == digest { report, at, e := s.store.Report(ctx, m, "runtime") @@ -55,6 +76,14 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des state.ApplyingUpgradeVersion = "" } if state.HeldOrchestrator == "" && (state.ApprovedConfigDigest == digest || old.ConfigDigest == digest) { + if desired.Payment.Paid() && state.ApprovedConfigDigest != digest { + if !desired.PaymentReady { + state.RolloutReason = "payment_startup_pending" + return false, nil + } + state.ApprovedConfigDigest = digest + state.RolloutReason = "" + } return false, nil } if state.PendingConfigDigest != digest { @@ -65,6 +94,7 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des state.DrainRequested = true state.DrainStartedAt = time.Now().UTC() state.HeldOrchestrator = manifest + state.HeldPayment = paymentJSON(old.Payment) s.holdUpgrade(ctx, m, state) } if old.ConfigDigest != digest { @@ -73,6 +103,15 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des return true, err } } + if old.Payment.Paid() && (!desired.Payment.Paid() || desired.Payment.RedeemerURL != old.Payment.RedeemerURL) { + if !s.paymentDrained(ctx, m, old, state.PaymentDrainAfter) { + state.RolloutReason = "payment_drain_pending" + return true, nil + } + if !desired.Payment.Paid() { + state.PaymentSettled = true + } + } state.HeldOrchestrator = "" state.HeldUpgradePlan = "" state.ApplyingConfigDigest = digest @@ -85,6 +124,9 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des // StageTarget drains for a change whose external prerequisites are prepared by // another subsystem. Gate releases the held workload once those facts are ready. func (s *Manager) StageTarget(ctx context.Context, m Machine, state *State, desired Desired, target string) (bool, error) { + if desired.PaymentError != nil { + return false, desired.PaymentError + } old, manifest, err := s.applied(ctx, m) if err != nil { return false, err @@ -105,6 +147,7 @@ func (s *Manager) StageTarget(ctx context.Context, m Machine, state *State, desi state.DrainStartedAt = time.Now().UTC() state.PendingConfigDigest = digest state.HeldOrchestrator = manifest + state.HeldPayment = paymentJSON(old.Payment) s.holdUpgrade(ctx, m, state) } done, err := s.drainComplete(ctx, m, state) @@ -145,6 +188,7 @@ func (s *Manager) drainComplete(ctx context.Context, m Machine, state *State) (b return false, err } if report.Drained && report.Generation == state.Generation && time.Since(at) <= s.config.StatusTTL && validDrainEvidence(m, *state, report, time.Now()) { + state.PaymentDrainAfter = evidenceTime(report) state.RolloutReason = "" return true, nil } @@ -166,6 +210,14 @@ func (s *Manager) removalComplete(ctx context.Context, m Machine, state *State) state.RolloutReason = "app_cleanup_pending" return false, err } + old, _, e := s.applied(ctx, m) + if e != nil { + return false, e + } + if !s.paymentDrained(ctx, m, old, state.PaymentDrainAfter) { + state.RolloutReason = "payment_drain_pending" + return false, nil + } state.RolloutReason = "" return true, nil } @@ -175,10 +227,47 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { if err != nil || !done { return false, err } - result, err := s.store.DB.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$5 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND lease_id=$3 AND revision=$4 AND lease_until>now())`, l.Machine.NodeID, l.Machine.Epoch, l.ID, l.Revision, l.Machine.CredentialVersion) + tx, err := s.store.DB.BeginTx(ctx, nil) if err != nil { return false, err } - n, err := result.RowsAffected() - return n == 1, err + defer tx.Rollback() + var yes int + err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$3 FOR UPDATE`, l.Machine.NodeID, l.Machine.Epoch, l.Machine.CredentialVersion).Scan(&yes) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND lease_id=$3 AND revision=$4 AND lease_until>now() FOR UPDATE`, l.Machine.NodeID, l.Machine.Epoch, l.ID, l.Revision).Scan(&yes) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + if _, err = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET drained=true WHERE node_id=$1`, l.Machine.NodeID); err != nil { + return false, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2`, l.Machine.NodeID, l.Machine.Epoch); err != nil { + return false, err + } + return true, tx.Commit() +} + +func paymentJSON(c payment.Config) string { b, _ := json.Marshal(c); return string(b) } +func (s *Manager) paymentDrained(ctx context.Context, m Machine, old Runtime, after time.Time) bool { + if !old.Payment.Paid() { + return true + } + r, at, e := s.store.Report(ctx, m, "runtime") + return e == nil && !after.IsZero() && !r.ObservedAt.Before(after) && r.Generation == old.Generation && !r.ClockUncertain && time.Since(at) <= s.config.StatusTTL && time.Since(r.ObservedAt) <= s.config.StatusTTL && r.ConfigDigest == old.ConfigDigest && r.Payment != nil && r.Payment.Generation == old.Payment.Generation && r.Payment.Applied && r.Payment.QueueKnown && r.Payment.Unsettled == 0 +} + +func evidenceTime(r Report) time.Time { + if r.Evidence == nil { + return time.Time{} + } + return r.Evidence.ObservedAt } diff --git a/api/internal/controlplane/machineconfig/runtime.go b/api/internal/controlplane/machineconfig/runtime.go index 38b3069..3fa2481 100644 --- a/api/internal/controlplane/machineconfig/runtime.go +++ b/api/internal/controlplane/machineconfig/runtime.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" "regexp" "strings" "time" @@ -77,6 +78,7 @@ func specializeNode(raw string, m Desired) string { if m.NodeDrainTimeout != nil { timeout = *m.NodeDrainTimeout } + raw = specializePayment(raw, m) raw = strings.ReplaceAll(raw, "@NODE_DRAIN_TIMEOUT@", timeout.String()) if m.NodeImage != "" { raw = regexp.MustCompile(`(?m)^ image: ghcr.io/livepeer/node:[^\n]+`).ReplaceAllString(raw, " image: "+m.NodeImage) @@ -94,6 +96,14 @@ type Runtime = contract.Metadata func DesiredRuntime(m Desired) Runtime { d := Runtime{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Generation: 1, Terminal: m.Terminal, ConfigDigest: Digest(m), ServiceURL: PrivateOrchestrator, APIURL: m.ControlAPIURL} + d.Payment = effectivePayment(m) + if d.Payment.Version == 0 { + d.Payment = payment.Offchain() + } + d.PaymentActive = !m.State.DrainRequested && m.State.ApplyingConfigDigest == "" && (!d.Payment.Paid() || (m.PaymentReady && m.State.ApprovedConfigDigest == d.ConfigDigest)) + if d.Payment.Paid() { + d.PaymentCredentialsRef = "/v1/nodes/" + m.NodeID + "/payment/credentials" + } d.RunnerServiceURL = PrivateOrchestrator d.Generation = max(m.State.Generation, 1) d.DrainRequested = m.State.DrainRequested diff --git a/api/internal/controlplane/machineconfig/system.go b/api/internal/controlplane/machineconfig/system.go index 53628af..82e730e 100644 --- a/api/internal/controlplane/machineconfig/system.go +++ b/api/internal/controlplane/machineconfig/system.go @@ -80,6 +80,9 @@ func addSystemWorkloads(files map[string][]byte, m Desired) error { continue } files[prefix+"system/node/network.yaml"] = []byte(nodeNetwork()) + if effectivePayment(m).Paid() { + files[prefix+"management/app-reconciler.yaml"] = append(files[prefix+"management/app-reconciler.yaml"], []byte("\n---\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata: {name: orchestrator-payment-egress, namespace: livepeer}\nspec:\n podSelector: {matchLabels: {app: orchestrator}}\n policyTypes: [Egress]\n egress:\n"+paymentNetwork(effectivePayment(m)))...) + } files[prefix+"system/node/kustomization.yaml"] = kustomize("orchestrator.yaml", "network.yaml") connectorResources := []string{} if files[prefix+"system/connector/tunnel.yaml"] != nil { diff --git a/api/internal/controlplane/machineconfig/system_test.go b/api/internal/controlplane/machineconfig/system_test.go index 3c32dac..56dfd54 100644 --- a/api/internal/controlplane/machineconfig/system_test.go +++ b/api/internal/controlplane/machineconfig/system_test.go @@ -126,8 +126,8 @@ func TestProxyRoutingFollowsHeldNodeConfiguration(t *testing.T) { private := build() m.Exposure = &Exposure{TunnelID: "tunnel", ServiceURL: "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.a.invalid", ProxyURLTemplate: "https://{proxy}.lp-aaaaaaaaaaaaaaaa.a.invalid", IngressDigest: "ingress"} a := build() - if !strings.Contains(string(a[prefix+nodeFile]), `APIOriginURL = "`+PrivateOrchestrator+`"`) { - t.Fatal("public Node routing omitted the private API origin") + if !strings.Contains(string(a[prefix+nodeFile]), `RunnerServiceURL = "`+PrivateOrchestrator+`"`) { + t.Fatal("public Node routing omitted the private runner callback URL") } m.State.HeldOrchestrator = string(a[prefix+nodeFile]) m.Exposure.ServiceURL = "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.b.invalid" diff --git a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml index 01c6ca9..5210875 100644 --- a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml +++ b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml @@ -61,7 +61,6 @@ data: Listen = "unsafe@0.0.0.0:8935" MetricsListen = "unsafe@0.0.0.0:8936" ServiceURL = "@SERVICE_URL@" - APIOriginURL = "http://orchestrator.livepeer.svc.cluster.local:8935" RunnerServiceURL = "http://orchestrator.livepeer.svc.cluster.local:8935" ProxyURLTemplate = "@PROXY_URL_TEMPLATE@" BootstrapSecretFile = "/credentials/secret" @@ -97,6 +96,7 @@ spec: runAsUser: 65532 runAsGroup: 65532 fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch seccompProfile: type: RuntimeDefault containers: diff --git a/api/internal/controlplane/machineconfig/types.go b/api/internal/controlplane/machineconfig/types.go index 6fee554..e202058 100644 --- a/api/internal/controlplane/machineconfig/types.go +++ b/api/internal/controlplane/machineconfig/types.go @@ -4,6 +4,7 @@ package machineconfig import ( "github.com/livepeer/control-center/runtime/appbundle" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/schema" "regexp" "time" @@ -29,6 +30,9 @@ type State struct { DrainStartedAt time.Time `json:"drain_started_at,omitempty"` DrainedGeneration int64 `json:"drained_generation,omitempty"` Target string `json:"target,omitempty"` + PaymentSettled bool `json:"payment_settled,omitempty"` + PaymentDrainAfter time.Time `json:"payment_drain_after,omitempty"` + HeldPayment string `json:"held_payment,omitempty"` HeldOrchestrator string `json:"held_orchestrator,omitempty"` PendingConfigDigest string `json:"pending_config_digest,omitempty"` ApprovedConfigDigest string `json:"approved_config_digest,omitempty"` @@ -55,6 +59,9 @@ type ConnectorConfig struct { } type Desired struct { + Payment payment.Config + PaymentError error + PaymentReady bool Machine Apps *schema.AppAssignmentSetV1 State State @@ -77,6 +84,7 @@ var imageDigestPattern = regexp.MustCompile(`^[a-zA-Z0-9./:_-]+@sha256:[0-9a-f]{ func ValidConnectorImage(image string) bool { return imageDigestPattern.MatchString(image) } type Report struct { + Payment *payment.Observation `json:"payment,omitempty"` ObserverID string `json:"observer_id,omitempty"` ObserverStartedAt time.Time `json:"observer_started_at,omitempty"` ClockUncertain bool `json:"clock_uncertain,omitempty"` diff --git a/api/internal/controlplane/migrations/001_initial.sql b/api/internal/controlplane/migrations/001_initial.sql index 34e6a5f..a1dadd4 100644 --- a/api/internal/controlplane/migrations/001_initial.sql +++ b/api/internal/controlplane/migrations/001_initial.sql @@ -18,6 +18,30 @@ CREATE TABLE lpcc.machine_configs ( sha256 TEXT NOT NULL CHECK(sha256 ~ '^[0-9a-f]{64}$'), generated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); +-- Payment infrastructure is part of the fresh-install schema. These records +-- deliberately survive enrollment and Auth account deletion. +CREATE TABLE lpcc.payment_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); +INSERT INTO lpcc.payment_revision DEFAULT VALUES; +CREATE TABLE lpcc.payment_machines ( + node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), + recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', + generation BIGINT NOT NULL CHECK(generation>0), config JSONB NOT NULL, + initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false +); +CREATE TABLE lpcc.payment_versions ( + node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, + PRIMARY KEY(node_id,generation) +); +CREATE TABLE lpcc.payment_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); +CREATE TABLE lpcc.payment_grants ( + grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, + payment_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, + pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, + observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, + UNIQUE(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) +); +CREATE INDEX payment_grants_machine ON lpcc.payment_grants(node_id,epoch); -- DOWN +DROP TABLE lpcc.payment_grants,lpcc.payment_secrets,lpcc.payment_versions,lpcc.payment_machines,lpcc.payment_revision; DROP TABLE lpcc.machine_configs; DROP TABLE lpcc.machines; diff --git a/api/internal/controlplane/migrations/007_runtime_retirement.sql b/api/internal/controlplane/migrations/007_runtime_retirement.sql index 1a0d28a..d2b2498 100644 --- a/api/internal/controlplane/migrations/007_runtime_retirement.sql +++ b/api/internal/controlplane/migrations/007_runtime_retirement.sql @@ -6,6 +6,8 @@ ALTER TABLE lpcc.enrollments ADD COLUMN retained_bundle BYTEA; CREATE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN + UPDATE lpcc.payment_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + UPDATE lpcc.payment_machines SET recovery_required=recovery_required OR (NOT drained AND (initialized OR config->>'mode'='paid') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'payment_settled'='true')) WHERE node_id=OLD.node_id; UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id diff --git a/api/internal/controlplane/observed_state.go b/api/internal/controlplane/observed_state.go index 25d4c74..72a140e 100644 --- a/api/internal/controlplane/observed_state.go +++ b/api/internal/controlplane/observed_state.go @@ -14,12 +14,16 @@ import ( fleet "github.com/livepeer/control-center/api/internal/controlplane/discovery" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" + "github.com/livepeer/control-center/api/internal/controlplane/payments" "github.com/livepeer/control-center/api/internal/controlplane/tunnel" + "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/schema" ) type componentObservation struct { + Payment *payment.Observation `json:"payment,omitempty"` ObserverID string `json:"observer_id,omitempty"` ObserverStartedAt *time.Time `json:"observer_started_at,omitempty"` Component string `json:"component"` @@ -79,6 +83,7 @@ type tunnelObservation struct { } type machineObservation struct { + Payment paymentView `json:"payment"` NodeID string `json:"node_id"` Epoch string `json:"epoch"` Hostname string `json:"hostname"` @@ -172,6 +177,10 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse } else if err != nil { return v, err } + v.Payment, err = s.paymentView(ctx, m) + if err != nil { + return v, err + } v.Lifecycle, v.RolloutGeneration = record.Lifecycle, record.Generation if m.Terminal { var ack *time.Time @@ -230,6 +239,18 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse expires = timePointer(effective.Add(ttl)) } c := componentObservation{Component: name, Generation: report.Generation, ObservedAt: report.ObservedAt, ReceivedAt: &received, ExpiresAt: expires, Fresh: expires != nil && now.Before(*expires), Current: report.Generation == record.Generation, Ready: report.Ready, Reason: safeObservationReason(report.Reason), ClockUncertain: report.ClockUncertain, BundleSHA256: report.BundleSHA256, ConfigDigest: report.ConfigDigest, DeliveryReason: safeObservationReason(report.DeliveryReason)} + c.Payment = report.Payment + if c.Payment != nil { + copy := *c.Payment + copy.GrantID = "" + if !c.Fresh || !c.Current || c.ClockUncertain { + copy.Ready = false + copy.Applied = false + copy.QueueKnown = false + copy.Handoff = "unverified" + } + c.Payment = © + } c.AppsError = safeObservationReason(report.AppsError) c.Apps, c.Downloaded, c.DownloadedAt = report.Apps, report.Downloaded, timePointer(report.DownloadedAt) c.ObserverID, c.ObserverStartedAt = report.ObserverID, timePointer(report.ObserverStartedAt) @@ -414,3 +435,41 @@ func (s *Server) observedMachineList(ctx context.Context, owner string, admin bo } return result, rows.Err() } + +type paymentView struct { + Desired payment.Config `json:"desired"` + DeliveredGeneration int64 `json:"delivered_generation"` + RecoveryRequired bool `json:"recovery_required"` +} + +func (s *Server) paymentView(ctx context.Context, m Machine) (paymentView, error) { + var v paymentView + var err error + v.Desired, err = payments.Load(ctx, s.db, m.NodeID) + if err != nil { + return v, err + } + v.Desired.RPCSecret = "" + v.Desired.RPCGrants = nil + v.Desired.RedeemerGrants = nil + _ = s.db.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, m.NodeID).Scan(&v.RecoveryRequired) + var b []byte + if m.Terminal { + err = s.db.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&b) + } else { + err = s.db.QueryRowContext(ctx, `SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, m.NodeID).Scan(&b) + } + if err == nil { + files, e := artifact.Read(b) + if e == nil { + var meta contract.Metadata + if json.Unmarshal(files["runtime.json"], &meta) == nil { + v.DeliveredGeneration = meta.Payment.Generation + } + } + } + if errors.Is(err, sql.ErrNoRows) { + err = nil + } + return v, err +} diff --git a/api/internal/controlplane/payment_credentials.go b/api/internal/controlplane/payment_credentials.go new file mode 100644 index 0000000..b2d0dc7 --- /dev/null +++ b/api/internal/controlplane/payment_credentials.go @@ -0,0 +1,207 @@ +package controlplane + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "strings" + "uuid" + + "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/orchestrator" + "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/transport" +) + +func (s *Server) submissionToken(id string) string { + h := hmac.New(sha256.New, []byte(s.params.MachineTokenSecret)) + h.Write([]byte("livepeer-redemption-submit-v1\x00" + id)) + return id + "." + hex.EncodeToString(h.Sum(nil)) +} +func (s *Server) paymentCredentials(w http.ResponseWriter, r *http.Request) { + m, e := s.authenticateMachine(r.Context(), r.PathValue("node_id"), bearer(r), false) + if e != nil { + s.respondError(w, e) + return + } + var in orchestrator.Request + if boundedMachineInput(r, &in, 4096) != nil || !orchestrator.ValidLaunch(in.Launch) || in.PaymentGeneration < 1 || !fingerprintPattern.MatchString(in.ConfigDigest) || !strings.HasPrefix(s.params.PublicAPIURL, "https://") { + fail(w, 403, "payment delivery refused") + return + } + tx, e := s.db.BeginTx(r.Context(), nil) + if e != nil { + s.databaseError(w, e) + return + } + defer tx.Rollback() + var current int64 + e = tx.QueryRowContext(r.Context(), `SELECT credential_version FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 FOR UPDATE`, m.NodeID, m.Epoch).Scan(¤t) + if e != nil || current != m.CredentialVersion { + fail(w, 409, "enrollment changed") + return + } + var bundle []byte + e = tx.QueryRowContext(r.Context(), `SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, m.NodeID).Scan(&bundle) + if e != nil { + fail(w, 409, "configuration unavailable") + return + } + files, e := artifact.Read(bundle) + var metadata contract.Metadata + if e == nil { + metadata, e = transport.ReadMetadata(files["runtime.json"]) + } + if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Payment.Paid() || metadata.Payment.Generation != in.PaymentGeneration || metadata.ConfigDigest != in.ConfigDigest { + fail(w, 409, "payment configuration changed") + return + } + rpc, e := s.readPaymentRPC(metadata.Payment.RPCSecret) + if e != nil { + fail(w, 503, "payment secret unavailable") + return + } + hash := sha256.Sum256(rpc) + var fingerprint string + e = tx.QueryRowContext(r.Context(), `SELECT fingerprint FROM lpcc.payment_secrets WHERE reference=$1`, metadata.Payment.RPCSecret).Scan(&fingerprint) + if e != nil || fingerprint != hex.EncodeToString(hash[:]) { + fail(w, 503, "payment secret version changed") + return + } + var initialized bool + if e = tx.QueryRowContext(r.Context(), `SELECT initialized FROM lpcc.payment_machines WHERE node_id=$1`, m.NodeID).Scan(&initialized); e != nil { + s.databaseError(w, e) + return + } + id := uuid.New().String() + var revoked sql.NullTime + e = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.payment_grants(grant_id,node_id,epoch,payment_generation,config_digest,pod_uid,launch_id,process_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) DO UPDATE SET grant_id=lpcc.payment_grants.grant_id RETURNING grant_id::text,revoked_at`, id, m.NodeID, m.Epoch, in.PaymentGeneration, in.ConfigDigest, in.PodUID, in.LaunchID, in.ProcessID).Scan(&id, &revoked) + if e != nil { + s.databaseError(w, e) + return + } + if revoked.Valid { + fail(w, 403, "submission grant revoked") + return + } + if e = tx.Commit(); e != nil { + s.databaseError(w, e) + return + } + respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, PaymentGeneration: in.PaymentGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) +} + +func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { + secret := s.params.PaymentWebhookSecret + if len(secret) < 32 || len(r.Header.Values("Authorization")) != 1 || subtle.ConstantTimeCompare([]byte(bearer(r)), []byte(secret)) != 1 { + fail(w, 401, "webhook authentication required") + return + } + var in struct { + Headers http.Header `json:"headers"` + Ticket json.RawMessage `json:"ticket"` + } + if appInput(r, &in) != nil { + respond(w, 200, map[string]int{"status": 403}) + return + } + token := "" + count := 0 + for k, v := range in.Headers { + if strings.EqualFold(k, "Authorization") { + count += len(v) + if len(v) == 1 { + kind, t, ok := strings.Cut(v[0], " ") + if ok && kind == "Bearer" { + token = t + } + } + } + } + id, _, ok := strings.Cut(token, ".") + var ticket struct { + Recipient string `json:"recipient"` + } + allowed := count == 1 && ok && appID(id) && len(s.params.MachineTokenSecret) >= 32 && hmac.Equal([]byte(token), []byte(s.submissionToken(id))) && json.Unmarshal(in.Ticket, &ticket) == nil && payment.Address.MatchString(ticket.Recipient) + if allowed { + var recipient string + e := s.db.QueryRowContext(r.Context(), `SELECT v.config->>'recipient' FROM lpcc.payment_grants g JOIN lpcc.payment_versions v ON v.node_id=g.node_id AND v.generation=g.payment_generation JOIN lpcc.machines m ON m.node_id=g.node_id AND m.enrollment_epoch=g.epoch WHERE g.grant_id=$1 AND g.revoked_at IS NULL`, id).Scan(&recipient) + allowed = e == nil && strings.EqualFold(recipient, ticket.Recipient) + } + status := 403 + if allowed { + status = 200 + } + respond(w, 200, map[string]int{"status": status}) +} + +// Accept only a fresh, matching observation of the issued grant. This permits a +// held Node's grant across ordinary management refresh, without allowing it to +// authenticate to any management endpoint. +func (s *Server) observePaymentGrant(ctx context.Context, m Machine, reportPayment *payment.Observation, digest string) error { + p := reportPayment + if p == nil || !p.Applied || p.PodUID == "" { + return nil + } + if p.Mode != "offchain" && (p.Mode != "paid" || !appID(p.GrantID)) { + return nil + } + tx, e := s.db.BeginTx(ctx, nil) + if e != nil { + return e + } + defer tx.Rollback() + var b []byte + e = tx.QueryRowContext(ctx, `SELECT c.bundle FROM lpcc.machines m JOIN lpcc.machine_configs c USING(node_id) WHERE m.node_id=$1 AND m.enrollment_epoch=$2 AND m.credential_version=$3 FOR UPDATE OF m`, m.NodeID, m.Epoch, m.CredentialVersion).Scan(&b) + if errors.Is(e, sql.ErrNoRows) { + return nil + } + if e != nil { + return e + } + files, e := artifact.Read(b) + if e != nil { + return e + } + meta, e := transport.ReadMetadata(files["runtime.json"]) + if e != nil { + return e + } + if meta.ConfigDigest != digest || meta.Payment.Generation != p.Generation || meta.Payment.Mode != p.Mode { + return nil + } + if p.Mode == "offchain" { + // The replacement has no submission bearer to observe. Retire the held + // paid workload's grants only after its offchain successor is applied. + _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, m.NodeID, m.Epoch) + if e != nil { + return e + } + return tx.Commit() + } + var id string + e = tx.QueryRowContext(ctx, `UPDATE lpcc.payment_grants SET observed_at=now() WHERE grant_id=$1 AND node_id=$2 AND epoch=$3 AND payment_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL RETURNING grant_id::text`, p.GrantID, m.NodeID, m.Epoch, p.Generation, digest, p.PodUID).Scan(&id) + if errors.Is(e, sql.ErrNoRows) { + return nil + } + if e != nil { + return e + } + _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND grant_id<>$3 AND revoked_at IS NULL AND issued_sequence<(SELECT issued_sequence FROM lpcc.payment_grants WHERE grant_id=$3)`, m.NodeID, m.Epoch, id) + if e != nil { + return e + } + if p.Ready { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET initialized=true WHERE node_id=$1`, m.NodeID); e != nil { + return e + } + } + return tx.Commit() +} diff --git a/api/internal/controlplane/payment_settings.go b/api/internal/controlplane/payment_settings.go new file mode 100644 index 0000000..807e2f7 --- /dev/null +++ b/api/internal/controlplane/payment_settings.go @@ -0,0 +1,303 @@ +package controlplane + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "encoding/json/jsontext" + jsonv2 "encoding/json/v2" + "errors" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + + "github.com/j0sh/boa/pkg/boa" + "github.com/livepeer/control-center/api/internal/controlplane/machineapps" + "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" + "github.com/livepeer/control-center/api/internal/controlplane/payments" + "github.com/livepeer/control-center/runtime/payment" + "github.com/spf13/cobra" +) + +type paymentInput struct { + Version int `json:"version"` + Machines map[string]payment.Config `json:"machines"` +} +type paymentApplyParams struct { + ConfigFile string `name:"config" env:"CONTROL_CENTER_CONFIG" configfile:"optional-default" basepath:"source" default:"config.toml" boa:"noconfig"` + DatabaseParams + PaymentSecretsDir string `optional:"true"` + PaymentWebhookSecret string `secret:"true" optional:"true"` + PaymentWebhookSecretFile string `secretfor:"PaymentWebhookSecret" basepath:"source"` + RuntimeNodeImage string `env:"RUNTIME_NODE_IMAGE" optional:"true"` + File string `name:"file" boa:"noconfig" descr:"Payment infrastructure JSON file"` + AcknowledgeRecovery string `name:"acknowledge-recovery" optional:"true" boa:"noconfig" descr:"Confirm restored retained state after a fresh empty-queue observation"` + ExpectedRevision int64 `name:"expected-revision" min:"0" boa:"noconfig"` +} + +func PaymentsCommand() *cobra.Command { + apply := boa.Cmd[paymentApplyParams]{Use: "apply", Short: "Apply deployment-owned payment infrastructure", Args: cobra.NoArgs, RunFuncE: func(p *paymentApplyParams, cmd *cobra.Command, _ []string) error { + b, e := os.ReadFile(p.File) + if e != nil { + return errors.New("payment input unavailable") + } + var input paymentInput + if len(b) > 128<<10 || jsonv2.Unmarshal(b, &input, jsonv2.RejectUnknownMembers(true), jsontext.AllowDuplicateNames(false)) != nil || input.Version != 1 || len(input.Machines) == 0 || len(input.Machines) > 1000 { + return errors.New("invalid payment infrastructure document") + } + db, e := OpenDB(cmd.Context(), p.PGConnstr, p.PGPassword) + if e != nil { + return e + } + defer db.Close() + s := New(db, Params{PaymentSecretsDir: p.PaymentSecretsDir, PaymentWebhookSecret: p.PaymentWebhookSecret, RuntimeNodeImage: p.RuntimeNodeImage}, slog.New(slog.NewTextHandler(io.Discard, nil))) + rev, e := s.applyPayments(cmd.Context(), input, p.ExpectedRevision, p.AcknowledgeRecovery) + if e == nil { + fmt.Fprintln(cmd.OutOrStdout(), rev) + } + return e + }}.ToCobra() + return boa.Cmd[boa.NoParams]{Use: "payments", Short: "Deployment payment configuration", SubCmds: []*cobra.Command{apply}}.ToCobra() +} + +// readPaymentRPC never exposes a path or a URL in its errors. +func (s *Server) readPaymentRPC(ref string) ([]byte, error) { + bad := errors.New("payment RPC secret unavailable") + if !payment.SecretRef.MatchString(ref) || !filepath.IsAbs(s.params.PaymentSecretsDir) { + return nil, bad + } + path := filepath.Join(s.params.PaymentSecretsDir, ref) + info, e := os.Lstat(path) + if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { + return nil, bad + } + f, e := os.Open(path) + if e != nil { + return nil, bad + } + defer f.Close() + info, e = f.Stat() + if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { + return nil, bad + } + b, e := io.ReadAll(io.LimitReader(f, 4097)) + if e != nil || len(b) > 4096 { + return nil, bad + } + b = []byte(strings.TrimSpace(string(b))) + u, e := url.Parse(string(b)) + if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.Fragment != "" { + return nil, bad + } + return b, nil +} + +func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected int64, acknowledge ...string) (int64, error) { + if input.Version != 1 || len(input.Machines) == 0 || len(input.Machines) > 1000 { + return 0, errors.New("invalid payment document") + } + nodes := make([]string, 0, len(input.Machines)) + fingerprints := map[string]string{} + for node, c := range input.Machines { + c.Recipient = strings.ToLower(c.Recipient) + c.Controller = strings.ToLower(c.Controller) + c.ETHUSDFeed = strings.ToLower(c.ETHUSDFeed) + input.Machines[node] = c + if !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(node) || c.Generation != 0 { + return 0, errors.New("invalid payment machine identity") + } + if e := c.Validate(); e != nil { + return 0, e + } + nodes = append(nodes, node) + if c.Paid() { + if len(s.params.PaymentWebhookSecret) < 32 { + return 0, errors.New("paid operation requires a webhook service credential") + } + if !machineconfigImage(s.params.RuntimeNodeImage) { + return 0, errors.New("paid operation requires a pinned wrapper/Node image") + } + b, e := s.readPaymentRPC(c.RPCSecret) + if e != nil { + return 0, e + } + if e := payment.ValidateEndpoint(string(b), c.RPCGrants); e != nil { + return 0, e + } + h := sha256.Sum256(b) + fingerprints[c.RPCSecret] = hex.EncodeToString(h[:]) + } + } + sort.Strings(nodes) + tx, e := s.policyTx(ctx) + if e != nil { + return 0, e + } + defer tx.Rollback() + var revision int64 + if e = tx.QueryRowContext(ctx, `SELECT revision FROM lpcc.payment_revision WHERE id=true FOR UPDATE`).Scan(&revision); e != nil { + return 0, e + } + + // Import is a complete desired snapshot: omission never silently disables paid service. + rows, e := tx.QueryContext(ctx, `SELECT node_id FROM lpcc.payment_machines WHERE config->>'mode'='paid'`) + if e != nil { + return 0, e + } + for rows.Next() { + var n string + if e = rows.Scan(&n); e != nil { + break + } + if _, ok := input.Machines[n]; !ok { + e = errors.New("explicit offchain intent is required") + break + } + } + if e == nil { + e = rows.Err() + } + rows.Close() + if e != nil { + return 0, e + } + for ref, digest := range fingerprints { + var old string + e = tx.QueryRowContext(ctx, `SELECT fingerprint FROM lpcc.payment_secrets WHERE reference=$1`, ref).Scan(&old) + if e == nil && old != digest { + return 0, errors.New("referenced payment secret versions are immutable") + } + if e != nil && !errors.Is(e, sql.ErrNoRows) { + return 0, e + } + if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_secrets(reference,fingerprint) VALUES($1,$2) ON CONFLICT DO NOTHING`, ref, digest); e != nil { + return 0, e + } + } + changed := false + for _, node := range nodes { + c := input.Machines[node] + old, e := payments.Load(ctx, tx, node) + if e != nil { + return 0, e + } + c.Generation = old.Generation + before, _ := json.Marshal(old) + after, _ := json.Marshal(c) + if string(before) == string(after) { + continue + } + // Same locking order as assignment mutation and configuration publication. + var epoch string + e = tx.QueryRowContext(ctx, `SELECT enrollment_epoch::text FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&epoch) + if e != nil && !errors.Is(e, sql.ErrNoRows) { + return 0, e + } + if epoch != "" { + a, e := machineapps.Snapshot(ctx, tx, node, epoch) + if e != nil { + return 0, e + } + if a != nil { + for _, a := range a.Entries { + if a.Revision != nil && a.Desired == "present" { + if e = c.Compatible(a.Revision.Definition); e != nil { + return 0, definitionProblem(e) + } + } + } + } + } + var recipient, controller string + var chain uint64 + e = tx.QueryRowContext(ctx, `SELECT recipient,chain_id,controller FROM lpcc.payment_machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&recipient, &chain, &controller) + if e != nil && !errors.Is(e, sql.ErrNoRows) { + return 0, e + } + if c.Paid() { + if recipient != "" && (!strings.EqualFold(recipient, c.Recipient) || chain != c.ChainID || !strings.EqualFold(controller, c.Controller)) { + return 0, errors.New("payment recipient and chain binding are immutable") + } + recipient = strings.ToLower(c.Recipient) + chain = c.ChainID + controller = strings.ToLower(c.Controller) + c.Recipient = recipient + c.Controller = controller + } + c.Generation = old.Generation + 1 + after, _ = json.Marshal(c) + _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_machines(node_id,recipient,chain_id,controller,generation,config) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation,config=EXCLUDED.config,drained=false`, node, recipient, chain, controller, c.Generation, string(after)) + if e != nil { + return 0, e + } + if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_versions VALUES($1,$2,$3)`, node, c.Generation, string(after)); e != nil { + return 0, e + } + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, node); e != nil { + return 0, e + } + if e = writeAudit(ctx, tx, "system", "deployment:payments", "payment.apply", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(c.Generation)}, "success", "changed"); e != nil { + return 0, e + } + changed = true + } + if len(acknowledge) > 0 && acknowledge[0] != "" { + node := acknowledge[0] + if _, ok := input.Machines[node]; !ok { + return 0, errors.New("recovery acknowledgement requires the machine in the desired snapshot") + } + // Freeze publication and enrollment while checking the evidence against + // the currently delivered workload, including configuration-only changes. + var bundle []byte + if e = tx.QueryRowContext(ctx, `SELECT c.bundle FROM lpcc.machines m JOIN lpcc.machine_configs c USING(node_id) WHERE m.node_id=$1 FOR UPDATE OF m`, node).Scan(&bundle); e != nil { + return 0, errors.New("recovery acknowledgement requires a delivered configuration") + } + metadata, _, e := machineconfig.ReadApplied(bundle) + if e != nil { + return 0, e + } + var required bool + if e = tx.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&required); e != nil { + return 0, e + } + if required { + var ready bool + e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machines m JOIN lpcc.machine_reports r ON r.node_id=m.node_id AND r.epoch=m.enrollment_epoch AND r.credential_version=m.credential_version JOIN lpcc.payment_machines p ON p.node_id=m.node_id JOIN lpcc.payment_grants g ON g.grant_id::text=r.report#>>'{payment,grant_id}' AND g.node_id=m.node_id AND g.epoch=m.enrollment_epoch WHERE m.node_id=$1 AND r.component='runtime' AND r.generation=$2 AND r.report->>'config_digest'=$3 AND g.config_digest=$3 AND g.pod_uid=r.report#>>'{payment,pod_uid}' AND g.payment_generation=p.generation AND r.received_at>now()-interval '2 minutes' AND (r.report->>'observed_at')::timestamptz>now()-interval '2 minutes' AND NOT COALESCE((r.report->>'clock_uncertain')::boolean,false) AND r.report#>>'{payment,applied}'='true' AND r.report#>>'{payment,queue_known}'='true' AND r.report#>>'{payment,unsettled}'='0' AND (r.report#>>'{payment,generation}')::bigint=p.generation AND g.observed_at IS NOT NULL AND g.revoked_at IS NULL)`, node, metadata.Generation, metadata.ConfigDigest).Scan(&ready) + if e != nil { + return 0, e + } + if !ready { + return 0, errors.New("restore payment state and obtain fresh zero-unsettled evidence before acknowledging recovery") + } + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET recovery_required=false WHERE node_id=$1`, node); e != nil { + return 0, e + } + if e = writeAudit(ctx, tx, "system", "deployment:payments", "payment.recover", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(revision + 1)}, "success", "recovery_acknowledged"); e != nil { + return 0, e + } + changed = true + } + } + if expected > revision || (changed && expected != revision) { + return 0, problem(409, "payment_revision_changed", "Payment infrastructure changed.") + } + if changed { + revision++ + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_revision SET revision=$1 WHERE id=true`, revision); e != nil { + return 0, e + } + } + return revision, tx.Commit() +} + +func machineconfigImage(s string) bool { + return regexp.MustCompile(`^[a-zA-Z0-9./:_-]+@sha256:[0-9a-f]{64}$`).MatchString(s) +} diff --git a/api/internal/controlplane/payment_test.go b/api/internal/controlplane/payment_test.go new file mode 100644 index 0000000..43f54a1 --- /dev/null +++ b/api/internal/controlplane/payment_test.go @@ -0,0 +1,479 @@ +package controlplane + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" + "github.com/livepeer/control-center/api/internal/controlplane/payments" + "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/connector" + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/orchestrator" + "github.com/livepeer/control-center/runtime/payment" +) + +func paidSettings(t *testing.T, s *Server) payment.Config { + t.Helper() + dir := t.TempDir() + s.params.PaymentSecretsDir = dir + s.params.PaymentWebhookSecret = strings.Repeat("w", 32) + if e := os.WriteFile(filepath.Join(dir, "rpc-v1"), []byte("https://rpc.example/private-token"), 0600); e != nil { + t.Fatal(e) + } + return payment.Config{Version: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://api.example/redemption", WeiPerUSD: "1000000000000000", TicketFaceValue: "1000", TicketWinProb: "100", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} +} +func TestPaymentApplyAtomicBindingAndSecretVersions(t *testing.T) { + s := newTestServer(t) + c := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + in := paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}} + if rev, e := s.applyPayments(t.Context(), in, 0); e != nil || rev != 1 { + t.Fatal(rev, e) + } + if rev, e := s.applyPayments(t.Context(), in, 1); e != nil || rev != 1 { + t.Fatal("retry", rev, e) + } + if rev, e := s.applyPayments(t.Context(), in, 0); e != nil || rev != 1 { + t.Fatal("lost response retry", rev, e) + } + stale := c + stale.CredentialRevision++ + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: stale}}, 0); e == nil { + t.Fatal("stale edit accepted") + } + var n int + if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`).Scan(&n); e != nil || n != 1 { + t.Fatal(n, e) + } + // Omission and immutable bindings fail without committing another audit event. + other := payment.Offchain() + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{"lp-bbbbbbbbbbbbbbbb": other}}, 1); e == nil { + t.Fatal("omission disabled paid machine") + } + for _, mutate := range []func(*payment.Config){func(c *payment.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *payment.Config) { c.ChainID++ }, func(c *payment.Config) { c.TicketWinProb = "0" }} { + next := c + mutate(&next) + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: next}}, 1); e == nil { + t.Fatal("invalid change accepted") + } + } + if e := os.WriteFile(filepath.Join(s.params.PaymentSecretsDir, "rpc-v1"), []byte("https://rpc.example/changed-secret"), 0600); e != nil { + t.Fatal(e) + } + if _, e := s.applyPayments(t.Context(), in, 1); e == nil { + t.Fatal("overwritten secret version accepted") + } + if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`).Scan(&n); e != nil || n != 1 { + t.Fatal("partial commit", n, e) + } +} +func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { + s := newTestServer(t) + c := paidSettings(t, s) + machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) + node := machine["node_id"] + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}}, 0); e != nil { + t.Fatal(e) + } + cfg, e := payments.Load(t.Context(), s.db, node) + if e != nil { + t.Fatal(e) + } + // Install an applying bundle; this test exercises the real API boundary, not + // Kubernetes attestation (covered by the Runtime consumer tests). + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: machine["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: cfg, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + b, digest, e := machineconfig.Build(desired) + if e != nil { + t.Fatal(e) + } + if _, e = s.db.Exec(`UPDATE lpcc.machine_configs SET bundle=$2,sha256=$3 WHERE node_id=$1`, node, b, digest); e != nil { + t.Fatal(e) + } + files, _ := artifact.Read(b) + var meta contract.Metadata + json.Unmarshal(files["runtime.json"], &meta) + launch := connector.Launch{PodName: "orchestrator-test", PodUID: "uid-test", LaunchID: strings.Repeat("a", 32), ProcessID: strings.Repeat("b", 64)} + in := orchestrator.Request{Launch: launch, PaymentGeneration: cfg.Generation, ConfigDigest: meta.ConfigDigest} + path := "/v1/nodes/" + node + "/payment/credentials" + requireStatus(t, request(t, s, "POST", path, "session-a", in), 401) + w := request(t, s, "POST", path, machine["token"], in) + requireStatus(t, w, 200) + var g orchestrator.Grant + if json.Unmarshal(w.Body.Bytes(), &g) != nil || g.RPCURL == "" || g.Headers == "" { + t.Fatal(w.Body.String()) + } + retry := request(t, s, "POST", path, machine["token"], in) + requireStatus(t, retry, 200) + if retry.Body.String() != w.Body.String() { + t.Fatal("credential retry changed") + } + webhook := func(recipient string, headers map[string][]string, secret string) int { + w := request(t, s, "POST", "/internal/redemption/authorize", secret, map[string]any{"headers": headers, "ticket": map[string]string{"recipient": recipient}}) + if w.Code != 200 { + return w.Code + } + var d struct { + Status int `json:"status"` + } + json.Unmarshal(w.Body.Bytes(), &d) + return d.Status + } + h := map[string][]string{"Authorization": {strings.TrimPrefix(g.Headers, "Authorization: ")}} + if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 200 { + t.Fatal("valid submission denied") + } + if webhook("0x"+strings.Repeat("3", 40), h, s.params.PaymentWebhookSecret) != 403 { + t.Fatal("cross recipient allowed") + } + if webhook(c.Recipient, h, "wrong-service-secret") != 401 { + t.Fatal("service authentication bypass") + } + h["authorization"] = h["Authorization"] + if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 403 { + t.Fatal("duplicate authorization allowed") + } + delete(h, "authorization") + // Management refresh does not silently revoke the loaded submission bearer. + if _, e = s.db.Exec(`UPDATE lpcc.machines SET credential_version=credential_version+1 WHERE node_id=$1`, node); e != nil { + t.Fatal(e) + } + if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 200 { + t.Fatal("refresh revoked retained grant") + } + if e = s.RetireMachine(t.Context(), node); e != nil { + t.Fatal(e) + } + if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 403 { + t.Fatal("forced retirement did not revoke") + } + var recovery bool + if e = s.db.QueryRow(`SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&recovery); e != nil || !recovery { + t.Fatal(recovery, e) + } + fresh := enroll(t, s, ownerA, strings.Repeat("a", 64)) + if fresh["epoch"] == machine["epoch"] { + t.Fatal("enrollment not replaced") + } + c.Recipient = "0x" + strings.Repeat("3", 40) + if _, e = s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}}, 1); e == nil { + t.Fatal("re-enrollment reset pinned recipient") + } +} + +func TestPaidActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing.T) { + s := newTestServer(t) + cfg := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + t.Fatal(e) + } + c := enroll(t, s, ownerA, strings.Repeat("a", 64)) + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + metadata := func() contract.Metadata { + t.Helper() + var b []byte + if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { + t.Fatal(e) + } + f, e := artifact.Read(b) + if e != nil { + t.Fatal(e) + } + var m contract.Metadata + if json.Unmarshal(f["runtime.json"], &m) != nil { + t.Fatal("metadata") + } + return m + } + if metadata().PaymentActive { + t.Fatal("saved setting treated as active paid operation") + } + m0 := metadata() + launch := orchestrator.Launch{PodName: "orchestrator-test", PodUID: "node-pod", LaunchID: strings.Repeat("a", 32), ProcessID: strings.Repeat("b", 64)} + w := request(t, s, "POST", "/v1/nodes/"+node+"/payment/credentials", c["token"], orchestrator.Request{Launch: launch, PaymentGeneration: m0.Payment.Generation, ConfigDigest: m0.ConfigDigest}) + requireStatus(t, w, 200) + var grant orchestrator.Grant + json.Unmarshal(w.Body.Bytes(), &grant) + report := func(known bool, n int64) { + t.Helper() + m := metadata() + r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Payment: &payment.Observation{Generation: m.Payment.Generation, Mode: "paid", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+node+"/status", c["token"], r), 200) + } + if _, e := s.db.Exec(`UPDATE lpcc.payment_machines SET recovery_required=true WHERE node_id=$1`, node); e != nil { + t.Fatal(e) + } + in := paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}} + if _, e := s.applyPayments(t.Context(), in, 1, node); e == nil { + t.Fatal("recovery acknowledged without fresh payment evidence") + } + report(true, 0) + // A fresh report from a previously delivered configuration cannot clear + // recovery after publication changes, even within the same payment generation. + if _, e := s.db.Exec(`UPDATE lpcc.machine_reports SET report=jsonb_set(report,'{config_digest}',to_jsonb(repeat('f',64))) WHERE node_id=$1 AND component='runtime'`, node); e != nil { + t.Fatal(e) + } + if _, e := s.applyPayments(t.Context(), in, 1, node); e == nil { + t.Fatal("recovery acknowledged evidence for a different delivered configuration") + } + report(true, 0) + if rev, e := s.applyPayments(t.Context(), in, 1, node); e != nil || rev != 2 { + t.Fatal("explicit restored-state acknowledgement", rev, e) + } + if rev, e := s.applyPayments(t.Context(), in, 1, node); e != nil || rev != 2 { + t.Fatal("recovery acknowledgement retry", rev, e) + } + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + if !metadata().PaymentActive { + t.Fatal("fresh applied Node did not activate") + } + adminA(t, s) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+node, "session-a", map[string]any{"epoch": c["epoch"]}), 202) + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + report(true, 0) // This zero predates authoritative completion of active work. + reportRuntime(t, s, c, "runner", true) + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { + t.Fatal("pre-drain empty queue authorized retirement") + } + for _, sample := range []struct { + known bool + n int64 + }{{false, 0}, {true, 1}} { + report(sample.known, sample.n) + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { + t.Fatal("unknown/nonempty queue authorized retirement") + } + } + report(true, 0) + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 0 { + t.Fatal("settled ordinary removal did not complete") + } + var drained, recovery bool + if e := s.db.QueryRow(`SELECT drained,recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&drained, &recovery); e != nil || !drained || recovery { + t.Fatal("ordinary retirement misclassified", drained, recovery, e) + } +} + +func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { + s := newTestServer(t) + cfg := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + t.Fatal(e) + } + c := enroll(t, s, ownerA, strings.Repeat("a", 64)) + var b []byte + if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { + t.Fatal(e) + } + files, _ := artifact.Read(b) + var m contract.Metadata + json.Unmarshal(files["runtime.json"], &m) + issue := func(nonce string) orchestrator.Grant { + t.Helper() + l := orchestrator.Launch{PodName: "orchestrator-test", PodUID: "same-pod", LaunchID: strings.Repeat(nonce, 32), ProcessID: strings.Repeat(nonce, 64)} + w := request(t, s, "POST", "/v1/nodes/"+node+"/payment/credentials", c["token"], orchestrator.Request{Launch: l, PaymentGeneration: m.Payment.Generation, ConfigDigest: m.ConfigDigest}) + requireStatus(t, w, 200) + var g orchestrator.Grant + if e := json.Unmarshal(w.Body.Bytes(), &g); e != nil { + t.Fatal(e) + } + return g + } + old := issue("a") + newer := issue("b") + machine, e := s.authenticateMachine(t.Context(), node, c["token"], false) + if e != nil { + t.Fatal(e) + } + observe := func(g orchestrator.Grant) { + t.Helper() + if e := s.observePaymentGrant(t.Context(), machine, &payment.Observation{Generation: m.Payment.Generation, Mode: "paid", PodUID: "same-pod", GrantID: g.GrantID, Applied: true, Ready: true}, m.ConfigDigest); e != nil { + t.Fatal(e) + } + } + observe(old) + var revoked bool + if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, newer.GrantID).Scan(&revoked); e != nil || revoked { + t.Fatal("old observation revoked an applying grant", e) + } + observe(newer) + observe(old) + if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, old.GrantID).Scan(&revoked); e != nil || !revoked { + t.Fatal("replacement did not retire predecessor", e) + } + third := issue("c") + if !third.RequireState { + t.Fatal("initialized paid database can be silently recreated") + } + off := payment.Offchain() + off.Generation = m.Payment.Generation + 1 + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: c["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: off, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + b, digest, e := machineconfig.Build(desired) + if e != nil { + t.Fatal(e) + } + files, _ = artifact.Read(b) + var replacement contract.Metadata + json.Unmarshal(files["runtime.json"], &replacement) + o := &payment.Observation{Generation: off.Generation, Mode: "offchain", PodUID: "offchain-pod", Applied: true} + if e = s.observePaymentGrant(t.Context(), machine, o, m.ConfigDigest); e != nil { + t.Fatal(e) + } + if e = s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, third.GrantID).Scan(&revoked); e != nil || revoked { + t.Fatal("offchain observation revoked a still-held paid grant", e) + } + if _, e = s.db.Exec(`UPDATE lpcc.machine_configs SET bundle=$2,sha256=$3 WHERE node_id=$1`, node, b, digest); e != nil { + t.Fatal(e) + } + if e = s.observePaymentGrant(t.Context(), machine, o, replacement.ConfigDigest); e != nil { + t.Fatal(e) + } + if count(t, s, `SELECT count(*) FROM lpcc.payment_grants WHERE revoked_at IS NULL`) != 0 { + t.Fatal("applied offchain replacement retained submission grants") + } +} + +func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { + s := newTestServer(t) + cfg := paidSettings(t, s) + paidNode := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{paidNode: cfg}}, 0); e != nil { + t.Fatal(e) + } + a := enroll(t, s, ownerA, strings.Repeat("a", 64)) + b := enroll(t, s, ownerB, strings.Repeat("b", 64)) + adminA(t, s) + freeSource := strings.Replace(registryFixture(t), `amount = "0.001"`, `amount = "0"`, 1) + free, status := revisionResponse(t, s, freeSource, "", true) + if status != 201 { + t.Fatal("catalog applied machine policy", status) + } + requireStatus(t, putApp(t, s, a, free, 0, 1), 400) + requireStatus(t, putApp(t, s, b, free, 0, 1), 202) + w := request(t, s, "GET", "/v1/nodes/"+b["node_id"]+"/config", b["token"], nil) + requireStatus(t, w, 200) + files, e := artifact.Read(w.Body.Bytes()) + if e != nil { + t.Fatal(e) + } + var meta contract.Metadata + json.Unmarshal(files["runtime.json"], &meta) + if meta.Payment.Paid() || strings.Contains(string(files["runtime.json"]), cfg.Recipient) { + t.Fatal("cross-machine payment delivery") + } + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+a["node_id"]+"/payment/credentials", b["token"], map[string]any{}), 401) + // Browser administration has no payment-settings mutation interface. + requireStatus(t, request(t, s, "PUT", "/api/admin/machines/"+a["node_id"]+"/payment", "session-a", cfg), 404) +} + +func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { + s := newTestServer(t) + c := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + errors := make(chan error, 2) + for n := range 2 { + copy := c + copy.CredentialRevision = uint64(n + 1) + go func() { + _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: copy}}, 0) + errors <- e + }() + } + successes := 0 + for range 2 { + if <-errors == nil { + successes++ + } + } + if successes != 1 { + t.Fatal("concurrent edits both committed", successes) + } + if count(t, s, `SELECT count(*) FROM lpcc.payment_versions`) != 1 || count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`) != 1 { + t.Fatal("configuration and audit diverged") + } +} + +func TestUnapprovedPaidStartupCanRepairItsImageButCannotDisable(t *testing.T) { + s := newTestServer(t) + cfg := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + t.Fatal(e) + } + enroll(t, s, ownerA, strings.Repeat("a", 64)) + read := func() contract.Metadata { + t.Helper() + var b []byte + if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { + t.Fatal(e) + } + files, _ := artifact.Read(b) + var m contract.Metadata + if e := json.Unmarshal(files["runtime.json"], &m); e != nil { + t.Fatal(e) + } + return m + } + before := read() + s.params.RuntimeNodeImage = "registry.invalid/node@sha256:" + strings.Repeat("f", 64) + s.configs = s.newConfigurationManager() + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + after := read() + if after.ConfigDigest == before.ConfigDigest || !after.Payment.Paid() || after.PaymentActive || after.Payment.Generation != before.Payment.Generation { + t.Fatal("unapproved paid target could not repair its image under the same payment binding", after) + } + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: payment.Offchain()}}, 1); e != nil { + t.Fatal(e) + } + if e := s.reconcile(t.Context()); e != nil { + t.Fatal(e) + } + if !read().Payment.Paid() { + t.Fatal("failed paid startup bypassed the settlement gate to offchain") + } +} + +func TestForcedRetirementCannotUseDesiredOffchainAsSettlementProof(t *testing.T) { + s := newTestServer(t) + cfg := paidSettings(t, s) + node := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + t.Fatal(e) + } + _ = enroll(t, s, ownerA, strings.Repeat("a", 64)) + if _, e := s.db.Exec(`UPDATE lpcc.payment_machines SET initialized=true WHERE node_id=$1`, node); e != nil { + t.Fatal(e) + } + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: payment.Offchain()}}, 1); e != nil { + t.Fatal(e) + } + if e := s.RetireMachine(t.Context(), node); e != nil { + t.Fatal(e) + } + var required bool + if e := s.db.QueryRow(`SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&required); e != nil || !required { + t.Fatal("pending disable hid retained paid state", required, e) + } +} diff --git a/api/internal/controlplane/payments/store.go b/api/internal/controlplane/payments/store.go new file mode 100644 index 0000000..8f8ac0e --- /dev/null +++ b/api/internal/controlplane/payments/store.go @@ -0,0 +1,31 @@ +package payments + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + + "github.com/livepeer/control-center/runtime/payment" +) + +type Querier interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func Load(ctx context.Context, q Querier, node string) (payment.Config, error) { + c := payment.Offchain() + var b []byte + err := q.QueryRowContext(ctx, `SELECT config FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&b) + if errors.Is(err, sql.ErrNoRows) { + return c, nil + } + if err != nil { + return c, err + } + err = json.Unmarshal(b, &c) + if err == nil { + err = c.Validate() + } + return c, err +} diff --git a/api/internal/controlplane/registry.go b/api/internal/controlplane/registry.go index 7b0447e..a59a523 100644 --- a/api/internal/controlplane/registry.go +++ b/api/internal/controlplane/registry.go @@ -41,9 +41,7 @@ func (s *Server) validateApp(w http.ResponseWriter, r *http.Request, _ UserIdent d, err = schema.ParseTOML([]byte(input.Source)) err = definitionProblem(err) } - if err == nil { - err = definitionProblem(schema.ValidatePolicy(d, s.registryMode())) - } + if err != nil { s.respondError(w, err) return @@ -53,7 +51,7 @@ func (s *Server) validateApp(w http.ResponseWriter, r *http.Request, _ UserIdent s.respondError(w, err) return } - respond(w, 200, map[string]any{"payment_mode": s.registryMode(), "definition": d, "canonical_format": schema.CanonicalFormat, "digest": schema.Digest(b)}) + respond(w, 200, map[string]any{"definition": d, "canonical_format": schema.CanonicalFormat, "digest": schema.Digest(b)}) } func (s *Server) prepareCreateApp(r *http.Request, u UserIdentity) (AdminApply, error) { return s.preparePublication(r, true) @@ -199,7 +197,7 @@ func (s *Server) listApps(w http.ResponseWriter, r *http.Request, _ UserIdentity apps = apps[:limit] next = &apps[len(apps)-1].Name } - respond(w, 200, map[string]any{"payment_mode": s.registryMode(), "apps": apps, "next_after_name": next}) + respond(w, 200, map[string]any{"apps": apps, "next_after_name": next}) } func (s *Server) inspectApp(w http.ResponseWriter, r *http.Request, _ UserIdentity) { limit, err := pageLimit(r) @@ -247,7 +245,7 @@ func (s *Server) inspectApp(w http.ResponseWriter, r *http.Request, _ UserIdenti revisions = revisions[:limit] next = &revisions[len(revisions)-1].Revision } - respond(w, 200, map[string]any{"payment_mode": s.registryMode(), "app": a, "revisions": revisions, "next_before_revision": next}) + respond(w, 200, map[string]any{"app": a, "revisions": revisions, "next_before_revision": next}) } func (s *Server) inspectAppRevision(w http.ResponseWriter, r *http.Request, _ UserIdentity) { id, err := uuid.Parse(r.PathValue("revision_id")) diff --git a/api/internal/controlplane/registry_store.go b/api/internal/controlplane/registry_store.go index a8bd446..9c81fd8 100644 --- a/api/internal/controlplane/registry_store.go +++ b/api/internal/controlplane/registry_store.go @@ -9,6 +9,7 @@ import ( "time" "uuid" + "github.com/livepeer/control-center/api/internal/controlplane/payments" "github.com/livepeer/control-center/schema" ) @@ -89,26 +90,26 @@ func loadPinnedRevision(ctx context.Context, q rowQuerier, ref schema.RevisionRe // already holds policyTx's lock, and current must come from the persisted // assignment read using tx, never from a request. // Unchanged references may scale/recover after retirement or a policy change. -func revisionForBinding(ctx context.Context, tx *sql.Tx, current *schema.RevisionRef, desired schema.RevisionRef, mode schema.PaymentMode) (CatalogRevision, error) { +func revisionForBinding(ctx context.Context, tx *sql.Tx, current *schema.RevisionRef, desired schema.RevisionRef, node string) (CatalogRevision, error) { r, err := loadPinnedRevision(ctx, tx, desired) if err != nil { return r, err } + config, err := payments.Load(ctx, tx, node) + if err != nil { + return r, err + } + if err := config.Compatible(r.Definition); err != nil { + return r, definitionProblem(err) + } if current != nil && *current == desired { return r, nil } if r.Lifecycle.RetiredAt != nil { return r, problem(409, "revision_retired", "Retired revisions cannot receive new bindings.") } - return r, definitionProblem(schema.ValidatePolicy(r.Definition, mode)) -} -func (s *Server) registryMode() schema.PaymentMode { - if s.params.RegistryPaymentMode == "" { - return schema.Offchain - } - return schema.PaymentMode(s.params.RegistryPaymentMode) + return r, nil } - func (s *Server) publishRevision(ctx context.Context, tx *sql.Tx, user UserIdentity, d schema.DefinitionV1, source, expected string, create bool, b []byte) (AdminChange, error) { digest := schema.Digest(b) old, err := readRevision(tx.QueryRowContext(ctx, `SELECT `+revisionColumns+revisionFrom+`WHERE r.app_name=$1 AND r.digest=$2`, d.Name, digest)) @@ -136,9 +137,7 @@ func (s *Server) publishRevision(ctx context.Context, tx *sql.Tx, user UserIdent } else if head == nil || *head != expected { return AdminChange{}, problem(409, "stale_head", "Another revision has been published. Refresh before publishing.") } - if err := schema.ValidatePolicy(d, s.registryMode()); err != nil { - return AdminChange{}, definitionProblem(err) - } + id := uuid.New().String() _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.app_revisions(revision_id,app_name,revision,app_version,schema_version,canonical_format,canonical,digest,source_toml,published_by) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, id, d.Name, next, d.AppVersion, d.SchemaVersion, schema.CanonicalFormat, b, digest, source, user.ID) if err == nil { diff --git a/api/internal/controlplane/registry_test.go b/api/internal/controlplane/registry_test.go index fd4b0ea..f2ea775 100644 --- a/api/internal/controlplane/registry_test.go +++ b/api/internal/controlplane/registry_test.go @@ -152,15 +152,14 @@ func TestRegistryPolicyAndBindingSeam(t *testing.T) { t.Fatal(status) } requireStatus(t, request(t, s, "POST", "/api/admin/apps/whoami/revisions/"+first.RevisionID+"/retire", "session-a", map[string]int{"expected_state_version": 1}), 200) - s.params.RegistryPaymentMode = "onchain" - requireStatus(t, request(t, s, "POST", "/api/admin/apps/validate", "session-a", map[string]string{"source_toml": source}), 400) + requireStatus(t, request(t, s, "POST", "/api/admin/apps/validate", "session-a", map[string]string{"source_toml": source}), 200) same, status := revisionResponse(t, s, source, uuid.New().String(), false) if status != 200 || same.RevisionID != first.RevisionID || same.Lifecycle.RetiredAt == nil { t.Fatal("retired retry lost to policy/precondition") } _, status = revisionResponse(t, s, strings.Replace(source, "replicas = 2", "replicas = 3", 1), first.RevisionID, false) - if status != 400 { - t.Fatal("new free onchain revision accepted") + if status != 201 { + t.Fatal("generic catalog rejected free price", status) } testBinding := func(current *schema.RevisionRef, ref schema.RevisionRef, want int) { t.Helper() @@ -169,7 +168,7 @@ func TestRegistryPolicyAndBindingSeam(t *testing.T) { t.Fatal(err) } defer tx.Rollback() - _, err = revisionForBinding(t.Context(), tx, current, ref, s.registryMode()) + _, err = revisionForBinding(t.Context(), tx, current, ref, "lp-0000000000000001") if want == 200 && err != nil { t.Fatal(err) } @@ -179,13 +178,11 @@ func TestRegistryPolicyAndBindingSeam(t *testing.T) { } testBinding(&first.RevisionRef, first.RevisionRef, 200) testBinding(nil, first.RevisionRef, 409) - s.params.RegistryPaymentMode = "offchain" active, status := revisionResponse(t, s, strings.Replace(source, "replicas = 2", "replicas = 3", 1), first.RevisionID, false) - if status != 201 { + if status != 200 { t.Fatal(status) } - s.params.RegistryPaymentMode = "onchain" - testBinding(nil, active.RevisionRef, 400) + testBinding(nil, active.RevisionRef, 200) testBinding(&active.RevisionRef, active.RevisionRef, 200) testBinding(&active.RevisionRef, first.RevisionRef, 409) testBinding(nil, schema.RevisionRef{RevisionID: uuid.New().String(), Digest: active.Digest}, 404) diff --git a/api/internal/controlplane/server.go b/api/internal/controlplane/server.go index 5169b09..d25e8f2 100644 --- a/api/internal/controlplane/server.go +++ b/api/internal/controlplane/server.go @@ -118,6 +118,8 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /v1/nodes/{node_id}/apps/{revision_id}/status", s.assignmentStatus) mux.HandleFunc("POST /v1/nodes/register", s.register) mux.HandleFunc("GET /v1/nodes/{node_id}/config", s.configuration) + mux.HandleFunc("POST /v1/nodes/{node_id}/payment/credentials", s.paymentCredentials) + mux.HandleFunc("POST /internal/redemption/authorize", s.redemptionAuthorize) mux.HandleFunc("POST /v1/nodes/{node_id}/credentials/refresh", s.refreshCredentials) mux.HandleFunc("POST /v1/nodes/{node_id}/tunnel/connector-token", s.connectorToken) mux.HandleFunc("POST /v1/nodes/{node_id}/status", s.machineStatus) diff --git a/api/internal/controlplane/tunnel/endpoints_test.go b/api/internal/controlplane/tunnel/endpoints_test.go index f4d3dd3..749e8db 100644 --- a/api/internal/controlplane/tunnel/endpoints_test.go +++ b/api/internal/controlplane/tunnel/endpoints_test.go @@ -183,7 +183,7 @@ func TestNodeSharedAccessIntegration(t *testing.T) { if err := os.WriteFile(runners, []byte(fmt.Sprintf("[[Runners]]\nID = \"app-fixture\"\nApp = \"fixture\"\nRunnerURL = %q\nMode = \"persistent\"\nProxy = true\nCapacity = 2\n\n[[Runners]]\nID = \"app-echo\"\nApp = \"echo\"\nRunnerURL = %q\nMode = \"single-shot\"\nProxy = true\nCapacity = 2\n", app.URL, app.URL)), 0600); err != nil { t.Fatal(err) } - config := fmt.Sprintf("Listen = %q\nMetricsListen = %q\nServiceURL = %q\nAPIOriginURL = %q\nRunnerServiceURL = %q\nProxyURLTemplate = %q\nRunnerConfig = %q\nRunnerGrants = [%q]\n", address, metrics, state.ServiceURL, PrivateOrchestrator, "http://"+address, state.ProxyURLTemplate, runners, strings.TrimPrefix(app.URL, "http://")) + config := fmt.Sprintf("Listen = %q\nMetricsListen = %q\nServiceURL = %q\nRunnerServiceURL = %q\nProxyURLTemplate = %q\nRunnerConfig = %q\nRunnerGrants = [%q]\n", address, metrics, state.ServiceURL, "http://"+address, state.ProxyURLTemplate, runners, strings.TrimPrefix(app.URL, "http://")) configPath := filepath.Join(directory, "config.toml") if err := os.WriteFile(configPath, []byte(config), 0600); err != nil { t.Fatal(err) diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 806e02c..7eb6ee6 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -20,8 +20,26 @@ } :8081 { + @private path /internal /internal/* + handle @private { + respond "Not found" 404 + } + @tickets { + path /redemption/tickets + method POST + } + handle @tickets { + uri strip_prefix /redemption + reverse_proxy redeemer:8941 + } + handle /redemption/* { + respond "Not found" 404 + } + header X-Content-Type-Options nosniff - reverse_proxy api:43812 + handle { + reverse_proxy api:43812 + } } :8082 { diff --git a/deploy/README.md b/deploy/README.md index 6ac34a2..241d77b 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -49,7 +49,8 @@ docker build -f ../runtime/services/Dockerfile.tunnel \ --build-arg RUNTIME_IMAGE=127.0.0.1:63812/controlcenter/runtime@sha256: \ -t 127.0.0.1:63812/controlcenter/connector:staging ../runtime/services docker push 127.0.0.1:63812/controlcenter/connector:staging -# Publish a compatible Node image as controlcenter/node as well. +# For paid operation, build a compatible Node binary and package its image with +# the Runtime startup wrapper (see docs/paid-operation.md). # Set RuntimeImage, RuntimeConnectorImage, and RuntimeNodeImage in config.toml # using the public registry hostname and the digests returned by the pushes. docker compose config --quiet @@ -62,12 +63,14 @@ and node address exclusions. Update `TunnelNodeAddresses` with the public and management addresses of every machine before enrollment; the bootstrap installer's origin firewall remains required. +For fresh managed paid installations, follow [the payment runbook](../docs/paid-operation.md) +for the redeemer Compose profile, credential mounts and deployment settings. + The deployed image digests and source provenance are recorded in [`staging-images.json`](staging-images.json). The initial staging build includes the existing working tree changes. Its matching Node source snapshot is retained -on the server at `/opt/controlcenter/node-source`; it supports the -`--api-origin-url` setting used by the current orchestrator template. Publish a -compatible Node image before changing `RuntimeNodeImage`. +on the server at `/opt/controlcenter/node-source`. Publish a compatible Node image +before changing `RuntimeNodeImage`. ## Operate diff --git a/deploy/compose.paid.yaml b/deploy/compose.paid.yaml new file mode 100644 index 0000000..2489538 --- /dev/null +++ b/deploy/compose.paid.yaml @@ -0,0 +1,28 @@ +# Fresh paid deployment: combine with compose.yaml and --profile paid. +services: + redeemer: + restart: unless-stopped + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + profiles: [paid] + image: ${LIVEPEER_REDEEMER_IMAGE:?Set a digest-pinned compatible Node image} + user: "65532:65532" + command: [redeemer, --config, /etc/livepeer/redeemer.toml] + volumes: + - ./redeemer.toml:/etc/livepeer/redeemer.toml:ro + - redeemer-data:/home/livepeer/.lpData + - ./secrets/redeemer:/run/redeemer:ro + stop_grace_period: 30s + + api: + volumes: + - ./secrets/payment-rpc:/run/payment-rpc:ro + secrets: + - payment-webhook-auth +secrets: + payment-webhook-auth: + file: ./secrets/payment-webhook-auth + +volumes: + redeemer-data: diff --git a/deploy/config.example.toml b/deploy/config.example.toml index 4f276cc..ac2a9fc 100644 --- a/deploy/config.example.toml +++ b/deploy/config.example.toml @@ -10,7 +10,6 @@ DefaultAdminEmail = "admin@example.com" Listen = "0.0.0.0:43812" PublicAPIURL = "https://controlcenter-api.livepeer.live" ConfigReconcileInterval = "1m" -RegistryPaymentMode = "offchain" # Publish both images to the bundled registry and use the returned digests. RuntimeImage = "controlcenter-registry.livepeer.live/controlcenter/runtime@sha256:" @@ -35,3 +34,7 @@ TunnelDrainTimeout = "10m" TunnelNodeAddresses = [""] DiscoveryRefreshInterval = "5m" DiscoveryMaxFailedRefreshes = 6 + +# Enable with compose.paid.yaml after applying deployment-owned payment settings. +# PaymentSecretsDir = "/run/payment-rpc" +# PaymentWebhookSecretFile = "/run/secrets/payment-webhook-auth" diff --git a/deploy/payments.example.json b/deploy/payments.example.json new file mode 100644 index 0000000..435b0fc --- /dev/null +++ b/deploy/payments.example.json @@ -0,0 +1,23 @@ +{ + "version": 1, + "machines": { + "lp-aaaaaaaaaaaaaaaa": { + "version": 1, + "credential_revision": 1, + "mode": "paid", + "network": "arbitrum-one-mainnet", + "chain_id": 42161, + "controller": "0xD8E8328501E9645d16Cf49539efC04f734606ee4", + "recipient": "0x2222222222222222222222222222222222222222", + "rpc_secret": "arbitrum-rpc-v1", + "redeemer_url": "https://controlcenter-api.livepeer.live/redemption", + "eth_usd_feed": "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612", + "price_max_age": "2h", + "ticket_face_value": "1000000000000000", + "ticket_win_prob": "1000000000000000000000000000000000000000000000000000000000000000", + "max_pending_tickets": 100000, + "max_tickets_per_recipient": 10000 + }, + "lp-bbbbbbbbbbbbbbbb": {"version": 1, "mode": "offchain"} + } +} diff --git a/deploy/redeemer.example.toml b/deploy/redeemer.example.toml new file mode 100644 index 0000000..b2a9293 --- /dev/null +++ b/deploy/redeemer.example.toml @@ -0,0 +1,10 @@ +Network = "arbitrum-one-mainnet" +DataDir = "/home/livepeer/.lpData" +Listen = "unsafe@0.0.0.0:8941" +MetricsListen = "unsafe@0.0.0.0:8942" +RedeemerDB = "/home/livepeer/.lpData/tickets.sqlite" +KeystoreFile = "/run/redeemer/keystore.json" +KeystorePasswordFile = "/run/redeemer/password" +RPCURLFile = "/run/redeemer/rpc" +AuthWebhookFile = "/run/redeemer/auth-url" +AuthWebhookHeadersFile = "/run/redeemer/auth-headers" diff --git a/docs/app-registry.md b/docs/app-registry.md index 3cd7347..6be598f 100644 --- a/docs/app-registry.md +++ b/docs/app-registry.md @@ -112,18 +112,10 @@ private `path`, `capacity`, and `price`; paths must be unique and nonnested. ## Pricing policy -Set `RegistryPaymentMode` in the API configuration, or the -`REGISTRY_PAYMENT_MODE` environment variable, to one of: - -| Mode | Registry behavior | -| --- | --- | -| `offchain` | Default; allows zero or positive prices. | -| `onchain` | Requires a positive price for validation and new publications. | - -This setting controls registry policy; it does not configure payment mode on -Livepeer Nodes. The publication API returns an identical existing revision even -if it no longer meets the current pricing policy. The catalog UI requires -validation first, so it cannot submit such a definition in onchain mode. +Catalog prices remain generic and immutable. Assignment and registration compatibility +is evaluated against the target machine's desired and observed Node payment settings. +See [managed paid operation](paid-operation.md) for deployment configuration and +activation. Publishing a price does not activate paid operation on a Node. ## Catalog API diff --git a/docs/paid-operation.md b/docs/paid-operation.md new file mode 100644 index 0000000..d217984 --- /dev/null +++ b/docs/paid-operation.md @@ -0,0 +1,165 @@ +# Managed paid operation + +This workflow targets fresh Control Center databases and fresh Runtime installations. +The app catalog's exact decimal prices are the registration inputs. Deployment +configuration owns Node payment infrastructure; the machine UI inspects its state. +Offchain Node advertises free service even if a catalog revision has a positive quote. +Paid Node requires positive USD prices with `hour` or `fixed` units for every app. + +## Fresh setup + +Build Node with the redeemer authorization webhook and `RedeemerHeadersFile` support. +Build Runtime, then build `runtime/services/Dockerfile.node` with digest-pinned +`NODE_IMAGE` and `RUNTIME_IMAGE` arguments. Publish the resulting image and set its +actual digest as `RuntimeNodeImage`. Use that same compatible Node build for +`LIVEPEER_REDEEMER_IMAGE`. Record all component revisions and image digests in the +acceptance evidence. An arbitrary image digest is not evidence of compatibility. + +```sh +docker build -f runtime/services/Dockerfile.node \ + --build-arg NODE_IMAGE= \ + --build-arg RUNTIME_IMAGE= \ + -t runtime/services +docker push +``` + +Use the digest returned by the push rather than the mutable build tag. The Pod's +volume policy preserves owner-only SQLite permissions on subsequent mounts; +retain that policy together with the database and its sidecars. + +Copy `deploy/redeemer.example.toml` to `deploy/redeemer.toml`. Mount a dedicated +redemption wallet, its password, and its chain RPC file only in the redeemer. +Its wallet must satisfy Node's standalone redeemer policy; the ticket recipient +is the registered orchestrator, not the dedicated transaction-signing wallet. +Use a separate persistent redeemer database. The orchestrator keeps its own +payment database and SQLite sidecars under its retained `/data` volume. + +Create owner-only files readable by container UID 65532: + +- `deploy/secrets/payment-rpc/`: an HTTPS RPC URL. +- `deploy/secrets/payment-webhook-auth`: a random secret of at least 32 bytes. +- `deploy/secrets/redeemer/keystore.json`, `password`, and `rpc`. +- `deploy/secrets/redeemer/auth-url`: `http://api:43812/internal/redemption/authorize`. +- `deploy/secrets/redeemer/auth-headers`: `Authorization: Bearer `. + +Set `PaymentSecretsDir` and `PaymentWebhookSecretFile` in the API deployment +configuration as shown in `deploy/config.example.toml`. Start the fresh deployment +with `docker compose -f compose.yaml -f compose.paid.yaml --profile paid up -d`. +Only `POST /redemption/tickets` is exposed through the verified HTTPS API ingress. +Keep the redeemer's raw listener, metrics and webhook inaccessible externally. +The same-host deployment accepts host compromise as a trust-boundary limitation. + +Copy and edit `deploy/payments.example.json`, using real machine IDs and recipient +addresses. The supplied ticket terms are illustrative, not an economic recommendation. +Select appropriate funded validation limits and ticket terms for your deployment. +Apply from the trusted API deployment environment: + +```sh +controlcenter payments apply --config /etc/controlcenter/config.toml \ + --file /operator/payments.json --expected-revision 0 +``` + +The command prints the current deployment revision. Use that revision on the next +apply. Imports are complete snapshots: retain all currently paid machine entries, +or explicitly set one to `{"version":1,"mode":"offchain"}`. Do not supply generated +`generation` values. An identical retry is a no-op, including after a lost response. Stale changes conflict. +Settings, generations and audit records commit together. API processes consume +persisted desired settings rather than importing their own startup snapshot. + +The first recipient and chain/controller binding remain pinned to the machine +identity across offchain operation, removal and re-enrollment. Ordinary apply +cannot change those bindings. No operator price override or pricing profile exists. +Private RPC/redemption access requires explicit IP:port grants; use exact addresses +and ports in `rpc_grants` / `redeemer_grants`. Loopback and broad CIDRs are unsupported. +The grants are rendered only for orchestrator egress; app policies remain isolated. + +## Activation, changes and credentials + +The existing maintenance workflow withdraws new work, drains active work and holds +the previous workload before replacing Node. Failed startup stays failed; it never +switches to free service. Node remains reachable through its protected private +Service when payment readiness fails, allowing management and recovery. + +Runtime verifies the live Pod incarnation before fetching RPC and submission +credentials over its separate orchestrator socket. A private readiness probe also +matches the current PID 1 to the issued launch association before payment +observations can be current. Container restart cannot reuse an earlier process +observation. Files are owner-only and +memory-backed. The submission bearer authorizes only recipient-bound ticket +submission. It is distinct from machine management and the redeemer's webhook +service credential. Neither API nor app/Runtime pods receive the signing key. + +For RPC rotation, provision a new immutable secret filename and change `rpc_secret`. +Never replace a referenced file's bytes. Increment `credential_revision` to rotate +submission credentials. Retain old RPC files while held workloads or rollback +settings reference them. An observed replacement grant retires earlier submission +grants. Management credential refresh fences management immediately while a held +Node's submission grant may remain usable until replacement. Restarted Node fetches +credentials for its exact published configuration. + +Rollback to previous settings is an explicit new apply at the current revision; +generations never decrease. A previously retired submission bearer is not restored: +a new process obtains a new grant. Keep immutable RPC secret versions available. + +## Failure, retirement and recovery + +Configuration application, local paid readiness and remote redemption handoff are +separate observations. A successful `/readyz`, download or empty worker pass does +not prove authorized handoff. `unverified` means no current successful handoff has +been observed; `degraded` reflects submission failures. Node's durable queue and +backpressure continue governing redemption outages. + +Disable, destination change and ordinary removal wait for app drain and fresh +successful evidence of zero unsettled tickets. Missing, stale or incomplete queue +evidence blocks completion. Drain expiry requires the existing audited retry. +Normal removal retains the paid workload and credentials while settling tickets. +An observed offchain replacement revokes the previous paid workload's submission +grants after the required drain completes. + +Forced removal or account deletion revokes submission grants immediately. Already +accepted tickets continue at the redeemer. Retained local tickets require explicit +recovery, reported as `recovery_required`; physical cleanup does not mean payments +drained. Preserve the orchestrator database and its sidecars. Re-enroll the same +machine identity and recover the retained database with its pinned recipient and +chain settings before resuming submission. Once the restored Node has reported a fresh successful +zero-unsettled observation, apply the same desired snapshot with +`--acknowledge-recovery ` and the current expected revision. This +records an explicit recovery audit event and clears the recovery-required flag. +After a paid Node has initialized successfully, credential delivery requires its +existing payment database; a missing database fails startup instead of silently +creating a replacement. Do not discard databases to clear an +error or reinterpret retained state on a different chain or recipient. + +Back up SQLite through a consistent online backup or while the writer is stopped; +retain the matching database/WAL state. Back up the redeemer database separately +from the orchestrator's, and keep signing-key backups under operator control. + +## Acceptance evidence + +Use two freshly installed CPU machines with different infrastructure settings and +unchanged shared catalog revisions. Record component commits/digests, desired and +observed generations, bounded spending/runtime limits, and redacted outcomes. +Exercise paid discovery/admission/execution/accounting, winning-ticket handoff, +lost acknowledgements, Node/redeemer restarts, webhook/redemption outages and +backpressure, rotation, ordinary/forced retirement and retained-state recovery. +Verify signing-key isolation, private endpoint reachability and blocked app access. +Keep application correctness, authorization, durable handoff and settlement results +separate. Local unit tests alone do not complete the funded #93/#118 gate. + +## Configuration and implementation ownership + +For #119, the deployment operator applies infrastructure settings through the +deployment CLI. Central administrator status, machine ownership and machine +credentials do not grant payment mutation authority. The browser exposes scoped +inspection only. PostgreSQL holds the authoritative desired settings. + +Control Center owns immutable recipient bindings, versioned secret references, +submission grants, the private authorization callback and configuration/audit +transactions. Runtime owns machine delivery, live Pod/process checks, private +credential files, activation/drain coordination and bounded observations. Node +owns price conversion, ticket validation, durable admission, acknowledgements, +retry and settlement. Its standalone redeemer alone holds the signing key. + +#93 owns funded challenge-app execution evidence using #90's responder/verifier; +#118 owns the broader fleet acceptance matrix. Record their remaining gates +separately from configuration integration and local verification. diff --git a/go.mod b/go.mod index 2d39d78..0fcacc9 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/jackc/pgx/v5 v5.11.0 github.com/livepeer/golang-runner v0.0.0-20261110073804-8664fdb1f080 github.com/livepeer/node v1.0.7-0.20261106162658-d5af6f14f102 + github.com/prometheus/common v0.72.0 github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 github.com/spf13/cobra v1.10.2 go.yaml.in/yaml/v3 v3.0.5 @@ -27,7 +28,6 @@ require ( github.com/opencontainers/go-digest v1.0.0 // indirect github.com/prometheus/client_golang v1.25.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect - github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect github.com/spf13/pflag v1.0.10 // indirect golang.org/x/sync v0.24.0 // indirect diff --git a/runtime/appreconciler/controller.go b/runtime/appreconciler/controller.go index 7a4ff00..f93ac79 100644 --- a/runtime/appreconciler/controller.go +++ b/runtime/appreconciler/controller.go @@ -50,6 +50,10 @@ func (c *Controller) hooks() OwnerHooks { return OwnerHooks{Observe: c.observe, Failure: c.failed, Now: c.now, Eligibility: func(r Registration) (bool, bool) { member, ready := c.Journal.Eligibility(r) + state := c.Journal.View() + if state.Metadata.Payment.Paid() && !state.Metadata.PaymentActive { + ready = false + } return member, ready && c.Probes != nil && c.Probes.Ready(r.InstanceID, r.PodUID) }} } @@ -343,6 +347,14 @@ func (c *Controller) Tick(ctx context.Context) error { }) for _, g := range groups { a := assignments[g.RevisionID] + if s.Metadata.Payment.Paid() && !s.Metadata.PaymentActive { + s.AssignmentReasons[a.RevisionID] = "payment_pending" + continue + } + if a.Revision != nil && s.Metadata.Payment.Compatible(a.Revision.Definition) != nil { + s.AssignmentReasons[a.RevisionID] = "payment_incompatible" + continue + } if !a.StartAllowed { s.AssignmentReasons[a.RevisionID] = "cleanup_prerequisite" continue @@ -594,11 +606,14 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo continue } pod, exists := view.Pods[i.Name] + if s.Metadata.Payment.Paid() && !s.Metadata.PaymentActive && i.AppID == "" { + continue + } if i.AppID == "" && (!exists || pod.UID != i.PodUID || pod.Deleting || pod.Phase != "Running") { continue } signalOK := i.Definition.Lifecycle.StopSignal == nil || (exists && pod.StopSignal == *i.Definition.Lifecycle.StopSignal) - if i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { + if (!s.Metadata.Payment.Paid() || s.Metadata.PaymentActive) && i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { for n := range registrations { registrations[n].Options.Status = "ready" } diff --git a/runtime/appreconciler/input.go b/runtime/appreconciler/input.go index 5721fb7..420f3e0 100644 --- a/runtime/appreconciler/input.go +++ b/runtime/appreconciler/input.go @@ -7,6 +7,7 @@ import ( "net/http" "net/url" "strings" + "time" "github.com/livepeer/control-center/runtime/appbundle" "github.com/livepeer/control-center/runtime/artifact" @@ -71,6 +72,9 @@ func (s Source) Read(ctx context.Context) (Input, error) { if err != nil || identity.Epoch != m.Epoch || identity.CredentialVersion != m.CredentialVersion { return input, errors.New("management_enrollment") } + if m.Payment.Paid() && m.PaymentActive { + m.PaymentActive = s.paymentActive(ctx, m) + } p, err := appbundle.Read(files, m) if err != nil { // Whole-archive/enrollment checks already succeeded. An invalid app payload @@ -80,3 +84,40 @@ func (s Source) Read(ctx context.Context) (Input, error) { } return Input{Metadata: m, Payload: p, Digest: a.Digest}, nil } + +// Payment eligibility is checked against the live process, even when an offline +// artifact repeats an earlier approval. Dependency loss cannot suppress drain. +func (s Source) paymentActive(ctx context.Context, m contract.Metadata) bool { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var pods struct { + Items []struct { + Metadata struct { + DeletionTimestamp *string `json:"deletionTimestamp"` + Annotations map[string]string `json:"annotations"` + } `json:"metadata"` + } `json:"items"` + } + if s.Kube.Request(ctx, "GET", "/api/v1/namespaces/livepeer/pods?labelSelector=app%3Dorchestrator", nil, &pods) != nil { + return false + } + live := 0 + for _, p := range pods.Items { + if p.Metadata.DeletionTimestamp == nil { + if p.Metadata.Annotations["livepeer.io/config-sha256"] != m.ConfigDigest { + return false + } + live++ + } + } + if live != 1 { + return false + } + req, _ := http.NewRequestWithContext(ctx, "GET", "http://orchestrator.livepeer.svc.cluster.local:8936/readyz", nil) + resp, e := s.Client.Do(req) + if e != nil { + return false + } + defer resp.Body.Close() + return resp.StatusCode == 200 +} diff --git a/runtime/appreconciler/payment_test.go b/runtime/appreconciler/payment_test.go new file mode 100644 index 0000000..8d5fcee --- /dev/null +++ b/runtime/appreconciler/payment_test.go @@ -0,0 +1,80 @@ +package appreconciler + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/transport" +) + +type paymentTransport func(*http.Request) (*http.Response, error) + +func (f paymentTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +func TestPaidAdmissionRequiresLiveMatchingNode(t *testing.T) { + digest := strings.Repeat("a", 64) + pods := 1 + ready := 200 + kube := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + items := []any{} + for range pods { + items = append(items, map[string]any{"metadata": map[string]any{"annotations": map[string]string{"livepeer.io/config-sha256": digest}}}) + } + json.NewEncoder(w).Encode(map[string]any{"items": items}) + })) + defer kube.Close() + token := filepath.Join(t.TempDir(), "token") + os.WriteFile(token, []byte("fixture"), 0600) + source := Source{Kube: &transport.Kube{Base: kube.URL, TokenFile: token, Client: kube.Client()}, Client: &http.Client{Transport: paymentTransport(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: ready, Body: io.NopCloser(strings.NewReader("ready")), Header: make(http.Header)}, nil + })}} + m := contract.Metadata{ConfigDigest: digest} + if !source.paymentActive(context.Background(), m) { + t.Fatal("matching ready Node rejected") + } + ready = 503 + if source.paymentActive(context.Background(), m) { + t.Fatal("cached approval admitted on unready Node") + } + ready = 200 + digest = strings.Repeat("b", 64) + if source.paymentActive(context.Background(), m) { + t.Fatal("different generation admitted") + } + digest = m.ConfigDigest + pods = 2 + if source.paymentActive(context.Background(), m) { + t.Fatal("ambiguous Node incarnation admitted") + } +} +func TestPendingPaidTargetDoesNotAllocateOrAdmit(t *testing.T) { + c, input, cluster, owner, _, _ := fixtureController(t) + input.value.Metadata.Payment = payment.Config{Mode: "paid", Generation: 1} + input.value.Metadata.PaymentActive = false + tick(t, c) + if len(c.Journal.View().Instances) != 0 { + t.Fatal("pending paid target allocated work") + } + input.value.Metadata.PaymentActive = true + registerApps(t, c, cluster) + input.value.Metadata.PaymentActive = false + tick(t, c) + for _, entry := range owner.accepted.Entries { + if entry.Options.Status == "ready" { + t.Fatal("readiness loss admitted new work") + } + } + for _, instance := range c.Journal.View().Instances { + if instance.WithdrawalID != "" { + t.Fatal("temporary payment readiness loss became terminal withdrawal") + } + } +} diff --git a/runtime/bootstrap-livepeer.sh b/runtime/bootstrap-livepeer.sh index 3da5942..5cebd39 100755 --- a/runtime/bootstrap-livepeer.sh +++ b/runtime/bootstrap-livepeer.sh @@ -172,9 +172,9 @@ prepare_installation() { "$INSTALL_DIR/volumes/http-source" "$INSTALL_DIR/volumes/orchestrator" "$INSTALL_DIR/volumes/app-reconciler" chown 65532:65532 "$INSTALL_DIR/volumes/http-source" "$INSTALL_DIR/volumes/orchestrator" "$INSTALL_DIR/volumes/app-reconciler" install -d -m 0700 "$INSTALL_DIR/volumes/management-sockets" \ - "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" + "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" "$INSTALL_DIR/volumes/management-sockets/orchestrator" chown 65532:65532 "$INSTALL_DIR/volumes/management-sockets" \ - "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" + "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" "$INSTALL_DIR/volumes/management-sockets/orchestrator" printf '%s\n' "$RUNTIME_IMAGE" | atomic_write "$INSTALL_DIR/state/runtime-image" chmod 0700 "$INSTALL_DIR/k3s" "$INSTALL_DIR/kubelet" write_once "$INSTALL_DIR/credentials/node-id" "$NODE_ID" diff --git a/runtime/cmd/livepeer-runtime/main.go b/runtime/cmd/livepeer-runtime/main.go index fcf2aa3..a7377d4 100644 --- a/runtime/cmd/livepeer-runtime/main.go +++ b/runtime/cmd/livepeer-runtime/main.go @@ -22,6 +22,7 @@ import ( "github.com/livepeer/control-center/runtime/httpsource" "github.com/livepeer/control-center/runtime/management" "github.com/livepeer/control-center/runtime/nodeproxy" + "github.com/livepeer/control-center/runtime/orchestrator" "github.com/livepeer/control-center/runtime/transport" ) @@ -38,6 +39,13 @@ func run(ctx context.Context, args []string) error { return errors.New("choose http-source, app-reconciler, connector-start, connector-probe, node-proxy or node-proxy-probe") } switch args[0] { + case "orchestrator-start": + return orchestrator.Start(ctx, args[1:]) + case "orchestrator-probe": + if !orchestrator.Probe(ctx) { + return errors.New("orchestrator not ready") + } + return nil case "http-source": return httpSource(ctx, args[1:]) case "app-reconciler": @@ -248,7 +256,10 @@ func httpSource(ctx context.Context, args []string) error { socketErrors := make(chan error, 1) integration := &connector.Integration{Reporter: &transport.Reports{Client: control, Directory: filepath.Join(*directory, "reports")}, Control: control, Kube: kube, Desired: source.Desired, StateFile: filepath.Join(*directory, "connector-grant.json")} integration.Restore() - sockets, err := management.Listen(*socketRoot, integration, management.AppReports{Control: control, Desired: source.Desired}) + payments := &orchestrator.Integration{Control: control, Kube: kube, Desired: source.Desired, TokenFile: *token, StateFile: filepath.Join(*directory, "payment-grant.json"), AllowHTTP: control.AllowHTTP} + payments.Restore() + source.Payment = payments.Observe + sockets, err := management.Listen(*socketRoot, integration, management.AppReports{Control: control, Desired: source.Desired}, payments) if err != nil { return err } diff --git a/runtime/connector/identity.go b/runtime/connector/identity.go index c932d55..907c72b 100644 --- a/runtime/connector/identity.go +++ b/runtime/connector/identity.go @@ -27,3 +27,6 @@ func hashProcess(boot, namespace, stat string) (string, error) { digest := sha256.Sum256([]byte(strings.TrimSpace(boot) + "\n" + namespace + "\n" + start)) return hex.EncodeToString(digest[:]), nil } + +// ProcessIdentity identifies PID 1 across exec for protected credential consumers. +func ProcessIdentity() (string, error) { return processIdentity() } diff --git a/runtime/contract/contract.go b/runtime/contract/contract.go index 7b7a833..5e55f14 100644 --- a/runtime/contract/contract.go +++ b/runtime/contract/contract.go @@ -1,41 +1,47 @@ // Package contract contains the machine wire contract shared by delivery and Runtime. package contract -import "time" +import ( + "github.com/livepeer/control-center/runtime/payment" + "time" +) const BundleFormat = 3 type Metadata struct { - NodeID string `json:"node_id"` - Epoch string `json:"epoch"` - CredentialVersion int64 `json:"credential_version"` - Generation int64 `json:"generation"` - Terminal bool `json:"terminal"` - TerminalCleanup bool `json:"terminal_cleanup,omitempty"` - TerminalInputDigest string `json:"terminal_input_digest,omitempty"` - DrainRequested bool `json:"drain_requested"` - ConfigDigest string `json:"config_digest"` - ServiceURL string `json:"service_url"` - TunnelID string `json:"tunnel_id"` - TokenGeneration int64 `json:"credential_generation"` - ProviderVersion int64 `json:"provider_version"` - APIURL string `json:"api_url"` - RunnerServiceURL string `json:"runner_service_url"` - ProxyURLTemplate string `json:"proxy_url_template"` - DiscoveryURL string `json:"discovery_url"` - IngressDigest string `json:"ingress_digest"` - AppsGeneration int64 `json:"apps_generation,omitempty"` - AppsDigest string `json:"apps_digest,omitempty"` - ConnectorTokenRef string `json:"connector_token_ref"` - BundleFormat int `json:"bundle_format,omitempty"` - AppsPayloadDigest string `json:"apps_payload_digest,omitempty"` - AppsError string `json:"apps_error,omitempty"` - RequestedAppsGeneration int64 `json:"requested_apps_generation,omitempty"` - DrainTarget string `json:"drain_target,omitempty"` - DrainStartedAt time.Time `json:"drain_started_at,omitempty"` - DrainDeadline time.Time `json:"drain_deadline,omitempty"` - UpgradeDigest string `json:"upgrade_digest,omitempty"` - UpgradeVersion string `json:"upgrade_version,omitempty"` + Payment payment.Config `json:"payment"` + PaymentCredentialsRef string `json:"payment_credentials_ref,omitempty"` + PaymentActive bool `json:"payment_active"` + NodeID string `json:"node_id"` + Epoch string `json:"epoch"` + CredentialVersion int64 `json:"credential_version"` + Generation int64 `json:"generation"` + Terminal bool `json:"terminal"` + TerminalCleanup bool `json:"terminal_cleanup,omitempty"` + TerminalInputDigest string `json:"terminal_input_digest,omitempty"` + DrainRequested bool `json:"drain_requested"` + ConfigDigest string `json:"config_digest"` + ServiceURL string `json:"service_url"` + TunnelID string `json:"tunnel_id"` + TokenGeneration int64 `json:"credential_generation"` + ProviderVersion int64 `json:"provider_version"` + APIURL string `json:"api_url"` + RunnerServiceURL string `json:"runner_service_url"` + ProxyURLTemplate string `json:"proxy_url_template"` + DiscoveryURL string `json:"discovery_url"` + IngressDigest string `json:"ingress_digest"` + AppsGeneration int64 `json:"apps_generation,omitempty"` + AppsDigest string `json:"apps_digest,omitempty"` + ConnectorTokenRef string `json:"connector_token_ref"` + BundleFormat int `json:"bundle_format,omitempty"` + AppsPayloadDigest string `json:"apps_payload_digest,omitempty"` + AppsError string `json:"apps_error,omitempty"` + RequestedAppsGeneration int64 `json:"requested_apps_generation,omitempty"` + DrainTarget string `json:"drain_target,omitempty"` + DrainStartedAt time.Time `json:"drain_started_at,omitempty"` + DrainDeadline time.Time `json:"drain_deadline,omitempty"` + UpgradeDigest string `json:"upgrade_digest,omitempty"` + UpgradeVersion string `json:"upgrade_version,omitempty"` } type Evidence struct { diff --git a/runtime/httpsource/source.go b/runtime/httpsource/source.go index 3852eae..016d25e 100644 --- a/runtime/httpsource/source.go +++ b/runtime/httpsource/source.go @@ -19,6 +19,7 @@ import ( "github.com/livepeer/control-center/runtime/appbundle" "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/runtime/transport" ) @@ -30,6 +31,7 @@ type Kubernetes interface { Publish(context.Context, string, *transport.Artifact, bool, string) error } type Source struct { + Payment func(context.Context, contract.Metadata, bool, bool, string) *payment.Observation Control *transport.Control Reporter transport.Requester Kube Kubernetes @@ -283,6 +285,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr } ready := false actual := "" + podUID := "" var deployment struct { Metadata struct { Generation int64 `json:"generation"` @@ -307,6 +310,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr var pods struct { Items []struct { Metadata struct { + UID string `json:"uid"` DeletionTimestamp *string `json:"deletionTimestamp"` Annotations map[string]string `json:"annotations"` } `json:"metadata"` @@ -323,6 +327,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr for _, p := range pods.Items { if p.Metadata.DeletionTimestamp == nil { count++ + podUID = p.Metadata.UID actual = p.Metadata.Annotations["livepeer.io/config-sha256"] for _, c := range p.Status.Conditions { podReady = podReady || (c.Type == "Ready" && c.Status == "True") @@ -379,6 +384,9 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr ready = ready && k3sVersion == m.UpgradeVersion } reason := "applying" + if m.Payment.Paid() && applied && actual == m.ConfigDigest && !ready { + reason = "payment_not_ready" + } if ready { reason = "ready" } @@ -388,6 +396,9 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr } payload := map[string]any{"epoch": m.Epoch, "credential_version": m.CredentialVersion, "component": "runtime", "generation": m.Generation, "bundle_sha256": strings.TrimPrefix(revision, "sha256:"), "config_digest": actual, "k3s_version": k3sVersion, "ready": ready, "https": strings.HasPrefix(s.Control.ConfigURL, "https://"), "reason": reason, "bundle_format": contract.BundleFormat, "apps_error": appErrorReason(appError), "observed_at": time.Now().UTC()} + if s.Payment != nil { + payload["payment"] = s.Payment(ctx, m, applied && actual == m.ConfigDigest && podUID != "", ready, podUID) + } if d := s.reporting.Load(); d != nil { payload["downloaded"], payload["downloaded_at"] = d.Downloaded, d.DownloadedAt } diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index b56e157..792581c 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -111,9 +111,9 @@ transition_credentials() { install -d -m 0700 "$INSTALL_DIR/volumes/app-reconciler" chown 65532:65532 "$INSTALL_DIR/volumes/app-reconciler" install -d -m 0700 "$INSTALL_DIR/volumes/management-sockets" \ - "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" + "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" "$INSTALL_DIR/volumes/management-sockets/orchestrator" chown 65532:65532 "$INSTALL_DIR/volumes/management-sockets" \ - "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" + "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" "$INSTALL_DIR/volumes/management-sockets/orchestrator" printf '%s\n' "$RUNTIME_IMAGE" | atomic_write "$INSTALL_DIR/state/runtime-image" LIVEPEER_ALLOW_DEVELOPMENT_HTTP=0 CONFIG_URL="$api/v1/nodes/$NODE_ID/config" diff --git a/runtime/management/sockets.go b/runtime/management/sockets.go index 2aeb2ce..eb82d71 100644 --- a/runtime/management/sockets.go +++ b/runtime/management/sockets.go @@ -19,8 +19,8 @@ type Sockets struct { cancel context.CancelFunc } -// Listen acquires the publisher lock before opening the two fixed consumer endpoints. -func Listen(root string, connector, apps http.Handler) (*Sockets, error) { +// Listen acquires the publisher lock before opening the fixed consumer endpoints. +func Listen(root string, connector, apps, orchestrator http.Handler) (*Sockets, error) { if !filepath.IsAbs(root) || filepath.Clean(root) != root { return nil, errors.New("management_socket_directory") } @@ -44,10 +44,11 @@ func Listen(root string, connector, apps http.Handler) (*Sockets, error) { s.Close() return nil, errors.New("management_already_running") } - for _, consumer := range []struct { + consumers := []struct { name string handler http.Handler - }{{"connector", connector}, {"apps", apps}} { + }{{"connector", connector}, {"apps", apps}, {"orchestrator", orchestrator}} + for _, consumer := range consumers { directory := filepath.Join(root, consumer.name) info, err := os.Lstat(directory) if err == nil && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0) { diff --git a/runtime/management/sockets_test.go b/runtime/management/sockets_test.go index 33b1b7d..28f6da8 100644 --- a/runtime/management/sockets_test.go +++ b/runtime/management/sockets_test.go @@ -40,7 +40,7 @@ func TestScopedSocketsAndEnrollmentFencedAppReporting(t *testing.T) { } w.Write([]byte(`{}`)) }) - sockets, err := Listen(root, connector, apps) + sockets, err := Listen(root, connector, apps, http.NotFoundHandler()) if err != nil { t.Fatal(err) } @@ -48,11 +48,11 @@ func TestScopedSocketsAndEnrollmentFencedAppReporting(t *testing.T) { defer cancel() defer sockets.Close() go sockets.Run(ctx) - if other, err := Listen(root, connector, apps); err == nil { + if other, err := Listen(root, connector, apps, http.NotFoundHandler()); err == nil { other.Close() t.Fatal("two management publishers acquired the same root") } - for _, consumer := range []string{"connector", "apps"} { + for _, consumer := range []string{"connector", "apps", "orchestrator"} { info, err := os.Stat(filepath.Join(root, consumer)) if err != nil || info.Mode().Perm() != 0700 { t.Fatal("consumer directory exposed") @@ -108,14 +108,14 @@ func TestSocketStartupRefusesSymlinkAndNonSocketPaths(t *testing.T) { if err = os.Symlink(t.TempDir(), filepath.Join(root, "connector")); err != nil { t.Fatal(err) } - if s, err := Listen(root, handler, handler); err == nil { + if s, err := Listen(root, handler, handler, handler); err == nil { s.Close() t.Fatal("followed consumer symlink") } os.Remove(filepath.Join(root, "connector")) os.Mkdir(filepath.Join(root, "connector"), 0700) os.WriteFile(filepath.Join(root, "connector", "control.sock"), []byte(strings.Repeat("x", 4)), 0600) - if s, err := Listen(root, handler, handler); err == nil { + if s, err := Listen(root, handler, handler, handler); err == nil { s.Close() t.Fatal("replaced non-socket") } diff --git a/runtime/manifests/bootstrap/rbac.yaml b/runtime/manifests/bootstrap/rbac.yaml index 6693503..eaf3638 100644 --- a/runtime/manifests/bootstrap/rbac.yaml +++ b/runtime/manifests/bootstrap/rbac.yaml @@ -64,7 +64,7 @@ rules: verbs: [get] - apiGroups: [''] resources: [pods] - verbs: [list] + verbs: [get, list] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/runtime/orchestrator/integration.go b/runtime/orchestrator/integration.go new file mode 100644 index 0000000..63a228f --- /dev/null +++ b/runtime/orchestrator/integration.go @@ -0,0 +1,192 @@ +// Package orchestrator delivers payment credentials to a verified Node process. +package orchestrator + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "os" + "regexp" + "sync" + "time" + + "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/connector" + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/transport" +) + +type Launch = connector.Launch +type Association struct { + Launch + Epoch string `json:"epoch"` + CredentialVersion int64 `json:"credential_version"` + PaymentGeneration int64 `json:"payment_generation"` + ConfigDigest string `json:"config_digest"` + GrantID string `json:"grant_id"` +} +type Request struct { + Launch + PaymentGeneration int64 `json:"payment_generation"` + ConfigDigest string `json:"config_digest"` +} +type Grant struct { + Association + RPCURL string `json:"rpc_url"` + Headers string `json:"headers"` + RequireState bool `json:"require_state"` +} +type ProcessObservation struct { + Association + ObservedAt time.Time `json:"observed_at"` + Ready bool `json:"ready"` +} + +type Kubernetes interface { + Request(context.Context, string, string, any, any) error +} +type Control interface { + Request(context.Context, string, any, int64) ([]byte, http.Header, error) +} +type Integration struct { + Control Control + Kube Kubernetes + Desired func() (contract.Metadata, bool) + TokenFile, StateFile string + AllowHTTP bool + mu sync.Mutex + order uint64 + metricsGrant string + lastAck, lastErr float64 + ackAt, errAt time.Time + grant *Association + observation *ProcessObservation +} + +var namePattern = regexp.MustCompile(`^[a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?$`) +var noncePattern = regexp.MustCompile(`^[0-9a-f]{32}$`) +var processPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) + +func ValidLaunch(l Launch) bool { + return namePattern.MatchString(l.PodName) && l.PodUID != "" && len(l.PodUID) <= 128 && noncePattern.MatchString(l.LaunchID) && processPattern.MatchString(l.ProcessID) +} +func (i *Integration) Restore() { + b, e := os.ReadFile(i.StateFile) + var a Association + if e == nil && len(b) < 16384 && json.Unmarshal(b, &a) == nil && ValidLaunch(a.Launch) && a.GrantID != "" { + i.grant = &a + } +} +func (i *Integration) checkPod(ctx context.Context, l Launch, m contract.Metadata) error { + var p struct { + Metadata struct { + UID string `json:"uid"` + DeletionTimestamp *string `json:"deletionTimestamp"` + Labels map[string]string `json:"labels"` + Annotations map[string]string `json:"annotations"` + } `json:"metadata"` + } + if !ValidLaunch(l) || i.Kube.Request(ctx, "GET", "/api/v1/namespaces/livepeer/pods/"+url.PathEscape(l.PodName), nil, &p) != nil || p.Metadata.UID != l.PodUID || p.Metadata.DeletionTimestamp != nil || p.Metadata.Labels["app"] != "orchestrator" || p.Metadata.Annotations["livepeer.io/config-sha256"] != m.ConfigDigest { + return errors.New("orchestrator_incarnation") + } + return nil +} +func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" || r.URL.RawQuery != "" { + http.Error(w, "operation refused", 403) + return + } + b, e := io.ReadAll(io.LimitReader(r.Body, 4097)) + if e != nil || len(b) > 4096 { + http.Error(w, "request refused", 400) + return + } + if r.URL.Path == "/payment/observation" { + var o ProcessObservation + m, ok := i.Desired() + if transport.Decode(b, &o) != nil || !ok || m.TerminalCleanup || o.Epoch != m.Epoch || o.ConfigDigest != m.ConfigDigest || o.PaymentGeneration != m.Payment.Generation || time.Since(o.ObservedAt) > 15*time.Second || o.ObservedAt.After(time.Now().Add(5*time.Second)) || i.checkPod(r.Context(), o.Launch, m) != nil { + http.Error(w, "observation refused", 409) + return + } + i.mu.Lock() + defer i.mu.Unlock() + if i.grant == nil || *i.grant != o.Association { + http.Error(w, "observation refused", 409) + return + } + if i.observation == nil || o.ObservedAt.After(i.observation.ObservedAt) { + i.observation = &o + } + w.Write([]byte("{}\n")) + return + } + if r.URL.Path != "/payment/credentials" { + http.Error(w, "operation refused", 403) + return + } + var l Launch + if transport.Decode(b, &l) != nil || !ValidLaunch(l) { + http.Error(w, "launch refused", 400) + return + } + grant, e := i.fetch(r.Context(), l) + if e != nil { + http.Error(w, "payment credential unavailable", 503) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(grant) +} +func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { + bad := errors.New("payment_credential_unavailable") + m, ok := i.Desired() + if !ok || i.AllowHTTP || !m.Payment.Paid() || m.TerminalCleanup || m.PaymentCredentialsRef != "/v1/nodes/"+m.NodeID+"/payment/credentials" { + return Grant{}, bad + } + before, e := os.ReadFile(i.TokenFile) + if e != nil || i.checkPod(ctx, l, m) != nil { + return Grant{}, bad + } + i.mu.Lock() + i.order++ + order := i.order + i.mu.Unlock() + b, _, e := i.Control.Request(ctx, "payment/credentials", Request{l, m.Payment.Generation, m.ConfigDigest}, 16384) + if e != nil { + return Grant{}, bad + } + var g Grant + if transport.Decode(b, &g) != nil || g.Launch != l || g.Epoch != m.Epoch || g.CredentialVersion != m.CredentialVersion || g.PaymentGeneration != m.Payment.Generation || g.ConfigDigest != m.ConfigDigest || g.GrantID == "" || g.RPCURL == "" || g.Headers == "" { + return Grant{}, bad + } + if i.checkPod(ctx, l, m) != nil { + return Grant{}, bad + } + authorized := func() bool { + after, e := os.ReadFile(i.TokenFile) + n, ok := i.Desired() + return ctx.Err() == nil && e == nil && ok && n.Epoch == m.Epoch && n.CredentialVersion == m.CredentialVersion && n.Generation == m.Generation && n.ConfigDigest == m.ConfigDigest && n.Payment.Generation == m.Payment.Generation && sha256.Sum256(before) == sha256.Sum256(after) + } + i.mu.Lock() + defer i.mu.Unlock() + if order != i.order || !authorized() { + return Grant{}, bad + } + b, _ = json.Marshal(g.Association) + if artifact.AtomicWrite(i.StateFile, b, 0600) != nil { + return Grant{}, bad + } + if !authorized() { + i.grant = nil + _ = artifact.AtomicWrite(i.StateFile, []byte("{}"), 0600) + return Grant{}, bad + } + a := g.Association + i.grant = &a + i.observation = nil + return g, nil +} diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go new file mode 100644 index 0000000..1831279 --- /dev/null +++ b/runtime/orchestrator/integration_test.go @@ -0,0 +1,192 @@ +package orchestrator + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" +) + +type kubeFunc func(context.Context, string, string, any, any) error + +func (f kubeFunc) Request(c context.Context, m, p string, in, out any) error { + return f(c, m, p, in, out) +} + +type controlFunc func(context.Context, string, any, int64) ([]byte, http.Header, error) + +func (f controlFunc) Request(c context.Context, p string, in any, n int64) ([]byte, http.Header, error) { + return f(c, p, in, n) +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) { + t.Helper() + dir := t.TempDir() + token := filepath.Join(dir, "token") + os.WriteFile(token, []byte("machine-secret"), 0600) + m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Payment: payment.Config{Mode: "paid", Generation: 2}, PaymentCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/payment/credentials"} + l := Launch{PodName: "orchestrator-test", PodUID: "uid", LaunchID: strings.Repeat("b", 32), ProcessID: strings.Repeat("c", 64)} + i := &Integration{TokenFile: token, StateFile: filepath.Join(dir, "grant.json"), Desired: func() (contract.Metadata, bool) { return m, true }} + i.Kube = kubeFunc(func(_ context.Context, _, p string, _ any, out any) error { + if !strings.Contains(p, "/livepeer/pods/") { + t.Fatal(p) + } + b, _ := json.Marshal(map[string]any{"metadata": map[string]any{"uid": l.PodUID, "labels": map[string]string{"app": "orchestrator"}, "annotations": map[string]string{"livepeer.io/config-sha256": m.ConfigDigest}}}) + return json.Unmarshal(b, out) + }) + i.Control = controlFunc(func(_ context.Context, p string, in any, _ int64) ([]byte, http.Header, error) { + if p != "payment/credentials" { + t.Fatal(p) + } + b, _ := json.Marshal(Grant{Association: Association{Launch: l, Epoch: m.Epoch, CredentialVersion: 1, PaymentGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) + return b, nil, nil + }) + return i, m, l +} +func TestPaymentDeliveryFencesAndSecretPersistence(t *testing.T) { + i, _, l := integrationFixture(t) + g, e := i.fetch(t.Context(), l) + if e != nil || g.Headers == "" { + t.Fatal(e) + } + b, e := os.ReadFile(i.StateFile) + if e != nil || strings.Contains(string(b), "redemption-secret") || strings.Contains(string(b), "rpc.example") { + t.Fatal("persisted secret", e) + } + old := i.Control + i.Control = controlFunc(func(ctx context.Context, p string, in any, n int64) ([]byte, http.Header, error) { + b, h, e := old.Request(ctx, p, in, n) + os.WriteFile(i.TokenFile, []byte("refreshed"), 0600) + return b, h, e + }) + if _, e = i.fetch(t.Context(), l); e == nil { + t.Fatal("refresh raced delivery") + } + i.AllowHTTP = true + if _, e = i.fetch(t.Context(), l); e == nil { + t.Fatal("insecure delivery") + } +} +func TestPaymentQueueEvidenceAndHandoffAreIndependent(t *testing.T) { + i, m, l := integrationFixture(t) + g, e := i.fetch(t.Context(), l) + if e != nil { + t.Fatal(e) + } + if i.Observe(t.Context(), m, true, true, l.PodUID).Applied { + t.Fatal("Pod UID alone renewed an earlier process grant") + } + processProof(t, i, g.Association, true) + old := http.DefaultClient + t.Cleanup(func() { http.DefaultClient = old }) + body := "# TYPE livepeer_collector_healthy gauge\n# TYPE livepeer_redemption_queue_tickets gauge\n# TYPE livepeer_redemption_transitions_total counter\nlivepeer_collector_healthy{component=\"orchestrator\",collector=\"redemptions\"} 1\n" + for _, s := range []string{"waiting", "eligible", "in_flight", "awaiting_finality", "rejected", "blocked", "unknown"} { + body += "livepeer_redemption_queue_tickets{component=\"orchestrator\",state=\"" + s + "\"} 0\n" + } + metrics := body + http.DefaultClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(metrics)), Header: make(http.Header)}, nil + })} + o := i.Observe(t.Context(), m, true, true, l.PodUID) + if !o.QueueKnown || o.Unsettled != 0 || !o.Ready || o.Handoff != "unverified" { + t.Fatal(o) + } + metrics = body + "livepeer_redemption_transitions_total{component=\"orchestrator\",event=\"retryable\"} 1\n" + o = i.Observe(t.Context(), m, true, true, l.PodUID) + if !o.Ready || o.Handoff != "degraded" { + t.Fatal(o) + } + i.errAt = time.Now().Add(-3 * time.Minute) + if i.Observe(t.Context(), m, true, true, l.PodUID).Handoff != "unverified" { + t.Fatal("repeated metrics renewed old failed handoff evidence") + } + metrics += "livepeer_redemption_transitions_total{component=\"orchestrator\",event=\"acknowledged\"} 1\n" + o = i.Observe(t.Context(), m, true, true, l.PodUID) + if o.Handoff != "healthy" { + t.Fatal(o) + } + restarted := &Integration{Kube: i.Kube, Desired: i.Desired, StateFile: i.StateFile} + restarted.Restore() + processProof(t, restarted, g.Association, true) + if restarted.Observe(t.Context(), m, true, true, l.PodUID).Handoff != "unverified" { + t.Fatal("management restart renewed old handoff evidence") + } + + metrics = "livepeer_collector_healthy{component=\"orchestrator\",collector=\"redemptions\"} 1\n" + if i.Observe(t.Context(), m, true, true, l.PodUID).QueueKnown { + t.Fatal("missing samples fabricated empty queue") + } + if i.Observe(t.Context(), m, true, true, "replacement").QueueKnown { + t.Fatal("borrowed replaced pod evidence") + } + i.observation.ObservedAt = time.Now().Add(-31 * time.Second) + if i.Observe(t.Context(), m, true, true, l.PodUID).Applied { + t.Fatal("expired process evidence remained current") + } +} + +func processProof(t *testing.T, i *Integration, a Association, ready bool) { + t.Helper() + b, _ := json.Marshal(ProcessObservation{Association: a, ObservedAt: time.Now(), Ready: ready}) + w := httptest.NewRecorder() + i.ServeHTTP(w, httptest.NewRequest("POST", "/payment/observation", strings.NewReader(string(b)))) + if w.Code != 200 { + t.Fatal("process proof rejected", w.Code) + } +} + +func TestProcessObservationCannotBorrowAnotherLaunchOrRenewOldEvidence(t *testing.T) { + i, _, l := integrationFixture(t) + g, e := i.fetch(t.Context(), l) + if e != nil { + t.Fatal(e) + } + for _, mutate := range []func(*ProcessObservation){ + func(o *ProcessObservation) { o.ProcessID = strings.Repeat("e", 64) }, + func(o *ProcessObservation) { o.LaunchID = strings.Repeat("f", 32) }, + func(o *ProcessObservation) { o.ObservedAt = time.Now().Add(-time.Minute) }, + } { + o := ProcessObservation{Association: g.Association, ObservedAt: time.Now(), Ready: true} + mutate(&o) + b, _ := json.Marshal(o) + w := httptest.NewRecorder() + i.ServeHTTP(w, httptest.NewRequest("POST", "/payment/observation", strings.NewReader(string(b)))) + if w.Code != 409 || i.observation != nil { + t.Fatal("stale or foreign process observation accepted", w.Code) + } + } +} + +func TestInitializedPaymentStateMustSurviveReplacement(t *testing.T) { + path := filepath.Join(t.TempDir(), "payments.sqlite") + if checkPaymentState(path, false) != nil { + t.Fatal("fresh installation cannot create its first database") + } + if checkPaymentState(path, true) == nil { + t.Fatal("missing durable state silently recreated") + } + if e := os.WriteFile(path, nil, 0600); e != nil { + t.Fatal(e) + } + if checkPaymentState(path, true) == nil { + t.Fatal("empty durable state accepted") + } + if e := os.WriteFile(path, []byte("retained database"), 0600); e != nil { + t.Fatal(e) + } + if e := checkPaymentState(path, true); e != nil { + t.Fatal(e) + } +} diff --git a/runtime/orchestrator/observation.go b/runtime/orchestrator/observation.go new file mode 100644 index 0000000..14bbc9d --- /dev/null +++ b/runtime/orchestrator/observation.go @@ -0,0 +1,139 @@ +package orchestrator + +import ( + "context" + "io" + "math" + "net/http" + "strings" + "time" + + "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/payment" + "github.com/prometheus/common/expfmt" + "github.com/prometheus/common/model" +) + +func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, ready bool, podUID string) *payment.Observation { + o := &payment.Observation{Generation: m.Payment.Generation, Mode: m.Payment.Mode, PodUID: podUID, Applied: applied, Ready: ready, Handoff: "unverified"} + if !m.Payment.Paid() { + return o + } + i.mu.Lock() + a := i.grant + proof := i.observation + i.mu.Unlock() + if !applied || a == nil || proof == nil || proof.Association != *a || time.Since(proof.ObservedAt) > 30*time.Second || a.PodUID != podUID || a.Epoch != m.Epoch || a.PaymentGeneration != m.Payment.Generation || a.ConfigDigest != m.ConfigDigest || i.checkPod(ctx, a.Launch, m) != nil { + o.Applied = false + o.Ready = false + return o + } + o.Ready = ready && proof.Ready + o.GrantID = a.GrantID + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, "GET", "http://orchestrator.livepeer.svc.cluster.local:8936/metrics", nil) + // Private fixed origin; never use URLs from metrics or reports. + client := *http.DefaultClient + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + resp, e := client.Do(req) + if e != nil { + return o + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return o + } + b, e := io.ReadAll(io.LimitReader(resp.Body, (1<<20)+1)) + if e != nil || len(b) > 1<<20 { + return o + } + parser := expfmt.NewTextParser(model.LegacyValidation) + families, e := parser.TextToMetricFamilies(strings.NewReader(string(b))) + if e != nil { + return o + } + healthy := false + states := map[string]bool{} + var total int64 + var ack, fail float64 + for name, f := range families { + for _, v := range f.Metric { + labels := map[string]string{} + for _, l := range v.Label { + labels[l.GetName()] = l.GetValue() + } + if labels["component"] != "orchestrator" { + continue + } + switch name { + case "livepeer_collector_healthy": + if v.Gauge == nil { + return o + } + if labels["collector"] == "redemptions" && v.GetGauge().GetValue() == 1 { + healthy = true + } + case "livepeer_redemption_queue_tickets": + if v.Gauge == nil { + return o + } + n := v.GetGauge().GetValue() + s := labels["state"] + if states[s] || math.IsNaN(n) || math.IsInf(n, 0) || n < 0 || n > 10000000 || math.Trunc(n) != n { + return o + } + states[s] = true + total += int64(n) + case "livepeer_redemption_transitions_total": + if labels["event"] == "acknowledged" { + ack += v.GetCounter().GetValue() + } + if labels["event"] == "retryable" || labels["event"] == "rejected" { + fail += v.GetCounter().GetValue() + } + } + } + } + for _, s := range []string{"waiting", "eligible", "in_flight", "awaiting_finality", "rejected", "blocked", "unknown"} { + if !states[s] { + return o + } + } + if i.checkPod(ctx, a.Launch, m) != nil { + return o + } + i.mu.Lock() + defer i.mu.Unlock() + if i.grant != a { + return o + } + o.QueueKnown = healthy && len(states) == 7 + o.Unsettled = total + now := time.Now() + if i.metricsGrant == a.GrantID && (ack < i.lastAck || fail < i.lastErr) { + return o + } + if i.metricsGrant != a.GrantID { + i.metricsGrant = a.GrantID + i.lastAck = ack + i.lastErr = fail + i.ackAt = time.Time{} + i.errAt = time.Time{} + return o // A counter baseline cannot date an earlier handoff after restart. + } + if ack > i.lastAck { + i.ackAt = now + } + if fail > i.lastErr { + i.errAt = now + } + i.lastAck = ack + i.lastErr = fail + if !i.errAt.IsZero() && !i.ackAt.After(i.errAt) && now.Sub(i.errAt) < 2*time.Minute { + o.Handoff = "degraded" + } else if !i.ackAt.IsZero() && now.Sub(i.ackAt) < 2*time.Minute { + o.Handoff = "healthy" + } + return o +} diff --git a/runtime/orchestrator/process.go b/runtime/orchestrator/process.go new file mode 100644 index 0000000..f3d1c25 --- /dev/null +++ b/runtime/orchestrator/process.go @@ -0,0 +1,116 @@ +package orchestrator + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "os" + "path/filepath" + "syscall" + "time" + + "github.com/livepeer/control-center/runtime/artifact" + "github.com/livepeer/control-center/runtime/connector" + "github.com/livepeer/control-center/runtime/transport" +) + +func Start(ctx context.Context, args []string) error { + if os.Getpid() != 1 { + return errors.New("orchestrator_requires_private_pid_namespace") + } + process, e := connector.ProcessIdentity() + if e != nil { + return e + } + var nonce [16]byte + if _, e = rand.Read(nonce[:]); e != nil { + return errors.New("orchestrator_launch_identity") + } + launch := Launch{PodName: os.Getenv("POD_NAME"), PodUID: os.Getenv("POD_UID"), LaunchID: hex.EncodeToString(nonce[:]), ProcessID: process} + if !ValidLaunch(launch) { + return errors.New("orchestrator_launch_identity") + } + dir := "/run/payment/private" + if info, e := os.Lstat(dir); e == nil && (info.Mode()&os.ModeSymlink != 0 || !info.IsDir()) { + return errors.New("payment_storage_unavailable") + } else if e != nil && !os.IsNotExist(e) { + return errors.New("payment_storage_unavailable") + } + if e = os.MkdirAll(dir, 0700); e != nil { + return errors.New("payment_storage_unavailable") + } + if os.Chmod(dir, 0700) != nil { + return errors.New("payment_storage_unavailable") + } + for _, f := range []string{"rpc", "headers", "launch.json"} { + if e = os.Remove(filepath.Join(dir, f)); e != nil && !os.IsNotExist(e) { + return errors.New("stale_payment_material") + } + } + client := transport.NewLocal("/management/control.sock") + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + var g Grant + for { + b, _, err := client.Request(ctx, "payment/credentials", launch, 16384) + if err == nil && transport.Decode(b, &g) == nil && g.Launch == launch && g.RPCURL != "" && g.Headers != "" { + break + } + select { + case <-ctx.Done(): + return errors.New("payment_credential_unavailable") + case <-time.After(time.Second): + } + } + if e := checkPaymentState("/data/payments.sqlite", g.RequireState); e != nil { + return e + } + + marker, _ := json.Marshal(g.Association) + if artifact.AtomicWrite(filepath.Join(dir, "rpc"), []byte(g.RPCURL), 0600) != nil || artifact.AtomicWrite(filepath.Join(dir, "headers"), []byte(g.Headers), 0600) != nil || artifact.AtomicWrite(filepath.Join(dir, "launch.json"), marker, 0600) != nil { + return errors.New("payment_credential_write") + } + _ = syscall.Exec("/usr/local/bin/livepeer", append([]string{"/usr/local/bin/livepeer"}, args...), []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/nonexistent"}) + _ = os.Remove(filepath.Join(dir, "rpc")) + _ = os.Remove(filepath.Join(dir, "headers")) + _ = os.Remove(filepath.Join(dir, "launch.json")) + return errors.New("orchestrator_exec_failed") +} + +// Probe runs inside the Node container and proves the marker still names its +// current PID 1. Pod UID alone cannot distinguish container restarts. +func Probe(ctx context.Context) bool { + b, e := os.ReadFile("/run/payment/private/launch.json") + var a Association + process, pe := connector.ProcessIdentity() + if e != nil || pe != nil || len(b) > 16384 || transport.Decode(b, &a) != nil || !ValidLaunch(a.Launch) || a.ProcessID != process { + return false + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:8936/readyz", nil) + client := *http.DefaultClient + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + r, e := client.Do(req) + if e != nil { + return false + } + r.Body.Close() + ready := r.StatusCode == 200 + _, _, e = transport.NewLocal("/management/control.sock").Request(ctx, "payment/observation", ProcessObservation{Association: a, ObservedAt: time.Now(), Ready: ready}, 1024) + return e == nil && ready +} + +func checkPaymentState(path string, required bool) error { + if !required { + return nil + } + info, e := os.Lstat(path) + if e != nil || !info.Mode().IsRegular() || info.Size() == 0 { + return errors.New("payment_state_recovery_required") + } + return nil +} diff --git a/runtime/payment/config.go b/runtime/payment/config.go new file mode 100644 index 0000000..d4df60d --- /dev/null +++ b/runtime/payment/config.go @@ -0,0 +1,176 @@ +// Package payment defines the nonsecret managed Node payment contract. +package payment + +import ( + "errors" + "math/big" + "net/netip" + "net/url" + "regexp" + "strconv" + "strings" + "time" + + "github.com/livepeer/control-center/schema" +) + +type Config struct { + Version int `json:"version"` + Generation int64 `json:"generation"` + CredentialRevision uint64 `json:"credential_revision,omitempty"` + Mode string `json:"mode"` + Network string `json:"network,omitempty"` + ChainID uint64 `json:"chain_id,omitempty"` + Controller string `json:"controller,omitempty"` + Recipient string `json:"recipient,omitempty"` + RPCSecret string `json:"rpc_secret,omitempty"` + RPCGrants []string `json:"rpc_grants,omitempty"` + RedeemerURL string `json:"redeemer_url,omitempty"` + RedeemerGrants []string `json:"redeemer_grants,omitempty"` + WeiPerUSD string `json:"wei_per_usd,omitempty"` + ETHUSDFeed string `json:"eth_usd_feed,omitempty"` + PriceMaxAge string `json:"price_max_age,omitempty"` + TicketFaceValue string `json:"ticket_face_value,omitempty"` + TicketWinProb string `json:"ticket_win_prob,omitempty"` + MaxPendingTickets int `json:"max_pending_tickets,omitempty"` + MaxTicketsPerRecipient int `json:"max_tickets_per_recipient,omitempty"` +} + +func Offchain() Config { return Config{Version: 1, Mode: "offchain"} } +func (c Config) Paid() bool { return c.Mode == "paid" } + +var Address = regexp.MustCompile(`^0x[0-9a-fA-F]{40}$`) +var SecretRef = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$`) + +func validAddress(s string) bool { return Address.MatchString(s) && strings.Trim(s[2:], "0") != "" } + +func (c Config) Validate() error { + bad := errors.New("invalid payment infrastructure settings") + if c.Version != 1 || c.Generation < 0 { + return bad + } + if c.Mode == "offchain" { + d := c + d.Generation = 0 + if d.CredentialRevision != 0 || d.Network != "" || d.Recipient != "" || d.ChainID != 0 || d.Controller != "" || d.RPCSecret != "" || d.RedeemerURL != "" || d.WeiPerUSD != "" || d.ETHUSDFeed != "" || d.TicketFaceValue != "" || d.TicketWinProb != "" || len(d.RPCGrants)+len(d.RedeemerGrants) > 0 || d.PriceMaxAge != "" || d.MaxPendingTickets != 0 || d.MaxTicketsPerRecipient != 0 { + return bad + } + return nil + } + if c.CredentialRevision == 0 || c.ChainID > uint64(^uint64(0)>>1) || !c.Paid() || (c.Network != "arbitrum-one-mainnet" && c.Network != "custom") || c.ChainID == 0 || (c.Network == "arbitrum-one-mainnet" && c.ChainID != 42161) || !validAddress(c.Controller) || !validAddress(c.Recipient) || !SecretRef.MatchString(c.RPCSecret) { + return errors.New("paid mode requires a supported network, chain/controller, recipient, versioned RPC secret, and positive credential_revision") + } + u, e := url.Parse(c.RedeemerURL) + if len(c.RedeemerURL) > 2048 || e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || u.RawPath != "" { + return errors.New("redeemer_url must be HTTPS without credentials, query, or fragment") + } + if e := ValidateEndpoint(c.RedeemerURL, c.RedeemerGrants); e != nil { + return e + } + if (c.WeiPerUSD == "") == (c.ETHUSDFeed == "") { + return errors.New("choose exactly one of wei_per_usd and eth_usd_feed") + } + if c.Network == "arbitrum-one-mainnet" && !strings.EqualFold(c.Controller, "0xD8E8328501E9645d16Cf49539efC04f734606ee4") { + return errors.New("mainnet requires the released Node mainnet controller") + } + if c.WeiPerUSD != "" { + r, ok := new(big.Rat).SetString(c.WeiPerUSD) + if !ok || r.Sign() <= 0 || len(c.WeiPerUSD) > 128 || c.PriceMaxAge != "" { + return errors.New("wei_per_usd must be a positive exact rate without price_max_age") + } + } else { + d, e := time.ParseDuration(c.PriceMaxAge) + if !validAddress(c.ETHUSDFeed) || e != nil || d <= 0 || d > 24*time.Hour { + return errors.New("eth_usd_feed requires an address and price_max_age between zero and 24h") + } + } + max := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) + for _, s := range []string{c.TicketFaceValue, c.TicketWinProb} { + n, ok := new(big.Int).SetString(s, 10) + if !ok || n.Sign() <= 0 || n.Cmp(max) > 0 || n.String() != s { + return bad + } + } + w, _ := new(big.Int).SetString(c.TicketWinProb, 10) + if w.Cmp(max) == 0 || c.MaxPendingTickets < 1 || c.MaxPendingTickets > 1000000 || c.MaxTicketsPerRecipient < 1 || c.MaxTicketsPerRecipient > c.MaxPendingTickets { + return bad + } + for _, grants := range [][]string{c.RPCGrants, c.RedeemerGrants} { + if len(grants) > 16 { + return bad + } + for _, g := range grants { + if _, _, e := Grant(g); e != nil { + return errors.New("payment grants must be explicit non-loopback IP:port destinations") + } + } + } + return nil +} + +// Grant is an explicit IP and TCP port. DNS names and broad networks cannot +// silently expand the Kubernetes exception for a private destination. +func Grant(s string) (netip.Addr, uint16, error) { + a, e := netip.ParseAddrPort(s) + if e != nil || a.Port() == 0 || a.Addr().IsUnspecified() || a.Addr().IsMulticast() || a.Addr().IsLoopback() || a.Addr().Zone() != "" { + return netip.Addr{}, 0, errors.New("payment grants require IP:port") + } + return a.Addr().Unmap(), a.Port(), nil +} + +func (c Config) Compatible(d schema.DefinitionV1) error { + mode := schema.Offchain + if c.Paid() { + mode = schema.Onchain + } + return schema.ValidatePolicy(d, mode) +} + +// Observation never contains credentials or individual ticket data. +type Observation struct { + Generation int64 `json:"generation"` + Mode string `json:"mode"` + PodUID string `json:"pod_uid"` + GrantID string `json:"grant_id,omitempty"` + Applied bool `json:"applied"` + Ready bool `json:"ready"` + QueueKnown bool `json:"queue_known"` + Unsettled int64 `json:"unsettled"` + Handoff string `json:"handoff"` +} + +// ValidateEndpoint rejects destinations the rendered egress policy cannot reach. +// Private DNS addresses still require exact grants at the Node/Kubernetes boundary. +func ValidateEndpoint(raw string, grants []string) error { + bad := errors.New("private or nonstandard-port payment destinations require matching IP:port grants") + u, e := url.Parse(raw) + if e != nil || u.Scheme != "https" || u.Hostname() == "" { + return errors.New("payment destinations require HTTPS") + } + port := uint64(443) + if u.Port() != "" { + port, e = strconv.ParseUint(u.Port(), 10, 16) + if e != nil || port == 0 { + return bad + } + } + ip, e := netip.ParseAddr(u.Hostname()) + if e == nil { + ip = ip.Unmap() + if ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsMulticast() { + return bad + } + if !ip.IsPrivate() && port == 443 { + return nil + } + } else if port == 443 { + return nil + } + for _, g := range grants { + a, p, e := Grant(g) + if e == nil && uint64(p) == port && (ip == netip.Addr{} || a == ip) { + return nil + } + } + return bad +} diff --git a/runtime/payment/config_test.go b/runtime/payment/config_test.go new file mode 100644 index 0000000..a727130 --- /dev/null +++ b/runtime/payment/config_test.go @@ -0,0 +1,27 @@ +package payment + +import ( + "strings" + "testing" +) + +func validConfig() Config { + return Config{Version: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} +} +func TestCompletePaidConfigurationAndExplicitOffchain(t *testing.T) { + if e := validConfig().Validate(); e != nil { + t.Fatal(e) + } + if e := Offchain().Validate(); e != nil { + t.Fatal(e) + } + for name, mutate := range map[string]func(*Config){"missing recipient": func(c *Config) { c.Recipient = "" }, "mode only": func(c *Config) { *c = Config{Version: 1, Mode: "paid"} }, "empty destination query": func(c *Config) { c.RedeemerURL += "?" }, "insecure destination": func(c *Config) { c.RedeemerURL = "http://redeemer.example" }, "inline destination secret": func(c *Config) { c.RedeemerURL = "https://secret@redeemer.example" }, "invalid winning probability": func(c *Config) { c.TicketWinProb = "0" }, "two rate policies": func(c *Config) { c.ETHUSDFeed = c.Controller; c.PriceMaxAge = "1h" }, "broad network": func(c *Config) { c.RedeemerGrants = []string{"10.0.0.0/8"} }, "wrong chain": func(c *Config) { c.Network = "arbitrum-one-mainnet" }, "offchain retains payment inputs": func(c *Config) { c.Mode = "offchain" }, "overflow": func(c *Config) { c.ChainID = ^uint64(0) }} { + t.Run(name, func(t *testing.T) { + c := validConfig() + mutate(&c) + if c.Validate() == nil { + t.Fatal("accepted invalid payment configuration") + } + }) + } +} diff --git a/runtime/services/Dockerfile.node b/runtime/services/Dockerfile.node new file mode 100644 index 0000000..f16ffd5 --- /dev/null +++ b/runtime/services/Dockerfile.node @@ -0,0 +1,8 @@ +# syntax=docker/dockerfile:1.7 +ARG NODE_IMAGE +ARG RUNTIME_IMAGE +FROM ${RUNTIME_IMAGE} AS runtime +FROM ${NODE_IMAGE} +COPY --from=runtime /usr/local/bin/livepeer-runtime /usr/local/bin/livepeer-runtime +USER 65532:65532 +ENTRYPOINT ["/usr/local/bin/livepeer"] diff --git a/runtime/services/Dockerfile.node.dockerignore b/runtime/services/Dockerfile.node.dockerignore new file mode 100644 index 0000000..a40fd48 --- /dev/null +++ b/runtime/services/Dockerfile.node.dockerignore @@ -0,0 +1,2 @@ +# No repository source or installed Runtime data is needed by this image. +** diff --git a/runtime/transport/client.go b/runtime/transport/client.go index 1fad70c..0d38eab 100644 --- a/runtime/transport/client.go +++ b/runtime/transport/client.go @@ -70,7 +70,7 @@ func (c *Control) Request(ctx context.Context, endpoint string, payload any, lim if c.ConfigURL != c.approvedURL || c.Base != c.approvedBase { return nil, nil, errors.New("control_origin_changed") } - if endpoint != "config" && endpoint != "status" && endpoint != "removal-ack" && endpoint != "tunnel/connector-token" && !appReportPath.MatchString(endpoint) { + if endpoint != "config" && endpoint != "status" && endpoint != "removal-ack" && endpoint != "tunnel/connector-token" && endpoint != "payment/credentials" && !appReportPath.MatchString(endpoint) { return nil, nil, errors.New("control_endpoint") } token, err := os.ReadFile(c.TokenFile) @@ -144,6 +144,11 @@ func ReadMetadata(b []byte) (contract.Metadata, error) { if len(b) > 16384 || Decode(b, &m) != nil || !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(m.NodeID) || m.Generation < 1 || m.CredentialVersion < 1 || !epochPattern.MatchString(m.Epoch) || m.BundleFormat != contract.BundleFormat { return m, errors.New("metadata_invalid") } + if m.Payment.Version != 0 { + if m.Payment.Validate() != nil { + return m, errors.New("metadata_payment_invalid") + } + } return m, nil } diff --git a/runtime/transport/client_test.go b/runtime/transport/client_test.go index 6c465a0..701a027 100644 --- a/runtime/transport/client_test.go +++ b/runtime/transport/client_test.go @@ -37,6 +37,9 @@ func TestControlOriginsCredentialsAndRedirects(t *testing.T) { if _, _, err = c.Request(context.Background(), "config", nil, 1024); !IsStatus(err, 302) || calls != 0 { t.Fatal("redirect leaked request", err, calls) } + if _, _, err = c.Request(context.Background(), "payment/credentials", map[string]string{"pod_uid": "current"}, 1024); !IsStatus(err, 302) || calls != 0 { + t.Fatal("payment delivery was refused or redirected", err, calls) + } c.ConfigURL = receiver.URL if _, _, err = c.Request(context.Background(), "config", nil, 1024); err == nil || calls != 0 { t.Fatal("origin mutated") diff --git a/schema/validate.go b/schema/validate.go index eb1f496..d9d10aa 100644 --- a/schema/validate.go +++ b/schema/validate.go @@ -165,14 +165,14 @@ func refDigest(r reference.Reference) string { func ValidatePolicy(d DefinitionV1, mode PaymentMode) error { e := new(ValidationError) if mode != Offchain && mode != Onchain { - e.add("price", "Unknown registry payment mode.") + e.add("price", "Unknown target Node payment mode.") } else if mode == Onchain && len(d.Apps) == 0 && d.Price.Amount == "0" { - e.add("price.amount", "Onchain publications and new bindings require an explicit positive price.") + e.add("price.amount", "Paid Node assignments require an explicit positive price.") } if mode == Onchain { for n, o := range d.Apps { if o.Price.Amount == "0" { - e.add(fmt.Sprintf("apps[%d].price.amount", n), "Onchain apps require a positive price.") + e.add(fmt.Sprintf("apps[%d].price.amount", n), "Paid Node apps require a positive price.") } } } diff --git a/ui/src/catalog.tsx b/ui/src/catalog.tsx index 48ddacd..b8e7514 100644 --- a/ui/src/catalog.tsx +++ b/ui/src/catalog.tsx @@ -7,12 +7,11 @@ type Lifecycle = { version: number; retired_at: string | null; retired_by: strin type Summary = Ref & { revision: number; app_version: string; lifecycle: Lifecycle } type App = { name: string; head: Summary; revision_count: number; active_revision_count: number } type Revision = Summary & { name: string; source_toml: string; definition: unknown; published_at: string; published_by: string } -type Preview = { definition: unknown; digest: string; payment_mode: string } +type Preview = { definition: unknown; digest: string } const starter = 'name = "my-app"\nschema_version = 1\n\n[container]\nimage = "REPOSITORY@sha256:DIGEST"\n\n[resources.limits]\nmemory = "1GiB"\n\n[http]\nport = 8080\n' export function Catalog({ session, authorityFailure }: { session: Session; authorityFailure: (error: APIError) => void }) { const [apps, setApps] = useState([]) - const [mode, setMode] = useState('offchain') const [nextApp, setNextApp] = useState(null) const [selectedApp, setSelectedApp] = useState(null) const [history, setHistory] = useState([]) @@ -56,14 +55,14 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho } } function loadApps(after?: string) { - void run('list', signal => api<{ apps: App[]; payment_mode: string; next_after_name: string | null }>(session, '/api/admin/apps' + (after ? `?after_name=${encodeURIComponent(after)}` : ''), { signal }), data => { + void run('list', signal => api<{ apps: App[]; next_after_name: string | null }>(session, '/api/admin/apps' + (after ? `?after_name=${encodeURIComponent(after)}` : ''), { signal }), data => { setApps(old => after ? [...old, ...data.apps.filter(a => !old.some(b => b.name === a.name))] : data.apps) - setMode(data.payment_mode); setNextApp(data.next_after_name) + setNextApp(data.next_after_name) }) } function loadHistory(name: string, before?: number, rebase = false) { - void run('history', signal => api<{ app: App; revisions: Summary[]; next_before_revision: number | null; payment_mode: string }>(session, `/api/admin/apps/${encodeURIComponent(name)}` + (before ? `?before_revision=${before}` : ''), { signal }), data => { - setSelectedApp(data.app); setHistory(old => before ? [...old, ...data.revisions] : data.revisions); setNextRevision(data.next_before_revision); setMode(data.payment_mode) + void run('history', signal => api<{ app: App; revisions: Summary[]; next_before_revision: number | null }>(session, `/api/admin/apps/${encodeURIComponent(name)}` + (before ? `?before_revision=${before}` : ''), { signal }), data => { + setSelectedApp(data.app); setHistory(old => before ? [...old, ...data.revisions] : data.revisions); setNextRevision(data.next_before_revision) if (rebase) { setExpectedHead(data.app.head.revision_id); setPreview(null); setConflict(false); setMessage('Publication base refreshed. Validate the draft again.') } }) } @@ -89,7 +88,7 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho } function validate() { const version = draft.current; setMessage(''); setProblem(''); setFields([]); setPreview(null) - void run('validation', signal => api(session, '/api/admin/apps/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal, body: JSON.stringify({ source_toml: source }) }), data => { if (version === draft.current) { setPreview(data); setMode(data.payment_mode) } }) + void run('validation', signal => api(session, '/api/admin/apps/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal, body: JSON.stringify({ source_toml: source }) }), data => { if (version === draft.current) { setPreview(data) } }) } function publish() { if (changing.current || !preview || (!creating && (!selectedApp || !expectedHead))) return @@ -111,7 +110,7 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho }) } return
-

App catalog

Registry pricing policy: {mode}. Revisions are immutable.

+

App catalog

Prices belong to each immutable app revision. Payment activation is configured per machine.

{problem &&
{problem}{fields.length > 0 &&
    {fields.map((f, i) =>
  • {f.path}: {f.message}
  • )}
}
} {message &&
{message}
}
    {apps.map(app =>
  • Revision {app.head.revision} · version {app.head.app_version || '(unversioned)'} · {app.active_revision_count} active
  • )}
diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index a559551..e7e5ea6 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -7,10 +7,11 @@ type Probe = { observed_at: string; due_at: string; expires_at: string; success: type Instance = { revision_id: string; generation: number; activation_generation: number; instance_id: string; pod_uid?: string; runner_id?: string; app_id?: string; phase: string; ready: boolean; registered: boolean; capacity: number; sessions: number; reason?: string; workload_reason?: string; deadline?: string; withdrawal_id?: string; drain_expired_at?: string; forced?: boolean; removal_published_at?: string; terminated_at?: string; registration_gone?: boolean; node_observed_at?: string; node_expires_at?: string; accepted_sequence?: number; startup_deadline?: string; probe?: Probe } type AssignmentObservation = { revision_id: string; generation: number; activation_generation: number; reason?: string; instances: number; ready: number; registered: number; cleanup_pending: number; node_expires_at?: string; probe_expires_at?: string } type Apps = { desired_generation: number; desired_digest?: string; staged?: Stage; published?: Stage; applied?: Stage; reason?: string; instances: Instance[]; assignments?: AssignmentObservation[]; instances_total?: number; instances_omitted?: number; owner_recreated_at?: string } -type Component = { observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } +type PaymentEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; queue_known: boolean; unsettled: number; handoff: string } +type Component = { payment?: PaymentEvidence; observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } type Assignment = { revision_id: string; digest: string; name: string; version: string; revision: number; generation: number; activation_generation: number; desired: string; replicas: number; start_allowed: boolean; completed_at: string | null; failure?: string; health: { type: string; interval: string; timeout: string; failure_threshold: number } } type Membership = { state: string; provenance_current: boolean; queried_at?: string; observed_at?: string; expires_at?: string } -export type MachineObservation = { node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } +export type MachineObservation = { payment?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number; recovery_required: boolean }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } export function machineStatusSummary(machine: { terminal?: boolean; report_state?: string; last_config_fetch_at?: string | null }) { const labels: Record = { observed: 'Runtime observed', stale: 'Status stale', clock_uncertain: 'Clock uncertain' } @@ -18,8 +19,8 @@ export function machineStatusSummary(machine: { terminal?: boolean; report_state } const reasons: Record = { - sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', - resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', + payment_not_ready: 'Paid Node is not ready; inspect credential delivery, retained payment state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', + payment_pending: 'Waiting for the target payment configuration', payment_incompatible: 'App price is incompatible with the target payment mode', payment_drain_pending: 'Waiting for payment settlement', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', } function reason(code?: string) { return code ? reasons[code] || code.replaceAll('_', ' ') : '' } function date(value?: string | null) { return value && Date.parse(value) > 0 ? new Date(value).toLocaleString() : 'Unobserved' } @@ -82,6 +83,15 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: {problem &&
{problem}
} {!view && !problem &&

Loading observed state…

} {view && <> + {view.payment &&
+

Payment operation

+

Desired: {view.payment.desired.mode} · generation {view.payment.desired.generation}. Delivered generation: {view.payment.delivered_generation}.

+ {view.payment.desired.recipient &&

Recipient: {view.payment.desired.recipient} · {view.payment.desired.network}

} +

Configuration: {fresh(runtime) && runtime?.payment?.applied ? `applied generation ${runtime.payment.generation}` : 'pending or unobserved'}. Local paid admission: {fresh(runtime) && runtime?.payment?.mode === 'paid' && runtime.payment.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.payment?.handoff || 'unverified' : 'unverified'}.

+ {fresh(runtime) && runtime?.payment?.mode === 'offchain' &&

Effective service is free; catalog registration quotes are retained.

} + {view.payment.recovery_required &&

Payment recovery required. Retained tickets have not been confirmed drained.

} +
} +

{reason(view.lifecycle)} · rollout generation {view.rollout_generation}. External app reachability: unverified. Configured checks observe the private app endpoint.

{view.delivery_reason &&
{reason(view.delivery_reason)}. Retained app input keeps its original identity.
} {runtime?.apps_error &&
App input validation: {reason(runtime.apps_error)}. Management status is reported separately.
} diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index bd9419c..1766db1 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -227,3 +227,19 @@ test('expired inventory preserves its unverified source-version explanation', as await page.clock.fastForward(2000) await expect(page.getByText('Retained inventory has no confirmation for the current source version', { exact: false })).toBeVisible() }) + +test('paid readiness stays separate from handoff and retirement recovery', async ({ page }) => { + await page.clock.install() + const state = await setup(page, false) + state.view.payment = { desired: { mode: 'paid', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } + state.view.components[0].payment = { generation: 3, mode: 'paid', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } + await page.clock.fastForward(5100) + await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Local paid admission: ready') + await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Remote handoff: degraded') + state.view.payment.recovery_required = true + await page.clock.fastForward(5100) + await expect(page.getByRole('alert')).toContainText('Payment recovery required') + state.view.components[0].fresh = false + await page.clock.fastForward(5100) + await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Remote handoff: unverified') +}) From 3d4ea2bdd0300abe65473dcf168538f6580728e1 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 01:05:49 -0800 Subject: [PATCH 02/15] Drain and replace Node across management credential lifetimes --- .../machineconfig/payment_test.go | 10 ++++++ .../controlplane/machineconfig/runtime.go | 2 +- .../templates/system/node/orchestrator.yaml | 2 ++ runtime/lib/credentials.sh | 32 ++++++++++++++++--- runtime/tests/test_credentials.py | 12 +++++++ 5 files changed, 52 insertions(+), 6 deletions(-) diff --git a/api/internal/controlplane/machineconfig/payment_test.go b/api/internal/controlplane/machineconfig/payment_test.go index ce72b59..2b22dc8 100644 --- a/api/internal/controlplane/machineconfig/payment_test.go +++ b/api/internal/controlplane/machineconfig/payment_test.go @@ -76,6 +76,16 @@ func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { t.Fatal("missing private endpoint policy") } original := Digest(m) + refreshed := m + refreshed.CredentialVersion++ + if Digest(refreshed) == original { + t.Fatal("management refresh did not schedule Node drain and replacement") + } + refreshed = m + refreshed.Epoch = "22222222-2222-4222-8222-222222222222" + if Digest(refreshed) == original { + t.Fatal("re-enrollment reused a previous lifetime's Node workload") + } m.Payment.Generation++ m.Payment.CredentialRevision++ if Digest(m) == original { diff --git a/api/internal/controlplane/machineconfig/runtime.go b/api/internal/controlplane/machineconfig/runtime.go index 3fa2481..e464387 100644 --- a/api/internal/controlplane/machineconfig/runtime.go +++ b/api/internal/controlplane/machineconfig/runtime.go @@ -27,7 +27,7 @@ func templateValues(m Desired) *strings.Replacer { if strings.HasPrefix(m.ControlAPIURL, "http://") { mode = "development-http" } - return strings.NewReplacer("@RUNTIME_IMAGE@", m.RuntimeImage, "@CONTROL_TRANSPORT@", mode, "@NODE_ID@", m.NodeID, "@INSTALL_DIR@", m.InstallDir, "@K3S_VERSION@", m.K3sVersion, "@SERVICE_URL@", service, "@PROXY_URL_TEMPLATE@", proxy) + return strings.NewReplacer("@RUNTIME_IMAGE@", m.RuntimeImage, "@CONTROL_TRANSPORT@", mode, "@NODE_ID@", m.NodeID, "@ENROLLMENT_EPOCH@", m.Epoch, "@MANAGEMENT_CREDENTIAL_VERSION@", fmt.Sprint(m.CredentialVersion), "@INSTALL_DIR@", m.InstallDir, "@K3S_VERSION@", m.K3sVersion, "@SERVICE_URL@", service, "@PROXY_URL_TEMPLATE@", proxy) } func orchestratorConfiguration(m Desired) string { if m.State.HeldOrchestrator != "" { diff --git a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml index 5210875..0c3fccc 100644 --- a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml +++ b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml @@ -86,6 +86,8 @@ spec: template: metadata: annotations: + livepeer.io/enrollment-epoch: '@ENROLLMENT_EPOCH@' + livepeer.io/credential-version: '@MANAGEMENT_CREDENTIAL_VERSION@' livepeer.io/config-sha256: '@ORCHESTRATOR_DIGEST@' labels: app: orchestrator diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index 792581c..7616e47 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -5,9 +5,22 @@ control_transport() { if [[ ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} == 1 ]]; then printf 'development-http'; else printf 'https'; fi } +api_url() { + local api=${LIVEPEER_API_URL:-https://controlcenter-api.livepeer.live} + api=${api%/} + [[ "$api" =~ ^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'invalid LIVEPEER_API_URL: expected an API base URL' + printf '%s' "$api" +} + runtime_image() { - RUNTIME_IMAGE=${LIVEPEER_RUNTIME_IMAGE:-} - if [[ -z "$RUNTIME_IMAGE" && -f "$INSTALL_DIR/state/runtime-image" ]]; then RUNTIME_IMAGE=$(cat "$INSTALL_DIR/state/runtime-image"); fi + RUNTIME_IMAGE='' + if [[ ${LIVEPEER_RUNTIME_IMAGE+x} ]]; then + RUNTIME_IMAGE=$LIVEPEER_RUNTIME_IMAGE + elif [[ -f "$INSTALL_DIR/state/runtime-image" ]]; then + RUNTIME_IMAGE=$(cat "$INSTALL_DIR/state/runtime-image") + elif [[ -n ${SCRIPT_DIR:-} && -f "$SCRIPT_DIR/release-runtime-image" ]]; then + RUNTIME_IMAGE=$(cat "$SCRIPT_DIR/release-runtime-image") + fi [[ "$RUNTIME_IMAGE" =~ ^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$ ]] || die 'set LIVEPEER_RUNTIME_IMAGE to a built Go Runtime image pinned by digest' } @@ -70,6 +83,14 @@ stop_credential_consumers() { kube -n flux-system scale deployment/livepeer-app-reconciler --replicas=0 fi kube -n flux-system delete deployment/livepeer-tunnel --ignore-not-found --wait=true + if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then + # Prior app cleanup was verified before this transition. Do not let a + # retained Node from that lifetime survive issuance of its replacement. + if kube -n livepeer get deployment/orchestrator >/dev/null 2>&1; then + kube -n livepeer scale deployment/orchestrator --replicas=0 + fi + kube -n livepeer wait pod -l app=orchestrator --for=delete --timeout=120s + fi # Replica count alone does not prove old HTTP-speaking processes terminated. kube -n flux-system wait pod -l app=livepeer-http-source --for=delete --timeout=120s kube -n flux-system wait pod -l app=livepeer-app-reconciler --for=delete --timeout=120s @@ -81,10 +102,10 @@ transition_credentials() { managed_installation || die 'credential transition requires an initialized installation' [[ -s "$INSTALL_DIR/credentials/runner-bootstrap.secret" ]] || die 'restore the runner bootstrap credential before changing credentials' runtime_image - [[ -n "$ENROLLMENT_TOKEN" ]] || die 'credential transition requires a fresh owner enrollment JWT' + [[ -n "$ENROLLMENT_TOKEN" ]] || die 'credential transition requires LIVEPEER_ENROLLMENT_TOKEN with a fresh owner enrollment JWT' [[ "$ENROLLMENT_TOKEN" =~ ^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$ ]] || die 'invalid enrollment JWT' - api=${LIVEPEER_API_URL:-}; api=${api%/} - [[ "$api" =~ ^https://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'set LIVEPEER_API_URL to the verified HTTPS API' + api=$(api_url) + [[ "$api" == https://* ]] || die 'set LIVEPEER_API_URL to the verified HTTPS API' NODE_ID=$(cat "$INSTALL_DIR/credentials/node-id") [[ "$NODE_ID" =~ ^lp-[a-f0-9]{16}$ ]] || die 'invalid saved machine ID' fingerprint=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum); fingerprint=${fingerprint:0:64} @@ -136,6 +157,7 @@ transition_credentials() { --config <(printf 'header = "Authorization: Bearer %s"\n' "$ENROLLMENT_TOKEN") \ --data-binary "$request" "$api/v1/nodes/register") || die 'HTTPS re-enrollment failed; transition remains suspended' fi + ENROLLMENT_TOKEN='' status=${response##*$'\n'}; [[ "$status" == 200 ]] || die 'credential transition did not return HTTP 200; resume with the same operation' response=${response%$'\n'*} [[ $(jq -r '.node_id' <<< "$response") == "$NODE_ID" ]] || die 'credential transition returned a different machine' diff --git a/runtime/tests/test_credentials.py b/runtime/tests/test_credentials.py index c9ed156..1ec2165 100644 --- a/runtime/tests/test_credentials.py +++ b/runtime/tests/test_credentials.py @@ -154,6 +154,18 @@ def test_reenrollment_resume_rejects_a_different_issued_identity(self): self.assertEqual((self.root / 'credentials/identity.json').read_bytes(), identity) self.assertTrue((self.root / 'state/credential-transition.json').exists()) + def test_reenrollment_stops_prior_node_before_issuing_credentials(self): + result = self.transition(mode='reenroll') + self.assertEqual(result.returncode, 0, result.stderr) + steps = (self.root / 'steps').read_text().splitlines() + stopped = next(i for i, x in enumerate(steps) if 'wait pod -l app=orchestrator' in x) + self.assertLess(stopped, steps.index('refresh')) + + def test_refresh_keeps_node_for_authoritative_managed_drain(self): + result = self.transition() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn('scale deployment/orchestrator', (self.root / 'steps').read_text()) + if __name__ == '__main__': unittest.main() From 9189d369bca8753dc40e36aa1599fb2e9bfd9ca1 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 01:16:09 -0800 Subject: [PATCH 03/15] Keep payment lifecycle change scoped to Node fencing --- runtime/lib/credentials.sh | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index 7616e47..c357e45 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -5,22 +5,9 @@ control_transport() { if [[ ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} == 1 ]]; then printf 'development-http'; else printf 'https'; fi } -api_url() { - local api=${LIVEPEER_API_URL:-https://controlcenter-api.livepeer.live} - api=${api%/} - [[ "$api" =~ ^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'invalid LIVEPEER_API_URL: expected an API base URL' - printf '%s' "$api" -} - runtime_image() { - RUNTIME_IMAGE='' - if [[ ${LIVEPEER_RUNTIME_IMAGE+x} ]]; then - RUNTIME_IMAGE=$LIVEPEER_RUNTIME_IMAGE - elif [[ -f "$INSTALL_DIR/state/runtime-image" ]]; then - RUNTIME_IMAGE=$(cat "$INSTALL_DIR/state/runtime-image") - elif [[ -n ${SCRIPT_DIR:-} && -f "$SCRIPT_DIR/release-runtime-image" ]]; then - RUNTIME_IMAGE=$(cat "$SCRIPT_DIR/release-runtime-image") - fi + RUNTIME_IMAGE=${LIVEPEER_RUNTIME_IMAGE:-} + if [[ -z "$RUNTIME_IMAGE" && -f "$INSTALL_DIR/state/runtime-image" ]]; then RUNTIME_IMAGE=$(cat "$INSTALL_DIR/state/runtime-image"); fi [[ "$RUNTIME_IMAGE" =~ ^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$ ]] || die 'set LIVEPEER_RUNTIME_IMAGE to a built Go Runtime image pinned by digest' } @@ -102,10 +89,10 @@ transition_credentials() { managed_installation || die 'credential transition requires an initialized installation' [[ -s "$INSTALL_DIR/credentials/runner-bootstrap.secret" ]] || die 'restore the runner bootstrap credential before changing credentials' runtime_image - [[ -n "$ENROLLMENT_TOKEN" ]] || die 'credential transition requires LIVEPEER_ENROLLMENT_TOKEN with a fresh owner enrollment JWT' + [[ -n "$ENROLLMENT_TOKEN" ]] || die 'credential transition requires a fresh owner enrollment JWT' [[ "$ENROLLMENT_TOKEN" =~ ^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$ ]] || die 'invalid enrollment JWT' - api=$(api_url) - [[ "$api" == https://* ]] || die 'set LIVEPEER_API_URL to the verified HTTPS API' + api=${LIVEPEER_API_URL:-}; api=${api%/} + [[ "$api" =~ ^https://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'set LIVEPEER_API_URL to the verified HTTPS API' NODE_ID=$(cat "$INSTALL_DIR/credentials/node-id") [[ "$NODE_ID" =~ ^lp-[a-f0-9]{16}$ ]] || die 'invalid saved machine ID' fingerprint=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum); fingerprint=${fingerprint:0:64} @@ -157,7 +144,6 @@ transition_credentials() { --config <(printf 'header = "Authorization: Bearer %s"\n' "$ENROLLMENT_TOKEN") \ --data-binary "$request" "$api/v1/nodes/register") || die 'HTTPS re-enrollment failed; transition remains suspended' fi - ENROLLMENT_TOKEN='' status=${response##*$'\n'}; [[ "$status" == 200 ]] || die 'credential transition did not return HTTP 200; resume with the same operation' response=${response%$'\n'*} [[ $(jq -r '.node_id' <<< "$response") == "$NODE_ID" ]] || die 'credential transition returned a different machine' From 8389b94e1481f28e1cb764fa23e3fd37825e8e6c Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 01:29:14 -0800 Subject: [PATCH 04/15] Recognize deleted tunnel tombstones during recovery cleanup --- .../controlplane/tunnel/cloudflare.go | 8 ++++ .../tunnel/cloudflare_deletion_test.go | 41 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 api/internal/controlplane/tunnel/cloudflare_deletion_test.go diff --git a/api/internal/controlplane/tunnel/cloudflare.go b/api/internal/controlplane/tunnel/cloudflare.go index 5099ff0..5e76561 100644 --- a/api/internal/controlplane/tunnel/cloudflare.go +++ b/api/internal/controlplane/tunnel/cloudflare.go @@ -179,6 +179,14 @@ func (c *cloudflareHTTP) find(ctx context.Context, r CFResource, ownedOnly bool) if e != nil && !missing { return nil, e } + // Deleted tunnels retain an ID/name tombstone but lose config_src. + // Confirm its identity before treating that provider evidence as absence. + if !missing && r.Kind == "tunnel" && o.DeletedAt != nil && !o.DeletedAt.IsZero() { + if o.ID != r.ID || o.Name != r.Name { + return nil, ErrResourceConflict + } + missing = true + } if !missing && (!resourceOwned(r, o) || o.ID != r.ID) { return nil, ErrResourceConflict } diff --git a/api/internal/controlplane/tunnel/cloudflare_deletion_test.go b/api/internal/controlplane/tunnel/cloudflare_deletion_test.go new file mode 100644 index 0000000..bbd6778 --- /dev/null +++ b/api/internal/controlplane/tunnel/cloudflare_deletion_test.go @@ -0,0 +1,41 @@ +package tunnel + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestDeletedTunnelTombstoneAllowsEnrollmentRecovery(t *testing.T) { + now := time.Now().UTC() + want := CFResource{Kind: "tunnel", ID: "old", Name: "owned-epoch-tunnel", Watch: true} + object := cfObject{ID: want.ID, Name: want.Name, DeletedAt: &now} + var listed []cfObject + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var result any = object + if r.URL.Query().Get("is_deleted") == "false" { + result = listed + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "result": result}) + })) + defer server.Close() + provider := &cloudflareHTTP{client: server.Client(), base: server.URL} + if found, err := provider.FindOwned(t.Context(), want); err != nil || len(found) != 0 { + t.Fatal("provider tombstone blocked predecessor cleanup", found, err) + } + listed = []cfObject{{ID: "late", Name: want.Name, ConfigSrc: "cloudflare"}} + if found, err := provider.FindOwned(t.Context(), want); err != nil || len(found) != 1 || found[0].ID != "late" { + t.Fatal("tombstone hid a late active resource", found, err) + } + object.Name = "foreign" + if _, err := provider.FindOwned(t.Context(), want); !errors.Is(err, ErrResourceConflict) { + t.Fatal("foreign tombstone accepted", err) + } + object.Name, object.DeletedAt = want.Name, nil + if _, err := provider.FindOwned(t.Context(), want); !errors.Is(err, ErrResourceConflict) { + t.Fatal("active tunnel lost ownership protection", err) + } +} From 4abfc0fbb2a795c7f8a0b9c45dab92c760311855 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 02:21:33 -0800 Subject: [PATCH 05/15] Record bounded settlement and fresh-install recovery evidence --- docs/acceptance/119-managed-payments.json | 288 ++++++++++++++++++++++ docs/acceptance/119-managed-payments.md | 119 +++++++++ docs/paid-operation.md | 5 + 3 files changed, 412 insertions(+) create mode 100644 docs/acceptance/119-managed-payments.json create mode 100644 docs/acceptance/119-managed-payments.md diff --git a/docs/acceptance/119-managed-payments.json b/docs/acceptance/119-managed-payments.json new file mode 100644 index 0000000..d4440a9 --- /dev/null +++ b/docs/acceptance/119-managed-payments.json @@ -0,0 +1,288 @@ +{ + "version": 1, + "run": "cc-e2e-1112071043-bcbd", + "date": "2026-11-12", + "scope": "fresh installations", + "implementation_revision": "fa744f162a4aea818a6031ada21ed10ee49f351a", + "source_tree_sha256": "88e91434d846bf03a328ec75dff4f76322dadd6eccb49da9c03350038eb98b36", + "api_binary_sha256": "2373492e60bf6e6ddd1e99a6878e72deba1faaa0c5de1d6e98587dcc1f7b1c61", + "management_runtime_binary_sha256": "3dcb8489a68907629de585dad25a5cb11cb13b38c62236954922ebf25592deef", + "functional_node_source": { + "mode": "working-tree", + "revision": "0ee73c000bed553f5a02e40c972c1b5bd2d0ba80", + "sha256": "b9e54ae392831706c3ce85baa9cd12ecd227d90e807376bcb74262c767f3bd90" + }, + "functional_images": { + "runtime": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", + "connector": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/connector@sha256:4174086c856a6b85a42be12cd09becf37e75ee8ba54d72949f3a141235156226", + "node": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/node@sha256:a3dab72b2f364f88bc64bcc954e1ede32d43bcb7c6c288165c25a71740e2b57a", + "echo": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/echo@sha256:b20ba6e917c81842f707a3fa4a581c073ceff7c22782b7ec993abe5c27d7863b" + }, + "landed_wrapper_build": { + "node_commit": "3533951e66584531a54a771d21c1388873439099", + "node_image": "ghcr.io/livepeer/node@sha256:8c13bbd6abf8d7879c4999ea10d537996a6d54b330cfd5303ebf03b3e4782be9", + "runtime_image": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", + "wrapper_image": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/managed-node@sha256:cc0a711c242df53a1d621082f11876cdad3b04983afe0e87c89fa7529ac28fb9", + "actual_dockerfile_built": true, + "nonroot": true + }, + "catalog": [ + { + "name": "paid-echo-persistent", + "revision_id": "9a96a95f-ff0d-42b3-8ebb-5c6893ba4adb", + "digest": "sha256:2253e9cf61444a3da745db4ca77d3c973378b88f43d50bebfaa357ef79597d05", + "price": { + "amount": "0.001", + "currency": "usd", + "unit": "hour" + } + }, + { + "name": "paid-echo-fixed", + "revision_id": "e3b5ceb6-cb7f-4e40-b1c6-469f06d2901f", + "digest": "sha256:c8482a7f32e1cd6bd56e7a48e5ffc6fc612dc660a34226a5ec51a789d6fa4668", + "price": { + "amount": "0.001", + "currency": "usd", + "unit": "fixed" + } + } + ], + "workers": { + "count": 2, + "type": "e2-standard-4", + "k3s": "v1.37.2+k3s1", + "settings": [ + "private RPC and redemption", + "public RPC and redemption" + ] + }, + "checks": { + "routing-evidence": [ + { + "check": "orchestrator_exact_private_endpoint", + "role": "node-a", + "port": 41143, + "reachable": true + }, + { + "check": "orchestrator_exact_private_endpoint", + "role": "node-a", + "port": 41144, + "reachable": true + }, + { + "check": "all_app_workloads_isolated_from_private_payment_endpoints", + "role": "node-a", + "workloads": 3 + }, + { + "check": "orchestrator_exact_private_endpoint", + "role": "node-b", + "port": 41143, + "reachable": false + }, + { + "check": "orchestrator_exact_private_endpoint", + "role": "node-b", + "port": 41144, + "reachable": false + }, + { + "check": "all_app_workloads_isolated_from_private_payment_endpoints", + "role": "node-b", + "workloads": 3 + }, + { + "check": "unrelated_private_destination_blocked", + "role": "node-a", + "host_baseline_reachable": true + }, + { + "check": "unrelated_private_destination_blocked", + "role": "node-b", + "host_baseline_reachable": true + }, + { + "check": "unready_service_keeps_management_routing", + "same_pod": true, + "protected_discovery_status": 200, + "protected_stop_status": 404, + "sibling_payment_ready": true + }, + { + "check": "private_rpc_outage_recovered", + "same_pod": true + } + ], + "retained-outage-evidence": { + "paid_session_survived_rpc_readiness_loss": true, + "protected_diagnostics_reachable": true, + "retained_session_stop_succeeded_while_unready": true + }, + "disable-rollback-evidence": [ + { + "check": "disable_blocked_by_real_queued_ticket", + "paid_workload_retained": true, + "submission_grant_retained": true, + "sibling_unchanged": true + }, + { + "check": "rollback_reuses_immutable_inputs_with_new_grant", + "payment_generation": 4, + "retained_database_owner_only": true, + "sibling_unchanged": true + } + ], + "forced-recovery-evidence": [ + { + "check": "forced_retirement_with_queued_tickets", + "submission_grants_revoked_immediately": true, + "recovery_required": true, + "payment_drained": false, + "database_preserved": true, + "unhanded_tickets": 1 + }, + { + "check": "reenrollment_recovers_retained_payment_state", + "new_enrollment": true, + "recipient_pin_preserved": true, + "tickets_preserved": true, + "new_credentials_authorized": true, + "recovery_flag_preserved": true + } + ], + "management-refresh-evidence": { + "management_credential_version_advanced": true, + "node_replaced_after_managed_drain": true, + "replacement_grant_observed": true, + "older_submission_grants_revoked": true, + "payment_storage_preserved": true + }, + "backpressure-evidence": { + "queue_limit": 2, + "actual_unsettled": 2, + "paid_mode_retained": true, + "local_admission_not_ready": true + }, + "lost-ack-evidence": { + "durable_redeemer_acceptances": 9, + "acknowledgements_lost": 6, + "remote_health_degraded_then_healthy": true + }, + "ordinary-retirement-evidence": { + "ordinary_removal_blocked_by_actual_unsettled_tickets": true, + "paid_workload_retained": true, + "submission_grants_retained": true, + "completion_not_acknowledged": true + }, + "credential-log-scan-evidence": { + "sources_scanned": 8, + "known_credentials_absent": true, + "affected_sources": [] + }, + "settlement-restart-evidence": { + "transaction_hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780", + "same_signed_bytes_after_restart": true, + "same_nonce_after_restart": true, + "duplicate_transaction_identities": false + }, + "settlement-final-evidence": { + "transactions": [ + { + "hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780", + "nonce": "0", + "phase": "confirmed", + "raw_sha256": "0c6bb19ee1b6db7a9633f64884e71085e825521247ef81fa23da444671d35c28", + "acknowledged": true + } + ], + "settled": 1, + "tickets": 6 + } + }, + "settlement": { + "budget": { + "approved_maximum_usd": "0.40", + "ticket_liability_usd": "0.20", + "gas_usd": "0.20", + "internal_max_authorizations": 9, + "per_ticket_usd": "0.02", + "configured_face_value_wei": "8795613362832", + "replacements": 0, + "fee_ceiling_wei": "45000000" + }, + "additional_authorizations": 7, + "additional_winning_tickets": 1, + "receipt": { + "block_number": "523528218", + "chain_id": 42161, + "effective_gas_price_wei": "20000000", + "gas_cost_wei": "3796600000000", + "gas_used": 189830, + "redeemer_balance_wei": "496203400000000", + "status": 1, + "transaction_hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780" + }, + "finalized": true, + "unique_redemption_transaction_identities": 1, + "remaining_small_unsettled_tickets": 5 + }, + "cleanup": { + "status": "verified_for_owned_resources", + "run": "cc-e2e-1112071043-bcbd", + "audit_source": "saved post-cleanup final-audit.json and all-runs-audit.json", + "source_inventory_recorded_at": "2026-11-12T10:12:53.350733+00:00", + "cleanup_verified_at": "2026-11-12T10:09:25.022063+00:00", + "owned_gcp_resources": { + "instances": [], + "disks": [], + "firewall-rules": [], + "networks": [], + "subnets": [] + }, + "owned_cloudflare_resources": { + "cfd_tunnel": [], + "access/apps": [], + "access/policies": [], + "access/service_tokens": [], + "dns": [], + "certificates": [] + }, + "temporary_access_credentials_removed": true, + "all_four_attempts_cleaned": true, + "baseline_gcp_instances_missing": [], + "baseline_preservation_exception": { + "unrelated_tunnel_deleted_before_cleanup": true, + "deleted_at": "2026-11-12T08:13:03.063799Z", + "recorded_in_owned_intents": false, + "unconditional_baseline_preservation_passed": false + }, + "other_active_test_run_excluded_from_scope": true, + "owned_cleanup_passed": true, + "payment_backups": "owner-only local recovery archive" + }, + "remaining_acceptance": [ + "#90 responder/verifier and #44 collection contract", + "#93/#118 full verifier/fleet acceptance matrix", + "production image promotion and full production Compose networking acceptance" + ], + "recovery_archive": { + "sqlite_integrity_verified": true, + "postgres_dump_catalog_verified": true, + "component_images": { + "archive_bytes": 188944124, + "sha256": "d4721fe28cb056f4fc3ba670266c520056e95c8f8cb0f843c74e6e0bcf658f22", + "references": [ + "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/managed-node@sha256:cc0a711c242df53a1d621082f11876cdad3b04983afe0e87c89fa7529ac28fb9", + "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", + "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/connector@sha256:4174086c856a6b85a42be12cd09becf37e75ee8ba54d72949f3a141235156226", + "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/node@sha256:a3dab72b2f364f88bc64bcc954e1ede32d43bcb7c6c288165c25a71740e2b57a", + "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/echo@sha256:b20ba6e917c81842f707a3fa4a581c073ceff7c22782b7ec993abe5c27d7863b" + ], + "pinned_manifests_preserved": true + }, + "unsettled_small_tickets": 5, + "payment_drain_complete": false + } +} diff --git a/docs/acceptance/119-managed-payments.md b/docs/acceptance/119-managed-payments.md new file mode 100644 index 0000000..e23f25a --- /dev/null +++ b/docs/acceptance/119-managed-payments.md @@ -0,0 +1,119 @@ +# Managed paid operation: fresh-install evidence + +Date: 2026-11-12. Run: `cc-e2e-1112071043-bcbd`. + +This records payment/configuration integration for #119. The broader #93/#118 +acceptance gate remains open: #90's versioned responder, trusted verifier and +collection/report contract are still open work. The nonce-echo fixture used here +checks transport and execution correctness; it is not that benchmark verifier. + +## Environment and provenance + +Two fresh `e2-standard-4` CPU workers ran actual K3s, gVisor app workloads and +keyless Node. A third disposable GCP VM ran the isolated Control Center fixture, +registry, TLS routing and the actual hardened standalone redeemer. Worker A used +private RPC/redemption endpoints with exact IP/port grants; worker B used public +endpoints. Their shared immutable catalog revisions retained exact `0.001 USD` +prices, respectively `hour` and `fixed`, throughout infrastructure changes. + +The redeemer used the actual Compose service and separate persistent database, +UID 65532, read-only root, dropped capabilities and no-new-privileges. This harness +used host networking for the redeemer's loopback connection to the native API; +it does not establish the full production Compose networking acceptance case. +The signing key was mounted only into the redeemer. No application received +payment, RPC, enrollment or origin-access credentials. + +Node's outbound-header dependency landed in +[Node #85](https://github.com/livepeer/node/pull/85), commit +`3533951e66584531a54a771d21c1388873439099`. Its main-branch CI and both published +architectures passed. The committed wrapper Dockerfile was also built against +that landed Node image and the tested Runtime. The accompanying JSON separates +that built package from the earlier functional fixture image and records exact +source/binary hashes and image digests. These disposable-registry pins are test +artifacts, not a production release promotion. Their OCI images were archived +before registry teardown. + +## Verified outcomes + +- Full PostgreSQL-backed API/Runtime/schema race suite, `go vet`, 41 UI browser + checks and the production UI build passed. All 45 Runtime Linux checks passed + on each worker, including kubectl manifest validation. The later Cloudflare + tombstone regression passed the tunnel race suite. +- Both workers applied payment generation 1 and registered the same catalog + revisions. Actual Node parsed the rendered paid TOML. Failed paid configuration + remained paid/failed and retained the last valid configuration. +- Paid persistent/hourly and single-shot/fixed calls executed ordinary sandboxed + HTTP requests. A verifier-generated nonce was checked in the response. Origin + access headers were absent from application requests. +- During private RPC loss, the same live Pod became unready while its funded + retained session, protected diagnostics and session stop remained reachable. + The public-RPC sibling remained ready. Recovery needed no Pod replacement. +- Both private endpoints were reachable only from the explicitly allowed + orchestrator. All three apps on each worker and the other orchestrator were + blocked. An unrelated neighboring port was reachable from the host and blocked + from the orchestrator. +- RPC/submission rotation and explicit rollback produced new generations and + grants and retained owner-only SQLite state. The disable/rollback cycle left + the sibling unchanged. A real + unsettled ticket blocked paid disable; the live paid workload/grant remained. +- A queue limit of two with two actual unsettled tickets closed local admission + while preserving paid mode. Restoring capacity restored readiness. +- The redeemer durably accepted three ticket identities while six successful + acknowledgements were deliberately lost. Retries produced nine HTTP + acceptances, three unique stored tickets and degraded-then-healthy remote + handoff observations. Empty worker passes did not establish healthy handoff. +- Forced removal with one unhanded winning ticket immediately revoked grants, + retained payment storage and reported recovery required with drain incomplete. + Re-enrollment preserved all tickets and the recipient pin. Ordinary management + refresh drained/replaced Node and retired old grants after observing its + replacement. Public discovery recovered under the new enrollment. +- Real Cloudflare deletion returned a tunnel tombstone without `config_src`. + Matching its retained ID/name allowed predecessor cleanup; foreign/active + ownership checks and late-resource inventory remained enforced. +- Ordinary removal with unsettled tickets retained Node/storage/grants and did + not acknowledge completion. No forced-removal case was reported payment-drained. + +## Funded bounds and remaining gates + +The original campaign used a `0.003 USD` per-authorization ceiling and returned +three signed batches (five tickets). Two earlier unfunded signer requests returned +no signed batch. The five small winning tickets were durably handed off; their +face value did not cover the measured redemption gas ceiling, so settlement and +ordinary payment drain remained blocked by the existing economic guard. + +The operator then approved a maximum `0.40 USD`: `0.20` ticket liability and `0.20` +redeemer gas. The bounded extension allowed at most nine authorizations, each at +most `0.02 USD`, with no fee replacements and a `45,000,000 wei` gas-price ceiling. +Seven authorizations, about `0.018 USD` maximum payout each, produced one additional +winning ticket. Signing stopped immediately. Catalog prices were unchanged. + +Its transaction mined successfully and retained the same signed bytes/nonce +across redeemer restart, then reached finality. It used `189830` gas at +`20000000 wei`, totaling `0.0000037966 ETH`, with one durable transaction identity +and no fee replacement. Exact receipt and final cleanup evidence are recorded in +the accompanying JSON. The five small +unsettled tickets are preserved in separate owner-only Node/redeemer backups; +ordinary drain is not claimed complete for them. + +## Cleanup and recovery retention + +Cleanup was verified at `2026-11-12T10:09:25Z`. The saved post-cleanup inventory +contains no GCP or Cloudflare resources owned by this run; all four attempts +recorded verified cleanup and removed generated access credentials. A separate +active test run was excluded from this ownership scope and left untouched. + +The broader baseline check did not pass unconditionally: an unrelated baseline +tunnel had been deleted at `08:13:03Z`, before this run's `10:03:43Z` teardown. +It was absent from this run's ownership intents. The scoped cleanup result keeps +that exception visible rather than claiming full baseline preservation. + +Consistent Node/redeemer SQLite backups, a Control Center PostgreSQL dump, matching +private recovery inputs and the five pinned component images remain in an +owner-only operator archive. The OCI archive preserves the original pinned +manifests and has a recorded SHA-256. Cloud cleanup did not discard retained +financial state. Recover the five small tickets under their original bindings +and routing/trust inputs; removing infrastructure does not complete payment drain. + +Still outside the completed evidence: #90/#44 verifier/report integration and the +full #93/#118 attribution, offline, cancellation and fleet acceptance matrix. +No case depends on changing an existing installation into this implementation. diff --git a/docs/paid-operation.md b/docs/paid-operation.md index d217984..0346a8b 100644 --- a/docs/paid-operation.md +++ b/docs/paid-operation.md @@ -133,6 +133,11 @@ error or reinterpret retained state on a different chain or recipient. Back up SQLite through a consistent online backup or while the writer is stopped; retain the matching database/WAL state. Back up the redeemer database separately from the orchestrator's, and keep signing-key backups under operator control. +Retain the bound redemption origin and its private routing/trust inputs until +outstanding tickets are resolved. Restore those routes together with retained +state; changing destination still requires fresh zero-unsettled evidence. +Re-enrollment waits for authoritative cleanup of the preceding ingress resources +before publishing its new protected routes. ## Acceptance evidence From 413fceee78020a5da8e6dac19333af799f5ad005 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 02:32:10 -0800 Subject: [PATCH 06/15] Use onchain naming and preserve existing migration history --- README.md | 2 +- .../administrator_database_test.go | 2 +- api/internal/controlplane/assignments_test.go | 4 +- .../controlplane/machineconfig/manager.go | 2 +- .../machineconfig/observations.go | 4 +- .../controlplane/machineconfig/payment.go | 2 +- .../machineconfig/payment_test.go | 14 +-- .../controlplane/machineconfig/reports.go | 2 +- .../controlplane/machineconfig/rollout.go | 14 +-- .../controlplane/machineconfig/runtime.go | 4 +- .../controlplane/machineconfig/system.go | 2 +- .../controlplane/machineconfig/system_test.go | 4 +- .../templates/system/node/orchestrator.yaml | 1 + .../controlplane/migrations/001_initial.sql | 24 ----- .../migrations/007_runtime_retirement.sql | 2 - .../migrations/009_onchain_payments.sql | 68 +++++++++++++ .../controlplane/payment_credentials.go | 6 +- .../controlplane/payment_migration_test.go | 97 +++++++++++++++++++ api/internal/controlplane/payment_settings.go | 12 +-- api/internal/controlplane/payment_test.go | 52 +++++----- deploy/README.md | 6 +- ...compose.paid.yaml => compose.onchain.yaml} | 4 +- deploy/config.example.toml | 2 +- deploy/payments.example.json | 2 +- docs/acceptance/119-managed-payments.json | 24 +++-- docs/acceptance/119-managed-payments.md | 17 ++-- docs/app-registry.md | 4 +- ...paid-operation.md => onchain-operation.md} | 24 +++-- runtime/appreconciler/controller.go | 8 +- runtime/appreconciler/input.go | 2 +- runtime/appreconciler/payment_test.go | 8 +- runtime/httpsource/source.go | 2 +- runtime/orchestrator/integration.go | 2 +- runtime/orchestrator/integration_test.go | 2 +- runtime/orchestrator/observation.go | 2 +- runtime/payment/config.go | 10 +- runtime/payment/config_test.go | 6 +- schema/validate.go | 4 +- ui/src/machine-status.tsx | 4 +- ui/tests/machine-status.spec.ts | 8 +- 40 files changed, 311 insertions(+), 148 deletions(-) create mode 100644 api/internal/controlplane/migrations/009_onchain_payments.sql create mode 100644 api/internal/controlplane/payment_migration_test.go rename deploy/{compose.paid.yaml => compose.onchain.yaml} (87%) rename docs/{paid-operation.md => onchain-operation.md} (89%) diff --git a/README.md b/README.md index c061e43..09f2ed2 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ flowchart TB ## Documentation -- [Managed paid operation](docs/paid-operation.md): configure fresh deployments and inspect payment readiness. +- [Managed onchain operation](docs/onchain-operation.md): configure fresh deployments and inspect payment readiness. - [App registry](docs/app-registry.md): publish app definitions and assign revisions to machines. - [Fleet discovery](docs/fleet-discovery.md): expose managed orchestrators through an aggregate inventory. - [Machine status](docs/machine-status.md): inspect rollout, configured health, registration, discovery and cleanup evidence. diff --git a/api/internal/controlplane/administrator_database_test.go b/api/internal/controlplane/administrator_database_test.go index 8540e86..100c814 100644 --- a/api/internal/controlplane/administrator_database_test.go +++ b/api/internal/controlplane/administrator_database_test.go @@ -66,7 +66,7 @@ func TestAdministratorDatabasePrivileges(t *testing.T) { if err := db.QueryRow(`SELECT has_table_privilege($1,'lpcc.machine_app_heads','SELECT,INSERT,UPDATE,DELETE'),has_function_privilege($1,'lpcc.remove_machine_apps(text,uuid,text)','EXECUTE')`, role).Scan(&view, &execute); err != nil || view || execute { t.Fatal("assignment view/function access", role, view, execute, err) } - for _, table := range []string{"administrator_grants", "admin_audit_events", "apps", "app_revisions", "app_revision_state", "enrollments", "credential_refreshes", "machine_reports", "machine_states", "access_credentials", "machine_app_versions", "machine_app_deliveries", "machine_app_completions", "machine_app_diagnostics"} { + for _, table := range []string{"administrator_grants", "admin_audit_events", "apps", "app_revisions", "app_revision_state", "enrollments", "credential_refreshes", "machine_reports", "machine_states", "access_credentials", "machine_app_versions", "machine_app_deliveries", "machine_app_completions", "machine_app_diagnostics", "payment_revision", "payment_machines", "payment_versions", "payment_secrets", "payment_grants"} { var privilege, rls bool var policies int if err := db.QueryRow(`SELECT has_table_privilege($1,$2,'SELECT,INSERT,UPDATE,DELETE')`, role, "lpcc."+table).Scan(&privilege); err != nil || privilege { diff --git a/api/internal/controlplane/assignments_test.go b/api/internal/controlplane/assignments_test.go index 9a41461..a91bd60 100644 --- a/api/internal/controlplane/assignments_test.go +++ b/api/internal/controlplane/assignments_test.go @@ -517,9 +517,9 @@ func TestAssignmentReportValidationAndProviderBackoff(t *testing.T) { if err != nil { t.Fatal(err) } - // Empty certificate and retirement snapshot migrations can roll back while + // Empty payment, certificate and retirement snapshot migrations can roll back while // this enrollment is active; assignment history must still be preserved. - for range 2 { + for range 3 { if err := migrations.Down(t.Context(), s.db, files); err != nil { t.Fatal(err) } diff --git a/api/internal/controlplane/machineconfig/manager.go b/api/internal/controlplane/machineconfig/manager.go index a3159cb..8c8490c 100644 --- a/api/internal/controlplane/machineconfig/manager.go +++ b/api/internal/controlplane/machineconfig/manager.go @@ -62,7 +62,7 @@ func (s *Manager) Desired(m Machine, state State, exposure *Exposure) Desired { } d := Desired{Payment: p, PaymentError: err, Machine: m, State: state, Exposure: exposure, Connector: connector, ControlAPIURL: s.config.APIURL, RuntimeImage: s.config.RuntimeImage, NodeImage: s.config.NodeImage, NodeDrainTimeout: s.config.NodeDrainTimeout, StopSignals: s.config.StopSignals, DrainTimeout: s.drainTimeout()} - if p.Paid() && s.store.DB != nil { + if p.Onchain() && s.store.DB != nil { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) r, at, e := s.store.Report(ctx, m, "runtime") cancel() diff --git a/api/internal/controlplane/machineconfig/observations.go b/api/internal/controlplane/machineconfig/observations.go index 5905003..f16fa72 100644 --- a/api/internal/controlplane/machineconfig/observations.go +++ b/api/internal/controlplane/machineconfig/observations.go @@ -20,7 +20,7 @@ func optionalID(s string) bool { return s == "" || statusID.MatchString(s) } func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) error { if p := r.Payment; p != nil { - if r.Component != "runtime" || (p.Mode != "paid" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || p.Unsettled < 0 || p.Unsettled > 10000000 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { + if r.Component != "runtime" || (p.Mode != "onchain" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || p.Unsettled < 0 || p.Unsettled > 10000000 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { return ErrStaleStatus } if p.Applied { @@ -28,7 +28,7 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) if err != nil || r.ConfigDigest != meta.ConfigDigest || p.Generation != meta.Payment.Generation || p.Mode != meta.Payment.Mode || p.PodUID == "" { return ErrStaleStatus } - if p.Mode == "paid" { + if p.Mode == "onchain" { var known bool err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.payment_grants WHERE grant_id::text=$1 AND node_id=$2 AND epoch=$3 AND payment_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, m.Epoch, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) if err != nil { diff --git a/api/internal/controlplane/machineconfig/payment.go b/api/internal/controlplane/machineconfig/payment.go index 21d0662..cfc737c 100644 --- a/api/internal/controlplane/machineconfig/payment.go +++ b/api/internal/controlplane/machineconfig/payment.go @@ -30,7 +30,7 @@ func specializePayment(raw string, m Desired) string { // The Service remains a private route to a live process during dependency loss. raw = strings.Replace(raw, "spec:\n selector:\n app: orchestrator", "spec:\n publishNotReadyAddresses: true\n selector:\n app: orchestrator", 1) c := m.Payment - if !c.Paid() { + if !c.Onchain() { return raw } endpoint, _ := url.Parse(c.RedeemerURL) diff --git a/api/internal/controlplane/machineconfig/payment_test.go b/api/internal/controlplane/machineconfig/payment_test.go index 2b22dc8..feb169b 100644 --- a/api/internal/controlplane/machineconfig/payment_test.go +++ b/api/internal/controlplane/machineconfig/payment_test.go @@ -17,8 +17,8 @@ import ( "go.yaml.in/yaml/v3" ) -func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { - c := payment.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} +func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { + c := payment.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} b, d, e := Build(m) if e != nil { @@ -42,7 +42,7 @@ func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { if e := decoder.Decode(&document); e == io.EOF { break } else if e != nil { - t.Fatal("invalid paid manifest", name, e) + t.Fatal("invalid onchain manifest", name, e) } } } @@ -61,7 +61,7 @@ func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { path := filepath.Join(dir, "orchestrator.toml") os.WriteFile(path, []byte(config), 0600) if output, e := exec.Command(binary, "--config", path, "--print-config").CombinedOutput(); e != nil { - t.Fatal("actual Node rejected paid configuration", e, string(output)) + t.Fatal("actual Node rejected onchain configuration", e, string(output)) } } for _, want := range []string{"orchestrator-start", "orchestrator-probe", "publishNotReadyAddresses: true", "fsGroupChangePolicy: OnRootMismatch", "RPCURLFile", "RedeemerHeadersFile", "/data/payments.sqlite", "medium: Memory"} { @@ -102,7 +102,7 @@ func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { t.Fatal("payment metadata absent") } // Fields omitted by a held offchain identity must not survive from the - // desired paid configuration while the existing workload drains. + // desired onchain configuration while the existing workload drains. free := m free.State.HeldOrchestrator, free.State.HeldPayment = "", "" free.Payment = payment.Offchain() @@ -119,8 +119,8 @@ func TestPaidBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { } files, _ = artifact.Read(b) parsed, e = transport.ReadMetadata(files["runtime.json"]) - if e != nil || parsed.Payment.Paid() || parsed.Payment.Recipient != "" || parsed.Payment.RPCSecret != "" { - t.Fatal("held offchain workload inherited desired paid inputs", parsed.Payment, e) + if e != nil || parsed.Payment.Onchain() || parsed.Payment.Recipient != "" || parsed.Payment.RPCSecret != "" { + t.Fatal("held offchain workload inherited desired onchain inputs", parsed.Payment, e) } } diff --git a/api/internal/controlplane/machineconfig/reports.go b/api/internal/controlplane/machineconfig/reports.go index 63d08ab..832239b 100644 --- a/api/internal/controlplane/machineconfig/reports.go +++ b/api/internal/controlplane/machineconfig/reports.go @@ -95,7 +95,7 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b if previous.Drained && previous.Generation == report.Generation && previous.Evidence != nil && report.Evidence != nil && previous.Evidence.Target == report.Evidence.Target && time.Now().Before(previous.Evidence.ExpiresAt) { drainWake = false } - paymentWake := report.Component == "runtime" && report.Payment != nil && (record.RolloutReason == "payment_drain_pending" || (report.Payment.Mode == "paid" && record.ApprovedConfigDigest != report.ConfigDigest)) + paymentWake := report.Component == "runtime" && report.Payment != nil && (record.RolloutReason == "payment_drain_pending" || (report.Payment.Mode == "onchain" && record.ApprovedConfigDigest != report.ConfigDigest)) return paymentWake || drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil } diff --git a/api/internal/controlplane/machineconfig/rollout.go b/api/internal/controlplane/machineconfig/rollout.go index 9db8ef1..f9f27b7 100644 --- a/api/internal/controlplane/machineconfig/rollout.go +++ b/api/internal/controlplane/machineconfig/rollout.go @@ -29,7 +29,7 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des if desired.PaymentError != nil { return false, desired.PaymentError } - if desired.Payment.Paid() { + if desired.Payment.Onchain() { state.PaymentSettled = false } old, manifest, err := s.applied(ctx, m) @@ -40,12 +40,12 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des desired.State.HeldOrchestrator = "" desired.State.HeldUpgradePlan = "" digest := Digest(desired) - // Admission has never opened for this paid target. Its image or rendering + // Admission has never opened for this onchain target. Its image or rendering // can be repaired without asking the failed process to drain again, while // retaining the exact payment/storage binding and the admission freeze. frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested && !state.PaymentDrainAfter.IsZero() initial := state.ApplyingConfigDigest == "" && state.ApprovedConfigDigest == "" - if old.ConfigDigest != digest && old.Payment.Paid() && !old.PaymentActive && state.ApprovedConfigDigest != old.ConfigDigest && paymentJSON(old.Payment) == paymentJSON(desired.Payment) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { + if old.ConfigDigest != digest && old.Payment.Onchain() && !old.PaymentActive && state.ApprovedConfigDigest != old.ConfigDigest && paymentJSON(old.Payment) == paymentJSON(desired.Payment) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { state.HeldOrchestrator, state.HeldUpgradePlan = "", "" state.ApplyingConfigDigest = digest state.ApplyingUpgradeVersion = upgradeVersion(desired) @@ -76,7 +76,7 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des state.ApplyingUpgradeVersion = "" } if state.HeldOrchestrator == "" && (state.ApprovedConfigDigest == digest || old.ConfigDigest == digest) { - if desired.Payment.Paid() && state.ApprovedConfigDigest != digest { + if desired.Payment.Onchain() && state.ApprovedConfigDigest != digest { if !desired.PaymentReady { state.RolloutReason = "payment_startup_pending" return false, nil @@ -103,12 +103,12 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des return true, err } } - if old.Payment.Paid() && (!desired.Payment.Paid() || desired.Payment.RedeemerURL != old.Payment.RedeemerURL) { + if old.Payment.Onchain() && (!desired.Payment.Onchain() || desired.Payment.RedeemerURL != old.Payment.RedeemerURL) { if !s.paymentDrained(ctx, m, old, state.PaymentDrainAfter) { state.RolloutReason = "payment_drain_pending" return true, nil } - if !desired.Payment.Paid() { + if !desired.Payment.Onchain() { state.PaymentSettled = true } } @@ -258,7 +258,7 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { func paymentJSON(c payment.Config) string { b, _ := json.Marshal(c); return string(b) } func (s *Manager) paymentDrained(ctx context.Context, m Machine, old Runtime, after time.Time) bool { - if !old.Payment.Paid() { + if !old.Payment.Onchain() { return true } r, at, e := s.store.Report(ctx, m, "runtime") diff --git a/api/internal/controlplane/machineconfig/runtime.go b/api/internal/controlplane/machineconfig/runtime.go index e464387..645674c 100644 --- a/api/internal/controlplane/machineconfig/runtime.go +++ b/api/internal/controlplane/machineconfig/runtime.go @@ -100,8 +100,8 @@ func DesiredRuntime(m Desired) Runtime { if d.Payment.Version == 0 { d.Payment = payment.Offchain() } - d.PaymentActive = !m.State.DrainRequested && m.State.ApplyingConfigDigest == "" && (!d.Payment.Paid() || (m.PaymentReady && m.State.ApprovedConfigDigest == d.ConfigDigest)) - if d.Payment.Paid() { + d.PaymentActive = !m.State.DrainRequested && m.State.ApplyingConfigDigest == "" && (!d.Payment.Onchain() || (m.PaymentReady && m.State.ApprovedConfigDigest == d.ConfigDigest)) + if d.Payment.Onchain() { d.PaymentCredentialsRef = "/v1/nodes/" + m.NodeID + "/payment/credentials" } d.RunnerServiceURL = PrivateOrchestrator diff --git a/api/internal/controlplane/machineconfig/system.go b/api/internal/controlplane/machineconfig/system.go index 82e730e..a3e5263 100644 --- a/api/internal/controlplane/machineconfig/system.go +++ b/api/internal/controlplane/machineconfig/system.go @@ -80,7 +80,7 @@ func addSystemWorkloads(files map[string][]byte, m Desired) error { continue } files[prefix+"system/node/network.yaml"] = []byte(nodeNetwork()) - if effectivePayment(m).Paid() { + if effectivePayment(m).Onchain() { files[prefix+"management/app-reconciler.yaml"] = append(files[prefix+"management/app-reconciler.yaml"], []byte("\n---\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata: {name: orchestrator-payment-egress, namespace: livepeer}\nspec:\n podSelector: {matchLabels: {app: orchestrator}}\n policyTypes: [Egress]\n egress:\n"+paymentNetwork(effectivePayment(m)))...) } files[prefix+"system/node/kustomization.yaml"] = kustomize("orchestrator.yaml", "network.yaml") diff --git a/api/internal/controlplane/machineconfig/system_test.go b/api/internal/controlplane/machineconfig/system_test.go index 56dfd54..3c32dac 100644 --- a/api/internal/controlplane/machineconfig/system_test.go +++ b/api/internal/controlplane/machineconfig/system_test.go @@ -126,8 +126,8 @@ func TestProxyRoutingFollowsHeldNodeConfiguration(t *testing.T) { private := build() m.Exposure = &Exposure{TunnelID: "tunnel", ServiceURL: "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.a.invalid", ProxyURLTemplate: "https://{proxy}.lp-aaaaaaaaaaaaaaaa.a.invalid", IngressDigest: "ingress"} a := build() - if !strings.Contains(string(a[prefix+nodeFile]), `RunnerServiceURL = "`+PrivateOrchestrator+`"`) { - t.Fatal("public Node routing omitted the private runner callback URL") + if !strings.Contains(string(a[prefix+nodeFile]), `APIOriginURL = "`+PrivateOrchestrator+`"`) { + t.Fatal("public Node routing omitted the private API origin") } m.State.HeldOrchestrator = string(a[prefix+nodeFile]) m.Exposure.ServiceURL = "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.b.invalid" diff --git a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml index 0c3fccc..478061a 100644 --- a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml +++ b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml @@ -61,6 +61,7 @@ data: Listen = "unsafe@0.0.0.0:8935" MetricsListen = "unsafe@0.0.0.0:8936" ServiceURL = "@SERVICE_URL@" + APIOriginURL = "http://orchestrator.livepeer.svc.cluster.local:8935" RunnerServiceURL = "http://orchestrator.livepeer.svc.cluster.local:8935" ProxyURLTemplate = "@PROXY_URL_TEMPLATE@" BootstrapSecretFile = "/credentials/secret" diff --git a/api/internal/controlplane/migrations/001_initial.sql b/api/internal/controlplane/migrations/001_initial.sql index a1dadd4..34e6a5f 100644 --- a/api/internal/controlplane/migrations/001_initial.sql +++ b/api/internal/controlplane/migrations/001_initial.sql @@ -18,30 +18,6 @@ CREATE TABLE lpcc.machine_configs ( sha256 TEXT NOT NULL CHECK(sha256 ~ '^[0-9a-f]{64}$'), generated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); --- Payment infrastructure is part of the fresh-install schema. These records --- deliberately survive enrollment and Auth account deletion. -CREATE TABLE lpcc.payment_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); -INSERT INTO lpcc.payment_revision DEFAULT VALUES; -CREATE TABLE lpcc.payment_machines ( - node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), - recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', - generation BIGINT NOT NULL CHECK(generation>0), config JSONB NOT NULL, - initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false -); -CREATE TABLE lpcc.payment_versions ( - node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, - PRIMARY KEY(node_id,generation) -); -CREATE TABLE lpcc.payment_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); -CREATE TABLE lpcc.payment_grants ( - grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, - payment_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, - pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, - observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, - UNIQUE(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) -); -CREATE INDEX payment_grants_machine ON lpcc.payment_grants(node_id,epoch); -- DOWN -DROP TABLE lpcc.payment_grants,lpcc.payment_secrets,lpcc.payment_versions,lpcc.payment_machines,lpcc.payment_revision; DROP TABLE lpcc.machine_configs; DROP TABLE lpcc.machines; diff --git a/api/internal/controlplane/migrations/007_runtime_retirement.sql b/api/internal/controlplane/migrations/007_runtime_retirement.sql index d2b2498..1a0d28a 100644 --- a/api/internal/controlplane/migrations/007_runtime_retirement.sql +++ b/api/internal/controlplane/migrations/007_runtime_retirement.sql @@ -6,8 +6,6 @@ ALTER TABLE lpcc.enrollments ADD COLUMN retained_bundle BYTEA; CREATE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - UPDATE lpcc.payment_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; - UPDATE lpcc.payment_machines SET recovery_required=recovery_required OR (NOT drained AND (initialized OR config->>'mode'='paid') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'payment_settled'='true')) WHERE node_id=OLD.node_id; UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id diff --git a/api/internal/controlplane/migrations/009_onchain_payments.sql b/api/internal/controlplane/migrations/009_onchain_payments.sql new file mode 100644 index 0000000..ca4b747 --- /dev/null +++ b/api/internal/controlplane/migrations/009_onchain_payments.sql @@ -0,0 +1,68 @@ +-- UP +-- Payment bindings deliberately survive enrollment and Auth account deletion. +CREATE TABLE lpcc.payment_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); +INSERT INTO lpcc.payment_revision DEFAULT VALUES; +CREATE TABLE lpcc.payment_machines ( + node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), + recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', + generation BIGINT NOT NULL CHECK(generation>0), config JSONB NOT NULL, + initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false +); +CREATE TABLE lpcc.payment_versions ( + node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, + PRIMARY KEY(node_id,generation) +); +CREATE TABLE lpcc.payment_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); +CREATE TABLE lpcc.payment_grants ( + grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, + payment_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, + pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, + observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, + UNIQUE(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) +); +CREATE INDEX payment_grants_machine ON lpcc.payment_grants(node_id,epoch); + +CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER + SET search_path=pg_catalog,lpcc AS $$ +BEGIN + UPDATE lpcc.payment_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + UPDATE lpcc.payment_machines SET recovery_required=recovery_required OR (NOT drained AND (initialized OR config->>'mode'='onchain') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'payment_settled'='true')) WHERE node_id=OLD.node_id; + UPDATE lpcc.enrollments e SET retained_bundle=c.bundle + FROM lpcc.machine_configs c + WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + AND e.retained_bundle IS NULL; + RETURN OLD; +END $$; +ALTER TABLE lpcc.payment_revision ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.payment_machines ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.payment_versions ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.payment_secrets ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.payment_grants ENABLE ROW LEVEL SECURITY; +REVOKE ALL ON lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants FROM PUBLIC; +REVOKE ALL ON SEQUENCE lpcc.payment_grants_issued_sequence_seq FROM PUBLIC; +DO $$ DECLARE r TEXT; +BEGIN + FOREACH r IN ARRAY ARRAY['anon','authenticated'] LOOP + IF EXISTS(SELECT FROM pg_roles WHERE rolname=r) THEN + EXECUTE format('REVOKE ALL ON lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants FROM %I',r); + EXECUTE format('REVOKE ALL ON SEQUENCE lpcc.payment_grants_issued_sequence_seq FROM %I',r); + END IF; + END LOOP; +END $$; +-- DOWN +DO $$ BEGIN + IF EXISTS(SELECT FROM lpcc.payment_machines) OR EXISTS(SELECT FROM lpcc.payment_versions) + OR EXISTS(SELECT FROM lpcc.payment_secrets) OR EXISTS(SELECT FROM lpcc.payment_grants) THEN + RAISE EXCEPTION 'retain payment schema while payment history exists'; + END IF; +END $$; +CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER + SET search_path=pg_catalog,lpcc AS $$ +BEGIN + UPDATE lpcc.enrollments e SET retained_bundle=c.bundle + FROM lpcc.machine_configs c + WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + AND e.retained_bundle IS NULL; + RETURN OLD; +END $$; +DROP TABLE lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants; diff --git a/api/internal/controlplane/payment_credentials.go b/api/internal/controlplane/payment_credentials.go index b2d0dc7..1d492f3 100644 --- a/api/internal/controlplane/payment_credentials.go +++ b/api/internal/controlplane/payment_credentials.go @@ -59,7 +59,7 @@ func (s *Server) paymentCredentials(w http.ResponseWriter, r *http.Request) { if e == nil { metadata, e = transport.ReadMetadata(files["runtime.json"]) } - if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Payment.Paid() || metadata.Payment.Generation != in.PaymentGeneration || metadata.ConfigDigest != in.ConfigDigest { + if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Payment.Onchain() || metadata.Payment.Generation != in.PaymentGeneration || metadata.ConfigDigest != in.ConfigDigest { fail(w, 409, "payment configuration changed") return } @@ -150,7 +150,7 @@ func (s *Server) observePaymentGrant(ctx context.Context, m Machine, reportPayme if p == nil || !p.Applied || p.PodUID == "" { return nil } - if p.Mode != "offchain" && (p.Mode != "paid" || !appID(p.GrantID)) { + if p.Mode != "offchain" && (p.Mode != "onchain" || !appID(p.GrantID)) { return nil } tx, e := s.db.BeginTx(ctx, nil) @@ -179,7 +179,7 @@ func (s *Server) observePaymentGrant(ctx context.Context, m Machine, reportPayme } if p.Mode == "offchain" { // The replacement has no submission bearer to observe. Retire the held - // paid workload's grants only after its offchain successor is applied. + // onchain workload's grants only after its offchain successor is applied. _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, m.NodeID, m.Epoch) if e != nil { return e diff --git a/api/internal/controlplane/payment_migration_test.go b/api/internal/controlplane/payment_migration_test.go new file mode 100644 index 0000000..a4a6beb --- /dev/null +++ b/api/internal/controlplane/payment_migration_test.go @@ -0,0 +1,97 @@ +package controlplane + +import ( + "bytes" + "io/fs" + "strings" + "testing" + "testing/fstest" + + "github.com/livepeer/control-center/api/internal/controlplane/payments" + "github.com/livepeer/control-center/api/internal/migrations" + "github.com/livepeer/control-center/api/internal/testdb" + "github.com/livepeer/control-center/runtime/payment" +) + +func TestPaymentMigrationPreservesExistingOffchainMachine(t *testing.T) { + db := testdb.Open(t) + files, err := fs.Sub(MigrationFiles, "migrations") + if err != nil { + t.Fatal(err) + } + prior := fstest.MapFS{} + entries, err := fs.ReadDir(files, ".") + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if entry.Name() >= "009_" { + continue + } + data, err := fs.ReadFile(files, entry.Name()) + if err != nil { + t.Fatal(err) + } + prior[entry.Name()] = &fstest.MapFile{Data: data} + } + if err := migrations.Up(t.Context(), db, prior); err != nil { + t.Fatal(err) + } + // These are the hashes already recorded by main, not hashes recomputed from + // this branch. Editing either historical migration must reject this upgrade. + if _, err := db.Exec(`UPDATE lpcc.migrations SET sha256=CASE version + WHEN 1 THEN '3faa2618112eb2080dac3cf9e8da1dbead8460e2c2c0b361a33c8c869ea46951' + WHEN 7 THEN 'ef717f935c921d5f9f5fd683e2bd3643e275fc273f5f5f8abf4ac3efcb30d23c' + END WHERE version IN (1,7)`); err != nil { + t.Fatal(err) + } + const node = "lp-aaaaaaaaaaaaaaaa" + const bundle = "retained pre-payment bundle" + if _, err := db.Exec(`INSERT INTO auth.users(id,email) VALUES($1,'existing@example.invalid')`, ownerA); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO lpcc.machines(node_id,fingerprint,owner_id,hostname,install_dir,k3s_version) + VALUES($1,$2,$3,'existing','/srv/livepeer','v1.37.2+k3s1')`, node, strings.Repeat("a", 64), ownerA); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO lpcc.machine_configs(node_id,bundle,sha256) VALUES($1,$2,$3)`, node, []byte(bundle), strings.Repeat("b", 64)); err != nil { + t.Fatal(err) + } + if err := Migrate(t.Context(), db); err != nil { + t.Fatal(err) + } + config, err := payments.Load(t.Context(), db, node) + if err != nil || config.Mode != "offchain" || config.Generation != 0 { + t.Fatal("existing machine acquired payment settings", config, err) + } + var retained []byte + if err := db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&retained); err != nil || !bytes.Equal(retained, []byte(bundle)) { + t.Fatal("migration changed the existing bundle", err) + } + // The replacement retirement trigger must also work for existing machines + // without payment records, retaining the same pre-upgrade bundle. + if _, err := db.Exec(`DELETE FROM lpcc.machines WHERE node_id=$1`, node); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1`, node).Scan(&retained); err != nil || !bytes.Equal(retained, []byte(bundle)) { + t.Fatal("retirement lost the existing bundle", err) + } +} + +func TestPaymentMigrationRollbackPreservesPaymentHistory(t *testing.T) { + s := newTestServer(t) + config := onchainSettings(t, s) + if _, err := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{"lp-aaaaaaaaaaaaaaaa": config}}, 0); err != nil { + t.Fatal(err) + } + files, err := fs.Sub(MigrationFiles, "migrations") + if err != nil { + t.Fatal(err) + } + if err := migrations.Down(t.Context(), s.db, files); err == nil || !strings.Contains(err.Error(), "retain payment schema") { + t.Fatal("rollback did not protect payment history", err) + } + if count(t, s, `SELECT count(*) FROM lpcc.payment_versions`) != 1 { + t.Fatal("rollback discarded payment history") + } +} diff --git a/api/internal/controlplane/payment_settings.go b/api/internal/controlplane/payment_settings.go index 807e2f7..8e86e73 100644 --- a/api/internal/controlplane/payment_settings.go +++ b/api/internal/controlplane/payment_settings.go @@ -118,12 +118,12 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected return 0, e } nodes = append(nodes, node) - if c.Paid() { + if c.Onchain() { if len(s.params.PaymentWebhookSecret) < 32 { - return 0, errors.New("paid operation requires a webhook service credential") + return 0, errors.New("onchain operation requires a webhook service credential") } if !machineconfigImage(s.params.RuntimeNodeImage) { - return 0, errors.New("paid operation requires a pinned wrapper/Node image") + return 0, errors.New("onchain operation requires a pinned wrapper/Node image") } b, e := s.readPaymentRPC(c.RPCSecret) if e != nil { @@ -147,8 +147,8 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected return 0, e } - // Import is a complete desired snapshot: omission never silently disables paid service. - rows, e := tx.QueryContext(ctx, `SELECT node_id FROM lpcc.payment_machines WHERE config->>'mode'='paid'`) + // Import is a complete desired snapshot: omission never silently disables onchain service. + rows, e := tx.QueryContext(ctx, `SELECT node_id FROM lpcc.payment_machines WHERE config->>'mode'='onchain'`) if e != nil { return 0, e } @@ -222,7 +222,7 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected if e != nil && !errors.Is(e, sql.ErrNoRows) { return 0, e } - if c.Paid() { + if c.Onchain() { if recipient != "" && (!strings.EqualFold(recipient, c.Recipient) || chain != c.ChainID || !strings.EqualFold(controller, c.Controller)) { return 0, errors.New("payment recipient and chain binding are immutable") } diff --git a/api/internal/controlplane/payment_test.go b/api/internal/controlplane/payment_test.go index 43f54a1..2ffd062 100644 --- a/api/internal/controlplane/payment_test.go +++ b/api/internal/controlplane/payment_test.go @@ -16,7 +16,7 @@ import ( "github.com/livepeer/control-center/runtime/payment" ) -func paidSettings(t *testing.T, s *Server) payment.Config { +func onchainSettings(t *testing.T, s *Server) payment.Config { t.Helper() dir := t.TempDir() s.params.PaymentSecretsDir = dir @@ -24,11 +24,11 @@ func paidSettings(t *testing.T, s *Server) payment.Config { if e := os.WriteFile(filepath.Join(dir, "rpc-v1"), []byte("https://rpc.example/private-token"), 0600); e != nil { t.Fatal(e) } - return payment.Config{Version: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://api.example/redemption", WeiPerUSD: "1000000000000000", TicketFaceValue: "1000", TicketWinProb: "100", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} + return payment.Config{Version: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://api.example/redemption", WeiPerUSD: "1000000000000000", TicketFaceValue: "1000", TicketWinProb: "100", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} } func TestPaymentApplyAtomicBindingAndSecretVersions(t *testing.T) { s := newTestServer(t) - c := paidSettings(t, s) + c := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" in := paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}} if rev, e := s.applyPayments(t.Context(), in, 0); e != nil || rev != 1 { @@ -52,7 +52,7 @@ func TestPaymentApplyAtomicBindingAndSecretVersions(t *testing.T) { // Omission and immutable bindings fail without committing another audit event. other := payment.Offchain() if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{"lp-bbbbbbbbbbbbbbbb": other}}, 1); e == nil { - t.Fatal("omission disabled paid machine") + t.Fatal("omission disabled onchain machine") } for _, mutate := range []func(*payment.Config){func(c *payment.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *payment.Config) { c.ChainID++ }, func(c *payment.Config) { c.TicketWinProb = "0" }} { next := c @@ -73,7 +73,7 @@ func TestPaymentApplyAtomicBindingAndSecretVersions(t *testing.T) { } func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { s := newTestServer(t) - c := paidSettings(t, s) + c := onchainSettings(t, s) machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) node := machine["node_id"] if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}}, 0); e != nil { @@ -164,9 +164,9 @@ func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { } } -func TestPaidActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing.T) { +func TestOnchainActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing.T) { s := newTestServer(t) - cfg := paidSettings(t, s) + cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { t.Fatal(e) @@ -192,7 +192,7 @@ func TestPaidActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing return m } if metadata().PaymentActive { - t.Fatal("saved setting treated as active paid operation") + t.Fatal("saved setting treated as active onchain operation") } m0 := metadata() launch := orchestrator.Launch{PodName: "orchestrator-test", PodUID: "node-pod", LaunchID: strings.Repeat("a", 32), ProcessID: strings.Repeat("b", 64)} @@ -203,7 +203,7 @@ func TestPaidActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing report := func(known bool, n int64) { t.Helper() m := metadata() - r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Payment: &payment.Observation{Generation: m.Payment.Generation, Mode: "paid", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) + r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Payment: &payment.Observation{Generation: m.Payment.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) requireStatus(t, request(t, s, "POST", "/v1/nodes/"+node+"/status", c["token"], r), 200) } if _, e := s.db.Exec(`UPDATE lpcc.payment_machines SET recovery_required=true WHERE node_id=$1`, node); e != nil { @@ -275,7 +275,7 @@ func TestPaidActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { s := newTestServer(t) - cfg := paidSettings(t, s) + cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { t.Fatal(e) @@ -307,7 +307,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { } observe := func(g orchestrator.Grant) { t.Helper() - if e := s.observePaymentGrant(t.Context(), machine, &payment.Observation{Generation: m.Payment.Generation, Mode: "paid", PodUID: "same-pod", GrantID: g.GrantID, Applied: true, Ready: true}, m.ConfigDigest); e != nil { + if e := s.observePaymentGrant(t.Context(), machine, &payment.Observation{Generation: m.Payment.Generation, Mode: "onchain", PodUID: "same-pod", GrantID: g.GrantID, Applied: true, Ready: true}, m.ConfigDigest); e != nil { t.Fatal(e) } } @@ -323,7 +323,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { } third := issue("c") if !third.RequireState { - t.Fatal("initialized paid database can be silently recreated") + t.Fatal("initialized onchain database can be silently recreated") } off := payment.Offchain() off.Generation = m.Payment.Generation + 1 @@ -340,7 +340,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { t.Fatal(e) } if e = s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, third.GrantID).Scan(&revoked); e != nil || revoked { - t.Fatal("offchain observation revoked a still-held paid grant", e) + t.Fatal("offchain observation revoked a still-held onchain grant", e) } if _, e = s.db.Exec(`UPDATE lpcc.machine_configs SET bundle=$2,sha256=$3 WHERE node_id=$1`, node, b, digest); e != nil { t.Fatal(e) @@ -355,9 +355,9 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { s := newTestServer(t) - cfg := paidSettings(t, s) - paidNode := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{paidNode: cfg}}, 0); e != nil { + cfg := onchainSettings(t, s) + onchainNode := "lp-aaaaaaaaaaaaaaaa" + if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{onchainNode: cfg}}, 0); e != nil { t.Fatal(e) } a := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -378,7 +378,7 @@ func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { } var meta contract.Metadata json.Unmarshal(files["runtime.json"], &meta) - if meta.Payment.Paid() || strings.Contains(string(files["runtime.json"]), cfg.Recipient) { + if meta.Payment.Onchain() || strings.Contains(string(files["runtime.json"]), cfg.Recipient) { t.Fatal("cross-machine payment delivery") } requireStatus(t, request(t, s, "POST", "/v1/nodes/"+a["node_id"]+"/payment/credentials", b["token"], map[string]any{}), 401) @@ -388,7 +388,7 @@ func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { s := newTestServer(t) - c := paidSettings(t, s) + c := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" errors := make(chan error, 2) for n := range 2 { @@ -413,9 +413,9 @@ func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { } } -func TestUnapprovedPaidStartupCanRepairItsImageButCannotDisable(t *testing.T) { +func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) { s := newTestServer(t) - cfg := paidSettings(t, s) + cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { t.Fatal(e) @@ -441,8 +441,8 @@ func TestUnapprovedPaidStartupCanRepairItsImageButCannotDisable(t *testing.T) { t.Fatal(e) } after := read() - if after.ConfigDigest == before.ConfigDigest || !after.Payment.Paid() || after.PaymentActive || after.Payment.Generation != before.Payment.Generation { - t.Fatal("unapproved paid target could not repair its image under the same payment binding", after) + if after.ConfigDigest == before.ConfigDigest || !after.Payment.Onchain() || after.PaymentActive || after.Payment.Generation != before.Payment.Generation { + t.Fatal("unapproved onchain target could not repair its image under the same payment binding", after) } if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: payment.Offchain()}}, 1); e != nil { t.Fatal(e) @@ -450,14 +450,14 @@ func TestUnapprovedPaidStartupCanRepairItsImageButCannotDisable(t *testing.T) { if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } - if !read().Payment.Paid() { - t.Fatal("failed paid startup bypassed the settlement gate to offchain") + if !read().Payment.Onchain() { + t.Fatal("failed onchain startup bypassed the settlement gate to offchain") } } func TestForcedRetirementCannotUseDesiredOffchainAsSettlementProof(t *testing.T) { s := newTestServer(t) - cfg := paidSettings(t, s) + cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { t.Fatal(e) @@ -474,6 +474,6 @@ func TestForcedRetirementCannotUseDesiredOffchainAsSettlementProof(t *testing.T) } var required bool if e := s.db.QueryRow(`SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&required); e != nil || !required { - t.Fatal("pending disable hid retained paid state", required, e) + t.Fatal("pending disable hid retained onchain state", required, e) } } diff --git a/deploy/README.md b/deploy/README.md index 241d77b..9ef8fe3 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -49,8 +49,8 @@ docker build -f ../runtime/services/Dockerfile.tunnel \ --build-arg RUNTIME_IMAGE=127.0.0.1:63812/controlcenter/runtime@sha256: \ -t 127.0.0.1:63812/controlcenter/connector:staging ../runtime/services docker push 127.0.0.1:63812/controlcenter/connector:staging -# For paid operation, build a compatible Node binary and package its image with -# the Runtime startup wrapper (see docs/paid-operation.md). +# For onchain operation, build a compatible Node binary and package its image with +# the Runtime startup wrapper (see docs/onchain-operation.md). # Set RuntimeImage, RuntimeConnectorImage, and RuntimeNodeImage in config.toml # using the public registry hostname and the digests returned by the pushes. docker compose config --quiet @@ -63,7 +63,7 @@ and node address exclusions. Update `TunnelNodeAddresses` with the public and management addresses of every machine before enrollment; the bootstrap installer's origin firewall remains required. -For fresh managed paid installations, follow [the payment runbook](../docs/paid-operation.md) +For fresh managed onchain installations, follow [the payment runbook](../docs/onchain-operation.md) for the redeemer Compose profile, credential mounts and deployment settings. The deployed image digests and source provenance are recorded in diff --git a/deploy/compose.paid.yaml b/deploy/compose.onchain.yaml similarity index 87% rename from deploy/compose.paid.yaml rename to deploy/compose.onchain.yaml index 2489538..531f156 100644 --- a/deploy/compose.paid.yaml +++ b/deploy/compose.onchain.yaml @@ -1,11 +1,11 @@ -# Fresh paid deployment: combine with compose.yaml and --profile paid. +# Fresh onchain deployment: combine with compose.yaml and --profile onchain. services: redeemer: restart: unless-stopped read_only: true cap_drop: [ALL] security_opt: [no-new-privileges:true] - profiles: [paid] + profiles: [onchain] image: ${LIVEPEER_REDEEMER_IMAGE:?Set a digest-pinned compatible Node image} user: "65532:65532" command: [redeemer, --config, /etc/livepeer/redeemer.toml] diff --git a/deploy/config.example.toml b/deploy/config.example.toml index ac2a9fc..74405ea 100644 --- a/deploy/config.example.toml +++ b/deploy/config.example.toml @@ -35,6 +35,6 @@ TunnelNodeAddresses = [""] DiscoveryRefreshInterval = "5m" DiscoveryMaxFailedRefreshes = 6 -# Enable with compose.paid.yaml after applying deployment-owned payment settings. +# Enable with compose.onchain.yaml after applying deployment-owned payment settings. # PaymentSecretsDir = "/run/payment-rpc" # PaymentWebhookSecretFile = "/run/secrets/payment-webhook-auth" diff --git a/deploy/payments.example.json b/deploy/payments.example.json index 435b0fc..5e04179 100644 --- a/deploy/payments.example.json +++ b/deploy/payments.example.json @@ -4,7 +4,7 @@ "lp-aaaaaaaaaaaaaaaa": { "version": 1, "credential_revision": 1, - "mode": "paid", + "mode": "onchain", "network": "arbitrum-one-mainnet", "chain_id": 42161, "controller": "0xD8E8328501E9645d16Cf49539efC04f734606ee4", diff --git a/docs/acceptance/119-managed-payments.json b/docs/acceptance/119-managed-payments.json index d4440a9..aef72c8 100644 --- a/docs/acceptance/119-managed-payments.json +++ b/docs/acceptance/119-managed-payments.json @@ -28,7 +28,6 @@ }, "catalog": [ { - "name": "paid-echo-persistent", "revision_id": "9a96a95f-ff0d-42b3-8ebb-5c6893ba4adb", "digest": "sha256:2253e9cf61444a3da745db4ca77d3c973378b88f43d50bebfaa357ef79597d05", "price": { @@ -38,7 +37,6 @@ } }, { - "name": "paid-echo-fixed", "revision_id": "e3b5ceb6-cb7f-4e40-b1c6-469f06d2901f", "digest": "sha256:c8482a7f32e1cd6bd56e7a48e5ffc6fc612dc660a34226a5ec51a789d6fa4668", "price": { @@ -116,14 +114,14 @@ } ], "retained-outage-evidence": { - "paid_session_survived_rpc_readiness_loss": true, + "onchain_session_survived_rpc_readiness_loss": true, "protected_diagnostics_reachable": true, "retained_session_stop_succeeded_while_unready": true }, "disable-rollback-evidence": [ { "check": "disable_blocked_by_real_queued_ticket", - "paid_workload_retained": true, + "onchain_workload_retained": true, "submission_grant_retained": true, "sibling_unchanged": true }, @@ -162,7 +160,7 @@ "backpressure-evidence": { "queue_limit": 2, "actual_unsettled": 2, - "paid_mode_retained": true, + "onchain_mode_retained": true, "local_admission_not_ready": true }, "lost-ack-evidence": { @@ -172,7 +170,7 @@ }, "ordinary-retirement-evidence": { "ordinary_removal_blocked_by_actual_unsettled_tickets": true, - "paid_workload_retained": true, + "onchain_workload_retained": true, "submission_grants_retained": true, "completion_not_acknowledged": true }, @@ -284,5 +282,19 @@ }, "unsettled_small_tickets": 5, "payment_drain_complete": false + }, + "evidence_kind": "historical funded run before rebase and onchain terminology revision", + "post_rebase_validation": { + "base_revision": "b45110364d0a9c187c4497f524e3b0b93b4707be", + "mode": "onchain", + "schema_migration": "009_onchain_payments.sql", + "historical_migrations_unchanged": true, + "existing_offchain_bundle_preserved": true, + "postgresql_race_suite": "passed", + "go_vet": "passed", + "ui_browser_tests": 41, + "ui_build": "passed", + "funded_rerun": false, + "existing_onchain_runtime_upgrade_validated": false } } diff --git a/docs/acceptance/119-managed-payments.md b/docs/acceptance/119-managed-payments.md index e23f25a..f18bb52 100644 --- a/docs/acceptance/119-managed-payments.md +++ b/docs/acceptance/119-managed-payments.md @@ -1,4 +1,4 @@ -# Managed paid operation: fresh-install evidence +# Managed onchain operation: fresh-install evidence Date: 2026-11-12. Run: `cc-e2e-1112071043-bcbd`. @@ -7,6 +7,11 @@ acceptance gate remains open: #90's versioned responder, trusted verifier and collection/report contract are still open work. The nonce-echo fixture used here checks transport and execution correctness; it is not that benchmark verifier. +This is historical evidence for the recorded source hashes, before the branch +was rebased and its configuration terminology standardized to `onchain`. It is +not a funded rerun of the revised branch. Catalog revision IDs and digests retain +their original values; nonessential fixture names are omitted from the JSON. + ## Environment and provenance Two fresh `e2-standard-4` CPU workers ran actual K3s, gVisor app workloads and @@ -40,9 +45,9 @@ before registry teardown. on each worker, including kubectl manifest validation. The later Cloudflare tombstone regression passed the tunnel race suite. - Both workers applied payment generation 1 and registered the same catalog - revisions. Actual Node parsed the rendered paid TOML. Failed paid configuration - remained paid/failed and retained the last valid configuration. -- Paid persistent/hourly and single-shot/fixed calls executed ordinary sandboxed + revisions. Actual Node parsed the rendered onchain TOML. Failed onchain configuration + remained onchain/failed and retained the last valid configuration. +- Onchain persistent/hourly and single-shot/fixed calls executed ordinary sandboxed HTTP requests. A verifier-generated nonce was checked in the response. Origin access headers were absent from application requests. - During private RPC loss, the same live Pod became unready while its funded @@ -55,9 +60,9 @@ before registry teardown. - RPC/submission rotation and explicit rollback produced new generations and grants and retained owner-only SQLite state. The disable/rollback cycle left the sibling unchanged. A real - unsettled ticket blocked paid disable; the live paid workload/grant remained. + unsettled ticket blocked onchain disable; the live onchain workload/grant remained. - A queue limit of two with two actual unsettled tickets closed local admission - while preserving paid mode. Restoring capacity restored readiness. + while preserving onchain mode. Restoring capacity restored readiness. - The redeemer durably accepted three ticket identities while six successful acknowledgements were deliberately lost. Retries produced nine HTTP acceptances, three unique stored tickets and degraded-then-healthy remote diff --git a/docs/app-registry.md b/docs/app-registry.md index 6be598f..ec58573 100644 --- a/docs/app-registry.md +++ b/docs/app-registry.md @@ -114,8 +114,8 @@ private `path`, `capacity`, and `price`; paths must be unique and nonnested. Catalog prices remain generic and immutable. Assignment and registration compatibility is evaluated against the target machine's desired and observed Node payment settings. -See [managed paid operation](paid-operation.md) for deployment configuration and -activation. Publishing a price does not activate paid operation on a Node. +See [managed onchain operation](onchain-operation.md) for deployment configuration and +activation. Publishing a price does not activate onchain operation on a Node. ## Catalog API diff --git a/docs/paid-operation.md b/docs/onchain-operation.md similarity index 89% rename from docs/paid-operation.md rename to docs/onchain-operation.md index 0346a8b..a15174e 100644 --- a/docs/paid-operation.md +++ b/docs/onchain-operation.md @@ -1,10 +1,16 @@ -# Managed paid operation +# Managed onchain operation This workflow targets fresh Control Center databases and fresh Runtime installations. The app catalog's exact decimal prices are the registration inputs. Deployment configuration owns Node payment infrastructure; the machine UI inspects its state. Offchain Node advertises free service even if a catalog revision has a positive quote. -Paid Node requires positive USD prices with `hour` or `fixed` units for every app. +Onchain Node requires positive USD prices with `hour` or `fixed` units for every app. + +Payment persistence is introduced by additive migration `009_onchain_payments.sql`; +historical migrations remain unchanged. Applying it preserves existing machine +records and stored bundles, and unconfigured machines stay offchain. The funded +acceptance below covers fresh installations; it does not establish Runtime or +payment-storage upgrade compatibility for existing onchain installations. ## Fresh setup @@ -44,7 +50,7 @@ Create owner-only files readable by container UID 65532: Set `PaymentSecretsDir` and `PaymentWebhookSecretFile` in the API deployment configuration as shown in `deploy/config.example.toml`. Start the fresh deployment -with `docker compose -f compose.yaml -f compose.paid.yaml --profile paid up -d`. +with `docker compose -f compose.yaml -f compose.onchain.yaml --profile onchain up -d`. Only `POST /redemption/tickets` is exposed through the verified HTTPS API ingress. Keep the redeemer's raw listener, metrics and webhook inaccessible externally. The same-host deployment accepts host compromise as a trust-boundary limitation. @@ -60,7 +66,7 @@ controlcenter payments apply --config /etc/controlcenter/config.toml \ ``` The command prints the current deployment revision. Use that revision on the next -apply. Imports are complete snapshots: retain all currently paid machine entries, +apply. Imports are complete snapshots: retain all currently onchain machine entries, or explicitly set one to `{"version":1,"mode":"offchain"}`. Do not supply generated `generation` values. An identical retry is a no-op, including after a lost response. Stale changes conflict. Settings, generations and audit records commit together. API processes consume @@ -103,7 +109,7 @@ a new process obtains a new grant. Keep immutable RPC secret versions available. ## Failure, retirement and recovery -Configuration application, local paid readiness and remote redemption handoff are +Configuration application, local onchain readiness and remote redemption handoff are separate observations. A successful `/readyz`, download or empty worker pass does not prove authorized handoff. `unverified` means no current successful handoff has been observed; `degraded` reflects submission failures. Node's durable queue and @@ -112,8 +118,8 @@ backpressure continue governing redemption outages. Disable, destination change and ordinary removal wait for app drain and fresh successful evidence of zero unsettled tickets. Missing, stale or incomplete queue evidence blocks completion. Drain expiry requires the existing audited retry. -Normal removal retains the paid workload and credentials while settling tickets. -An observed offchain replacement revokes the previous paid workload's submission +Normal removal retains the onchain workload and credentials while settling tickets. +An observed offchain replacement revokes the previous onchain workload's submission grants after the required drain completes. Forced removal or account deletion revokes submission grants immediately. Already @@ -125,7 +131,7 @@ chain settings before resuming submission. Once the restored Node has reported a zero-unsettled observation, apply the same desired snapshot with `--acknowledge-recovery ` and the current expected revision. This records an explicit recovery audit event and clears the recovery-required flag. -After a paid Node has initialized successfully, credential delivery requires its +After a onchain Node has initialized successfully, credential delivery requires its existing payment database; a missing database fails startup instead of silently creating a replacement. Do not discard databases to clear an error or reinterpret retained state on a different chain or recipient. @@ -144,7 +150,7 @@ before publishing its new protected routes. Use two freshly installed CPU machines with different infrastructure settings and unchanged shared catalog revisions. Record component commits/digests, desired and observed generations, bounded spending/runtime limits, and redacted outcomes. -Exercise paid discovery/admission/execution/accounting, winning-ticket handoff, +Exercise onchain discovery/admission/execution/accounting, winning-ticket handoff, lost acknowledgements, Node/redeemer restarts, webhook/redemption outages and backpressure, rotation, ordinary/forced retirement and retained-state recovery. Verify signing-key isolation, private endpoint reachability and blocked app access. diff --git a/runtime/appreconciler/controller.go b/runtime/appreconciler/controller.go index f93ac79..d5683db 100644 --- a/runtime/appreconciler/controller.go +++ b/runtime/appreconciler/controller.go @@ -51,7 +51,7 @@ func (c *Controller) hooks() OwnerHooks { Eligibility: func(r Registration) (bool, bool) { member, ready := c.Journal.Eligibility(r) state := c.Journal.View() - if state.Metadata.Payment.Paid() && !state.Metadata.PaymentActive { + if state.Metadata.Payment.Onchain() && !state.Metadata.PaymentActive { ready = false } return member, ready && c.Probes != nil && c.Probes.Ready(r.InstanceID, r.PodUID) @@ -347,7 +347,7 @@ func (c *Controller) Tick(ctx context.Context) error { }) for _, g := range groups { a := assignments[g.RevisionID] - if s.Metadata.Payment.Paid() && !s.Metadata.PaymentActive { + if s.Metadata.Payment.Onchain() && !s.Metadata.PaymentActive { s.AssignmentReasons[a.RevisionID] = "payment_pending" continue } @@ -606,14 +606,14 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo continue } pod, exists := view.Pods[i.Name] - if s.Metadata.Payment.Paid() && !s.Metadata.PaymentActive && i.AppID == "" { + if s.Metadata.Payment.Onchain() && !s.Metadata.PaymentActive && i.AppID == "" { continue } if i.AppID == "" && (!exists || pod.UID != i.PodUID || pod.Deleting || pod.Phase != "Running") { continue } signalOK := i.Definition.Lifecycle.StopSignal == nil || (exists && pod.StopSignal == *i.Definition.Lifecycle.StopSignal) - if (!s.Metadata.Payment.Paid() || s.Metadata.PaymentActive) && i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { + if (!s.Metadata.Payment.Onchain() || s.Metadata.PaymentActive) && i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { for n := range registrations { registrations[n].Options.Status = "ready" } diff --git a/runtime/appreconciler/input.go b/runtime/appreconciler/input.go index 420f3e0..8d8d92d 100644 --- a/runtime/appreconciler/input.go +++ b/runtime/appreconciler/input.go @@ -72,7 +72,7 @@ func (s Source) Read(ctx context.Context) (Input, error) { if err != nil || identity.Epoch != m.Epoch || identity.CredentialVersion != m.CredentialVersion { return input, errors.New("management_enrollment") } - if m.Payment.Paid() && m.PaymentActive { + if m.Payment.Onchain() && m.PaymentActive { m.PaymentActive = s.paymentActive(ctx, m) } p, err := appbundle.Read(files, m) diff --git a/runtime/appreconciler/payment_test.go b/runtime/appreconciler/payment_test.go index 8d5fcee..36319a4 100644 --- a/runtime/appreconciler/payment_test.go +++ b/runtime/appreconciler/payment_test.go @@ -19,7 +19,7 @@ import ( type paymentTransport func(*http.Request) (*http.Response, error) func (f paymentTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } -func TestPaidAdmissionRequiresLiveMatchingNode(t *testing.T) { +func TestOnchainAdmissionRequiresLiveMatchingNode(t *testing.T) { digest := strings.Repeat("a", 64) pods := 1 ready := 200 @@ -55,13 +55,13 @@ func TestPaidAdmissionRequiresLiveMatchingNode(t *testing.T) { t.Fatal("ambiguous Node incarnation admitted") } } -func TestPendingPaidTargetDoesNotAllocateOrAdmit(t *testing.T) { +func TestPendingOnchainTargetDoesNotAllocateOrAdmit(t *testing.T) { c, input, cluster, owner, _, _ := fixtureController(t) - input.value.Metadata.Payment = payment.Config{Mode: "paid", Generation: 1} + input.value.Metadata.Payment = payment.Config{Mode: "onchain", Generation: 1} input.value.Metadata.PaymentActive = false tick(t, c) if len(c.Journal.View().Instances) != 0 { - t.Fatal("pending paid target allocated work") + t.Fatal("pending onchain target allocated work") } input.value.Metadata.PaymentActive = true registerApps(t, c, cluster) diff --git a/runtime/httpsource/source.go b/runtime/httpsource/source.go index 016d25e..31fe6e4 100644 --- a/runtime/httpsource/source.go +++ b/runtime/httpsource/source.go @@ -384,7 +384,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr ready = ready && k3sVersion == m.UpgradeVersion } reason := "applying" - if m.Payment.Paid() && applied && actual == m.ConfigDigest && !ready { + if m.Payment.Onchain() && applied && actual == m.ConfigDigest && !ready { reason = "payment_not_ready" } if ready { diff --git a/runtime/orchestrator/integration.go b/runtime/orchestrator/integration.go index 63a228f..b065183 100644 --- a/runtime/orchestrator/integration.go +++ b/runtime/orchestrator/integration.go @@ -144,7 +144,7 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { bad := errors.New("payment_credential_unavailable") m, ok := i.Desired() - if !ok || i.AllowHTTP || !m.Payment.Paid() || m.TerminalCleanup || m.PaymentCredentialsRef != "/v1/nodes/"+m.NodeID+"/payment/credentials" { + if !ok || i.AllowHTTP || !m.Payment.Onchain() || m.TerminalCleanup || m.PaymentCredentialsRef != "/v1/nodes/"+m.NodeID+"/payment/credentials" { return Grant{}, bad } before, e := os.ReadFile(i.TokenFile) diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go index 1831279..cf20446 100644 --- a/runtime/orchestrator/integration_test.go +++ b/runtime/orchestrator/integration_test.go @@ -36,7 +36,7 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) dir := t.TempDir() token := filepath.Join(dir, "token") os.WriteFile(token, []byte("machine-secret"), 0600) - m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Payment: payment.Config{Mode: "paid", Generation: 2}, PaymentCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/payment/credentials"} + m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Payment: payment.Config{Mode: "onchain", Generation: 2}, PaymentCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/payment/credentials"} l := Launch{PodName: "orchestrator-test", PodUID: "uid", LaunchID: strings.Repeat("b", 32), ProcessID: strings.Repeat("c", 64)} i := &Integration{TokenFile: token, StateFile: filepath.Join(dir, "grant.json"), Desired: func() (contract.Metadata, bool) { return m, true }} i.Kube = kubeFunc(func(_ context.Context, _, p string, _ any, out any) error { diff --git a/runtime/orchestrator/observation.go b/runtime/orchestrator/observation.go index 14bbc9d..5ef8df8 100644 --- a/runtime/orchestrator/observation.go +++ b/runtime/orchestrator/observation.go @@ -16,7 +16,7 @@ import ( func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, ready bool, podUID string) *payment.Observation { o := &payment.Observation{Generation: m.Payment.Generation, Mode: m.Payment.Mode, PodUID: podUID, Applied: applied, Ready: ready, Handoff: "unverified"} - if !m.Payment.Paid() { + if !m.Payment.Onchain() { return o } i.mu.Lock() diff --git a/runtime/payment/config.go b/runtime/payment/config.go index d4df60d..922d522 100644 --- a/runtime/payment/config.go +++ b/runtime/payment/config.go @@ -36,8 +36,8 @@ type Config struct { MaxTicketsPerRecipient int `json:"max_tickets_per_recipient,omitempty"` } -func Offchain() Config { return Config{Version: 1, Mode: "offchain"} } -func (c Config) Paid() bool { return c.Mode == "paid" } +func Offchain() Config { return Config{Version: 1, Mode: "offchain"} } +func (c Config) Onchain() bool { return c.Mode == "onchain" } var Address = regexp.MustCompile(`^0x[0-9a-fA-F]{40}$`) var SecretRef = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$`) @@ -57,8 +57,8 @@ func (c Config) Validate() error { } return nil } - if c.CredentialRevision == 0 || c.ChainID > uint64(^uint64(0)>>1) || !c.Paid() || (c.Network != "arbitrum-one-mainnet" && c.Network != "custom") || c.ChainID == 0 || (c.Network == "arbitrum-one-mainnet" && c.ChainID != 42161) || !validAddress(c.Controller) || !validAddress(c.Recipient) || !SecretRef.MatchString(c.RPCSecret) { - return errors.New("paid mode requires a supported network, chain/controller, recipient, versioned RPC secret, and positive credential_revision") + if c.CredentialRevision == 0 || c.ChainID > uint64(^uint64(0)>>1) || !c.Onchain() || (c.Network != "arbitrum-one-mainnet" && c.Network != "custom") || c.ChainID == 0 || (c.Network == "arbitrum-one-mainnet" && c.ChainID != 42161) || !validAddress(c.Controller) || !validAddress(c.Recipient) || !SecretRef.MatchString(c.RPCSecret) { + return errors.New("onchain mode requires a supported network, chain/controller, recipient, versioned RPC secret, and positive credential_revision") } u, e := url.Parse(c.RedeemerURL) if len(c.RedeemerURL) > 2048 || e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || u.RawPath != "" { @@ -120,7 +120,7 @@ func Grant(s string) (netip.Addr, uint16, error) { func (c Config) Compatible(d schema.DefinitionV1) error { mode := schema.Offchain - if c.Paid() { + if c.Onchain() { mode = schema.Onchain } return schema.ValidatePolicy(d, mode) diff --git a/runtime/payment/config_test.go b/runtime/payment/config_test.go index a727130..130eefe 100644 --- a/runtime/payment/config_test.go +++ b/runtime/payment/config_test.go @@ -6,16 +6,16 @@ import ( ) func validConfig() Config { - return Config{Version: 1, CredentialRevision: 1, Mode: "paid", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} + return Config{Version: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} } -func TestCompletePaidConfigurationAndExplicitOffchain(t *testing.T) { +func TestCompleteOnchainConfigurationAndExplicitOffchain(t *testing.T) { if e := validConfig().Validate(); e != nil { t.Fatal(e) } if e := Offchain().Validate(); e != nil { t.Fatal(e) } - for name, mutate := range map[string]func(*Config){"missing recipient": func(c *Config) { c.Recipient = "" }, "mode only": func(c *Config) { *c = Config{Version: 1, Mode: "paid"} }, "empty destination query": func(c *Config) { c.RedeemerURL += "?" }, "insecure destination": func(c *Config) { c.RedeemerURL = "http://redeemer.example" }, "inline destination secret": func(c *Config) { c.RedeemerURL = "https://secret@redeemer.example" }, "invalid winning probability": func(c *Config) { c.TicketWinProb = "0" }, "two rate policies": func(c *Config) { c.ETHUSDFeed = c.Controller; c.PriceMaxAge = "1h" }, "broad network": func(c *Config) { c.RedeemerGrants = []string{"10.0.0.0/8"} }, "wrong chain": func(c *Config) { c.Network = "arbitrum-one-mainnet" }, "offchain retains payment inputs": func(c *Config) { c.Mode = "offchain" }, "overflow": func(c *Config) { c.ChainID = ^uint64(0) }} { + for name, mutate := range map[string]func(*Config){"missing recipient": func(c *Config) { c.Recipient = "" }, "mode only": func(c *Config) { *c = Config{Version: 1, Mode: "onchain"} }, "empty destination query": func(c *Config) { c.RedeemerURL += "?" }, "insecure destination": func(c *Config) { c.RedeemerURL = "http://redeemer.example" }, "inline destination secret": func(c *Config) { c.RedeemerURL = "https://secret@redeemer.example" }, "invalid winning probability": func(c *Config) { c.TicketWinProb = "0" }, "two rate policies": func(c *Config) { c.ETHUSDFeed = c.Controller; c.PriceMaxAge = "1h" }, "broad network": func(c *Config) { c.RedeemerGrants = []string{"10.0.0.0/8"} }, "wrong chain": func(c *Config) { c.Network = "arbitrum-one-mainnet" }, "offchain retains payment inputs": func(c *Config) { c.Mode = "offchain" }, "overflow": func(c *Config) { c.ChainID = ^uint64(0) }} { t.Run(name, func(t *testing.T) { c := validConfig() mutate(&c) diff --git a/schema/validate.go b/schema/validate.go index d9d10aa..d79bd6f 100644 --- a/schema/validate.go +++ b/schema/validate.go @@ -167,12 +167,12 @@ func ValidatePolicy(d DefinitionV1, mode PaymentMode) error { if mode != Offchain && mode != Onchain { e.add("price", "Unknown target Node payment mode.") } else if mode == Onchain && len(d.Apps) == 0 && d.Price.Amount == "0" { - e.add("price.amount", "Paid Node assignments require an explicit positive price.") + e.add("price.amount", "Onchain Node assignments require an explicit positive price.") } if mode == Onchain { for n, o := range d.Apps { if o.Price.Amount == "0" { - e.add(fmt.Sprintf("apps[%d].price.amount", n), "Paid Node apps require a positive price.") + e.add(fmt.Sprintf("apps[%d].price.amount", n), "Onchain Node apps require a positive price.") } } } diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index e7e5ea6..df113dc 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -19,7 +19,7 @@ export function machineStatusSummary(machine: { terminal?: boolean; report_state } const reasons: Record = { - payment_not_ready: 'Paid Node is not ready; inspect credential delivery, retained payment state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', + payment_not_ready: 'Onchain Node is not ready; inspect credential delivery, retained payment state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', payment_pending: 'Waiting for the target payment configuration', payment_incompatible: 'App price is incompatible with the target payment mode', payment_drain_pending: 'Waiting for payment settlement', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', } function reason(code?: string) { return code ? reasons[code] || code.replaceAll('_', ' ') : '' } @@ -87,7 +87,7 @@ export function MachineStatus({ session, machine, authorityFailure }: { session:

Payment operation

Desired: {view.payment.desired.mode} · generation {view.payment.desired.generation}. Delivered generation: {view.payment.delivered_generation}.

{view.payment.desired.recipient &&

Recipient: {view.payment.desired.recipient} · {view.payment.desired.network}

} -

Configuration: {fresh(runtime) && runtime?.payment?.applied ? `applied generation ${runtime.payment.generation}` : 'pending or unobserved'}. Local paid admission: {fresh(runtime) && runtime?.payment?.mode === 'paid' && runtime.payment.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.payment?.handoff || 'unverified' : 'unverified'}.

+

Configuration: {fresh(runtime) && runtime?.payment?.applied ? `applied generation ${runtime.payment.generation}` : 'pending or unobserved'}. Local onchain admission: {fresh(runtime) && runtime?.payment?.mode === 'onchain' && runtime.payment.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.payment?.handoff || 'unverified' : 'unverified'}.

{fresh(runtime) && runtime?.payment?.mode === 'offchain' &&

Effective service is free; catalog registration quotes are retained.

} {view.payment.recovery_required &&

Payment recovery required. Retained tickets have not been confirmed drained.

} } diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index 1766db1..9908cfd 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -228,13 +228,13 @@ test('expired inventory preserves its unverified source-version explanation', as await expect(page.getByText('Retained inventory has no confirmation for the current source version', { exact: false })).toBeVisible() }) -test('paid readiness stays separate from handoff and retirement recovery', async ({ page }) => { +test('onchain readiness stays separate from handoff and retirement recovery', async ({ page }) => { await page.clock.install() const state = await setup(page, false) - state.view.payment = { desired: { mode: 'paid', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } - state.view.components[0].payment = { generation: 3, mode: 'paid', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } + state.view.payment = { desired: { mode: 'onchain', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } + state.view.components[0].payment = { generation: 3, mode: 'onchain', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } await page.clock.fastForward(5100) - await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Local paid admission: ready') + await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Local onchain admission: ready') await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Remote handoff: degraded') state.view.payment.recovery_required = true await page.clock.fastForward(5100) From b08f00470b51115c56e6338de50cbef47971d1a5 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 06:48:48 -0800 Subject: [PATCH 07/15] Remove existing-installation compatibility coverage and allowance --- .../controlplane/payment_migration_test.go | 97 ------------------- docs/acceptance/119-managed-payments.json | 4 +- docs/onchain-operation.md | 6 -- runtime/appreconciler/controller_test.go | 3 +- runtime/httpsource/source_test.go | 5 +- runtime/transport/client.go | 6 +- 6 files changed, 8 insertions(+), 113 deletions(-) delete mode 100644 api/internal/controlplane/payment_migration_test.go diff --git a/api/internal/controlplane/payment_migration_test.go b/api/internal/controlplane/payment_migration_test.go deleted file mode 100644 index a4a6beb..0000000 --- a/api/internal/controlplane/payment_migration_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package controlplane - -import ( - "bytes" - "io/fs" - "strings" - "testing" - "testing/fstest" - - "github.com/livepeer/control-center/api/internal/controlplane/payments" - "github.com/livepeer/control-center/api/internal/migrations" - "github.com/livepeer/control-center/api/internal/testdb" - "github.com/livepeer/control-center/runtime/payment" -) - -func TestPaymentMigrationPreservesExistingOffchainMachine(t *testing.T) { - db := testdb.Open(t) - files, err := fs.Sub(MigrationFiles, "migrations") - if err != nil { - t.Fatal(err) - } - prior := fstest.MapFS{} - entries, err := fs.ReadDir(files, ".") - if err != nil { - t.Fatal(err) - } - for _, entry := range entries { - if entry.Name() >= "009_" { - continue - } - data, err := fs.ReadFile(files, entry.Name()) - if err != nil { - t.Fatal(err) - } - prior[entry.Name()] = &fstest.MapFile{Data: data} - } - if err := migrations.Up(t.Context(), db, prior); err != nil { - t.Fatal(err) - } - // These are the hashes already recorded by main, not hashes recomputed from - // this branch. Editing either historical migration must reject this upgrade. - if _, err := db.Exec(`UPDATE lpcc.migrations SET sha256=CASE version - WHEN 1 THEN '3faa2618112eb2080dac3cf9e8da1dbead8460e2c2c0b361a33c8c869ea46951' - WHEN 7 THEN 'ef717f935c921d5f9f5fd683e2bd3643e275fc273f5f5f8abf4ac3efcb30d23c' - END WHERE version IN (1,7)`); err != nil { - t.Fatal(err) - } - const node = "lp-aaaaaaaaaaaaaaaa" - const bundle = "retained pre-payment bundle" - if _, err := db.Exec(`INSERT INTO auth.users(id,email) VALUES($1,'existing@example.invalid')`, ownerA); err != nil { - t.Fatal(err) - } - if _, err := db.Exec(`INSERT INTO lpcc.machines(node_id,fingerprint,owner_id,hostname,install_dir,k3s_version) - VALUES($1,$2,$3,'existing','/srv/livepeer','v1.37.2+k3s1')`, node, strings.Repeat("a", 64), ownerA); err != nil { - t.Fatal(err) - } - if _, err := db.Exec(`INSERT INTO lpcc.machine_configs(node_id,bundle,sha256) VALUES($1,$2,$3)`, node, []byte(bundle), strings.Repeat("b", 64)); err != nil { - t.Fatal(err) - } - if err := Migrate(t.Context(), db); err != nil { - t.Fatal(err) - } - config, err := payments.Load(t.Context(), db, node) - if err != nil || config.Mode != "offchain" || config.Generation != 0 { - t.Fatal("existing machine acquired payment settings", config, err) - } - var retained []byte - if err := db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&retained); err != nil || !bytes.Equal(retained, []byte(bundle)) { - t.Fatal("migration changed the existing bundle", err) - } - // The replacement retirement trigger must also work for existing machines - // without payment records, retaining the same pre-upgrade bundle. - if _, err := db.Exec(`DELETE FROM lpcc.machines WHERE node_id=$1`, node); err != nil { - t.Fatal(err) - } - if err := db.QueryRow(`SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1`, node).Scan(&retained); err != nil || !bytes.Equal(retained, []byte(bundle)) { - t.Fatal("retirement lost the existing bundle", err) - } -} - -func TestPaymentMigrationRollbackPreservesPaymentHistory(t *testing.T) { - s := newTestServer(t) - config := onchainSettings(t, s) - if _, err := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{"lp-aaaaaaaaaaaaaaaa": config}}, 0); err != nil { - t.Fatal(err) - } - files, err := fs.Sub(MigrationFiles, "migrations") - if err != nil { - t.Fatal(err) - } - if err := migrations.Down(t.Context(), s.db, files); err == nil || !strings.Contains(err.Error(), "retain payment schema") { - t.Fatal("rollback did not protect payment history", err) - } - if count(t, s, `SELECT count(*) FROM lpcc.payment_versions`) != 1 { - t.Fatal("rollback discarded payment history") - } -} diff --git a/docs/acceptance/119-managed-payments.json b/docs/acceptance/119-managed-payments.json index aef72c8..b30aed3 100644 --- a/docs/acceptance/119-managed-payments.json +++ b/docs/acceptance/119-managed-payments.json @@ -289,12 +289,10 @@ "mode": "onchain", "schema_migration": "009_onchain_payments.sql", "historical_migrations_unchanged": true, - "existing_offchain_bundle_preserved": true, "postgresql_race_suite": "passed", "go_vet": "passed", "ui_browser_tests": 41, "ui_build": "passed", - "funded_rerun": false, - "existing_onchain_runtime_upgrade_validated": false + "funded_rerun": false } } diff --git a/docs/onchain-operation.md b/docs/onchain-operation.md index a15174e..b58441e 100644 --- a/docs/onchain-operation.md +++ b/docs/onchain-operation.md @@ -6,12 +6,6 @@ configuration owns Node payment infrastructure; the machine UI inspects its stat Offchain Node advertises free service even if a catalog revision has a positive quote. Onchain Node requires positive USD prices with `hour` or `fixed` units for every app. -Payment persistence is introduced by additive migration `009_onchain_payments.sql`; -historical migrations remain unchanged. Applying it preserves existing machine -records and stored bundles, and unconfigured machines stay offchain. The funded -acceptance below covers fresh installations; it does not establish Runtime or -payment-storage upgrade compatibility for existing onchain installations. - ## Fresh setup Build Node with the redeemer authorization webhook and `RedeemerHeadersFile` support. diff --git a/runtime/appreconciler/controller_test.go b/runtime/appreconciler/controller_test.go index a615c69..31706b4 100644 --- a/runtime/appreconciler/controller_test.go +++ b/runtime/appreconciler/controller_test.go @@ -20,6 +20,7 @@ import ( "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" "github.com/livepeer/control-center/runtime/internal/testutil" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/runtime/transport" "github.com/livepeer/control-center/schema" runner "github.com/livepeer/golang-runner" @@ -42,7 +43,7 @@ func (i *testInputs) set(t *testing.T, set schema.AppAssignmentSetV1) { if err != nil { t.Fatal(err) } - i.value = Input{Metadata: contract.Metadata{NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} + i.value = Input{Metadata: contract.Metadata{Payment: payment.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} } type testCluster struct { diff --git a/runtime/httpsource/source_test.go b/runtime/httpsource/source_test.go index 290460a..7bf8f22 100644 --- a/runtime/httpsource/source_test.go +++ b/runtime/httpsource/source_test.go @@ -19,6 +19,7 @@ import ( "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" "github.com/livepeer/control-center/runtime/internal/testutil" + "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/runtime/transport" ) @@ -200,7 +201,7 @@ type sourceFixture struct { func newFixture(t *testing.T) *sourceFixture { t.Helper() set := testutil.Assignment(t) - f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} + f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{Payment: payment.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() @@ -483,7 +484,7 @@ func TestAppOnlyApplicationReportsActualAppliedArchive(t *testing.T) { func TestComponentComparisonCannotBorrowCrossEnrollmentOrCorruptEvidence(t *testing.T) { s := &Source{Store: artifact.Store{Directory: t.TempDir()}} cache := func(epoch, node, connector string) string { - m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} + m := contract.Metadata{Payment: payment.Offchain(), NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} return cacheBundle(t, s.Store, m, map[string][]byte{"system/node/kustomization.yaml": []byte(node), "system/connector/kustomization.yaml": []byte(connector)}) } old := cache("11111111-1111-4111-8111-111111111111", "same node", "old connector") diff --git a/runtime/transport/client.go b/runtime/transport/client.go index 0d38eab..8593e84 100644 --- a/runtime/transport/client.go +++ b/runtime/transport/client.go @@ -144,10 +144,8 @@ func ReadMetadata(b []byte) (contract.Metadata, error) { if len(b) > 16384 || Decode(b, &m) != nil || !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(m.NodeID) || m.Generation < 1 || m.CredentialVersion < 1 || !epochPattern.MatchString(m.Epoch) || m.BundleFormat != contract.BundleFormat { return m, errors.New("metadata_invalid") } - if m.Payment.Version != 0 { - if m.Payment.Validate() != nil { - return m, errors.New("metadata_payment_invalid") - } + if m.Payment.Validate() != nil { + return m, errors.New("metadata_payment_invalid") } return m, nil } From 691b9ae28637e02a92fe2e6b9ada3ab9d2ac5446 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 07:50:34 -0800 Subject: [PATCH 08/15] Consolidate onchain state and operational documentation --- README.md | 3 +- api/cmd/controlcenter/main.go | 2 +- api/cmd/controlcenter/main_test.go | 14 +- api/config.example.toml | 6 +- .../administrator_database_test.go | 2 +- api/internal/controlplane/assignments_test.go | 2 +- api/internal/controlplane/config.go | 6 +- .../controlplane/machine_credentials.go | 2 +- api/internal/controlplane/machineconfig.go | 7 +- .../controlplane/machineconfig/apps.go | 8 +- .../controlplane/machineconfig/bundle.go | 20 +- .../controlplane/machineconfig/manager.go | 18 +- .../machineconfig/observations.go | 6 +- .../machineconfig/{payment.go => onchain.go} | 30 +- .../{payment_test.go => onchain_test.go} | 38 +-- .../controlplane/machineconfig/reports.go | 6 +- .../controlplane/machineconfig/rollout.go | 56 ++-- .../controlplane/machineconfig/runtime.go | 16 +- .../controlplane/machineconfig/system.go | 4 +- .../controlplane/machineconfig/types.go | 16 +- .../controlplane/migrations/009_onchain.sql | 70 ++++ .../migrations/009_onchain_payments.sql | 68 ---- api/internal/controlplane/observed_state.go | 31 +- ..._credentials.go => onchain_credentials.go} | 46 +-- ...ayment_settings.go => onchain_settings.go} | 110 ++++--- .../{payment_test.go => onchain_test.go} | 159 +++++----- api/internal/controlplane/payments/store.go | 31 -- api/internal/controlplane/registry_store.go | 3 +- api/internal/controlplane/server.go | 2 +- deploy/README.md | 39 ++- deploy/compose.onchain.yaml | 8 +- deploy/config.example.toml | 6 +- ...ents.example.json => onchain.example.json} | 0 docs/acceptance/119-managed-payments.json | 298 ------------------ docs/acceptance/119-managed-payments.md | 124 -------- docs/app-registry.md | 4 +- docs/development.md | 4 + docs/fleet-discovery.md | 10 +- docs/machine-status.md | 9 +- docs/machine-tunnels.md | 12 +- docs/onchain-operation.md | 170 ---------- docs/operations.md | 34 ++ runtime/README.md | 10 +- runtime/appreconciler/controller.go | 14 +- runtime/appreconciler/controller_test.go | 4 +- runtime/appreconciler/input.go | 8 +- .../{payment_test.go => onchain_test.go} | 26 +- runtime/cmd/livepeer-runtime/main.go | 8 +- runtime/contract/contract.go | 8 +- runtime/httpsource/source.go | 12 +- runtime/httpsource/source_test.go | 6 +- runtime/{payment => onchain}/config.go | 14 +- runtime/{payment => onchain}/config_test.go | 6 +- runtime/orchestrator/integration.go | 24 +- runtime/orchestrator/integration_test.go | 28 +- runtime/orchestrator/observation.go | 10 +- runtime/orchestrator/process.go | 28 +- runtime/transport/client.go | 6 +- runtime/transport/client_test.go | 4 +- schema/validate.go | 4 +- ui/src/catalog.tsx | 2 +- ui/src/machine-status.tsx | 24 +- ui/tests/machine-status.spec.ts | 16 +- 63 files changed, 591 insertions(+), 1171 deletions(-) rename api/internal/controlplane/machineconfig/{payment.go => onchain.go} (77%) rename api/internal/controlplane/machineconfig/{payment_test.go => onchain_test.go} (80%) create mode 100644 api/internal/controlplane/migrations/009_onchain.sql delete mode 100644 api/internal/controlplane/migrations/009_onchain_payments.sql rename api/internal/controlplane/{payment_credentials.go => onchain_credentials.go} (72%) rename api/internal/controlplane/{payment_settings.go => onchain_settings.go} (58%) rename api/internal/controlplane/{payment_test.go => onchain_test.go} (66%) delete mode 100644 api/internal/controlplane/payments/store.go rename deploy/{payments.example.json => onchain.example.json} (100%) delete mode 100644 docs/acceptance/119-managed-payments.json delete mode 100644 docs/acceptance/119-managed-payments.md delete mode 100644 docs/onchain-operation.md rename runtime/appreconciler/{payment_test.go => onchain_test.go} (73%) rename runtime/{payment => onchain}/config.go (94%) rename runtime/{payment => onchain}/config_test.go (92%) diff --git a/README.md b/README.md index 09f2ed2..7b5f9b9 100644 --- a/README.md +++ b/README.md @@ -87,10 +87,9 @@ flowchart TB ## Documentation -- [Managed onchain operation](docs/onchain-operation.md): configure fresh deployments and inspect payment readiness. - [App registry](docs/app-registry.md): publish app definitions and assign revisions to machines. - [Fleet discovery](docs/fleet-discovery.md): expose managed orchestrators through an aggregate inventory. - [Machine status](docs/machine-status.md): inspect rollout, configured health, registration, discovery and cleanup evidence. - [Machine ingress](docs/machine-tunnels.md): configure protected tunnels and routing. -- [Operations](docs/operations.md): configure authentication and administrator access. +- [Operations](docs/operations.md): configure authentication, administrator access and onchain operation. - [Development](docs/development.md): run locally, build, and test. diff --git a/api/cmd/controlcenter/main.go b/api/cmd/controlcenter/main.go index 06a08bb..7f56f53 100644 --- a/api/cmd/controlcenter/main.go +++ b/api/cmd/controlcenter/main.go @@ -34,7 +34,7 @@ func command() *cobra.Command { func(ctx context.Context, raw string, _ bool) (*sql.DB, error) { return controlplane.OpenDB(ctx, raw, database.PGPassword) }) - root := boa.Cmd[boa.NoParams]{Use: "controlcenter", Short: "Livepeer machine control plane", SubCmds: []*cobra.Command{serve, migrate, controlplane.PaymentsCommand()}}.ToCobra() + root := boa.Cmd[boa.NoParams]{Use: "controlcenter", Short: "Livepeer machine control plane", SubCmds: []*cobra.Command{serve, migrate, controlplane.OnchainCommand()}}.ToCobra() root.SilenceUsage, root.SilenceErrors = true, true return root } diff --git a/api/cmd/controlcenter/main_test.go b/api/cmd/controlcenter/main_test.go index 828481e..e7e8d4c 100644 --- a/api/cmd/controlcenter/main_test.go +++ b/api/cmd/controlcenter/main_test.go @@ -54,12 +54,12 @@ func TestMigrationConfig(t *testing.T) { } } -func TestPaymentCommandHelpDoesNotExposeSecrets(t *testing.T) { +func TestOnchainCommandHelpDoesNotExposeSecrets(t *testing.T) { cmd := command() var out bytes.Buffer cmd.SetOut(&out) cmd.SetErr(&out) - cmd.SetArgs([]string{"payments", "apply", "--help"}) + cmd.SetArgs([]string{"onchain", "apply", "--help"}) if e := cmd.Execute(); e != nil { t.Fatal(e) } @@ -68,27 +68,27 @@ func TestPaymentCommandHelpDoesNotExposeSecrets(t *testing.T) { t.Fatal("missing flag", flag) } } - for _, secret := range []string{"--payment-webhook-secret ", "--pg-password "} { + for _, secret := range []string{"--onchain-webhook-secret ", "--pg-password "} { if strings.Contains(out.String(), secret) { t.Fatal("secret CLI flag exposed") } } } -func TestPaymentInputRejectsUnknownPricingAndDuplicateFields(t *testing.T) { +func TestOnchainInputRejectsUnknownPricingAndDuplicateFields(t *testing.T) { t.Setenv("PG_CONNSTR", "postgres://unused.invalid/no-network") for _, body := range []string{ `{"version":1,"machines":{"lp-aaaaaaaaaaaaaaaa":{"version":1,"mode":"offchain","price":"1"}}}`, `{"version":1,"version":1,"machines":{}}`, `{"version":2,"machines":{}}`, } { - path := filepath.Join(t.TempDir(), "payments.json") + path := filepath.Join(t.TempDir(), "onchain.json") if e := os.WriteFile(path, []byte(body), 0600); e != nil { t.Fatal(e) } cmd := command() - cmd.SetArgs([]string{"payments", "apply", "--config=", "--file", path, "--expected-revision", "0"}) - if e := cmd.Execute(); e == nil || e.Error() != "invalid payment infrastructure document" { + cmd.SetArgs([]string{"onchain", "apply", "--config=", "--file", path, "--expected-revision", "0"}) + if e := cmd.Execute(); e == nil || e.Error() != "invalid onchain infrastructure document" { t.Fatal("invalid input was not rejected before database access", e) } } diff --git a/api/config.example.toml b/api/config.example.toml index 5a3134f..17cdbee 100644 --- a/api/config.example.toml +++ b/api/config.example.toml @@ -27,8 +27,6 @@ Listen = "localhost:41932" PublicAPIURL = "http://localhost:41932" ConfigReconcileInterval = "1m" -# Registry price validation only; actual Node payment configuration is separate. - # Machine ingress is opt-in. See docs/machine-tunnels.md before enabling it. CloudflareEnabled = false CloudflareIngressApproved = false @@ -57,5 +55,5 @@ RuntimeNodeDrainTimeout = "12h" # 0-12h; 0s ends work immediately # TunnelDrainTimeout = "" # TunnelNodeAddresses = [""] # complete fleet inventory -# PaymentSecretsDir = "/run/payment-rpc" # immutable owner-only versioned files -# PaymentWebhookSecretFile = "/run/secrets/payment-webhook-auth" +# OnchainSecretsDir = "/run/onchain-rpc" # immutable owner-only versioned files +# OnchainWebhookSecretFile = "/run/secrets/onchain-webhook-auth" diff --git a/api/internal/controlplane/administrator_database_test.go b/api/internal/controlplane/administrator_database_test.go index 100c814..e9b9e59 100644 --- a/api/internal/controlplane/administrator_database_test.go +++ b/api/internal/controlplane/administrator_database_test.go @@ -66,7 +66,7 @@ func TestAdministratorDatabasePrivileges(t *testing.T) { if err := db.QueryRow(`SELECT has_table_privilege($1,'lpcc.machine_app_heads','SELECT,INSERT,UPDATE,DELETE'),has_function_privilege($1,'lpcc.remove_machine_apps(text,uuid,text)','EXECUTE')`, role).Scan(&view, &execute); err != nil || view || execute { t.Fatal("assignment view/function access", role, view, execute, err) } - for _, table := range []string{"administrator_grants", "admin_audit_events", "apps", "app_revisions", "app_revision_state", "enrollments", "credential_refreshes", "machine_reports", "machine_states", "access_credentials", "machine_app_versions", "machine_app_deliveries", "machine_app_completions", "machine_app_diagnostics", "payment_revision", "payment_machines", "payment_versions", "payment_secrets", "payment_grants"} { + for _, table := range []string{"administrator_grants", "admin_audit_events", "apps", "app_revisions", "app_revision_state", "enrollments", "credential_refreshes", "machine_reports", "machine_states", "access_credentials", "machine_app_versions", "machine_app_deliveries", "machine_app_completions", "machine_app_diagnostics", "onchain_revision", "onchain_state", "onchain_configs", "onchain_secrets", "onchain_grants"} { var privilege, rls bool var policies int if err := db.QueryRow(`SELECT has_table_privilege($1,$2,'SELECT,INSERT,UPDATE,DELETE')`, role, "lpcc."+table).Scan(&privilege); err != nil || privilege { diff --git a/api/internal/controlplane/assignments_test.go b/api/internal/controlplane/assignments_test.go index a91bd60..aeb56ca 100644 --- a/api/internal/controlplane/assignments_test.go +++ b/api/internal/controlplane/assignments_test.go @@ -517,7 +517,7 @@ func TestAssignmentReportValidationAndProviderBackoff(t *testing.T) { if err != nil { t.Fatal(err) } - // Empty payment, certificate and retirement snapshot migrations can roll back while + // Empty onchain, certificate and retirement snapshot migrations can roll back while // this enrollment is active; assignment history must still be preserved. for range 3 { if err := migrations.Down(t.Context(), s.db, files); err != nil { diff --git a/api/internal/controlplane/config.go b/api/internal/controlplane/config.go index f0721ac..8f00c41 100644 --- a/api/internal/controlplane/config.go +++ b/api/internal/controlplane/config.go @@ -35,9 +35,9 @@ type Params struct { PublicAPIURL string `env:"PUBLIC_API_URL" default:"http://localhost:41932" pattern:"^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*/?$" descr:"API URL reachable from runtime hosts and pods"` SupabaseURL string `env:"SUPABASE_URL" min:"1" descr:"Supabase project URL"` SupabasePublishableKey string `env:"SUPABASE_PUBLISHABLE_KEY" min:"1" descr:"Supabase browser-safe publishable key"` - PaymentSecretsDir string `optional:"true" descr:"Owner-only immutable RPC secret versions directory"` - PaymentWebhookSecret string `secret:"true" optional:"true"` - PaymentWebhookSecretFile string `secretfor:"PaymentWebhookSecret" basepath:"source"` + OnchainSecretsDir string `optional:"true" descr:"Owner-only immutable RPC secret versions directory"` + OnchainWebhookSecret string `secret:"true" optional:"true"` + OnchainWebhookSecretFile string `secretfor:"OnchainWebhookSecret" basepath:"source"` DefaultAdminEmail string `env:"DEFAULT_ADMIN_EMAIL" optional:"true" descr:"Seed a pending administrator email only when no active grants exist"` JWTSigningSecret string `env:"JWT_SIGNING_SECRET" secret:"true" min:"32" descr:"Persistent enrollment signing secret (at least 32 bytes)"` JWTSigningSecretFile string `env:"JWT_SIGNING_SECRET_FILE" secretfor:"JWTSigningSecret" basepath:"source" descr:"File containing the enrollment signing secret"` diff --git a/api/internal/controlplane/machine_credentials.go b/api/internal/controlplane/machine_credentials.go index a92aa79..fb0847d 100644 --- a/api/internal/controlplane/machine_credentials.go +++ b/api/internal/controlplane/machine_credentials.go @@ -245,7 +245,7 @@ func (s *Server) machineStatus(w http.ResponseWriter, r *http.Request) { return } if report.Component == "runtime" && !report.ClockUncertain && !report.ObservedAt.Before(time.Now().Add(-2*time.Minute)) { - if e := s.observePaymentGrant(r.Context(), m, report.Payment, report.ConfigDigest); e != nil { + if e := s.observeOnchainGrant(r.Context(), m, report.Onchain, report.ConfigDigest); e != nil { s.databaseError(w, e) return } diff --git a/api/internal/controlplane/machineconfig.go b/api/internal/controlplane/machineconfig.go index b37b8e2..109c339 100644 --- a/api/internal/controlplane/machineconfig.go +++ b/api/internal/controlplane/machineconfig.go @@ -3,8 +3,7 @@ package controlplane import ( "context" "encoding/json" - "github.com/livepeer/control-center/api/internal/controlplane/payments" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" "github.com/livepeer/control-center/api/internal/controlplane/tunnel" @@ -16,8 +15,8 @@ func exposure(r tunnel.RoutingState) *machineconfig.Exposure { func (s *Server) newConfigurationManager() *machineconfig.Manager { p := s.params return machineconfig.New(machineconfig.Config{APIURL: p.PublicAPIURL, DrainTimeout: p.TunnelDrainTimeout, StatusTTL: p.TunnelStatusTTL, RuntimeImage: p.RuntimeImage, NodeImage: p.RuntimeNodeImage, NodeDrainTimeout: &p.RuntimeNodeDrainTimeout, StopSignals: p.AppStopSignals, Connector: machineconfig.ConnectorConfig{Image: p.RuntimeConnectorImage, NodeAddresses: p.TunnelNodeAddresses}}, machineconfig.Dependencies{DB: s.db, Logger: s.logger, - Payment: func(ctx context.Context, m machineconfig.Machine) (payment.Config, error) { - return payments.Load(ctx, s.db, m.NodeID) + Onchain: func(ctx context.Context, m machineconfig.Machine) (onchain.Config, error) { + return loadOnchain(ctx, s.db, m.NodeID) }, Exposure: func(raw json.RawMessage) (*machineconfig.Exposure, error) { var r tunnel.RoutingState diff --git a/api/internal/controlplane/machineconfig/apps.go b/api/internal/controlplane/machineconfig/apps.go index bd8e077..0c8ed6b 100644 --- a/api/internal/controlplane/machineconfig/apps.go +++ b/api/internal/controlplane/machineconfig/apps.go @@ -33,7 +33,7 @@ func (s *Manager) prepareApps(ctx context.Context, m *Desired, lookupErr error) if err == nil && m.Apps != nil { for _, a := range m.Apps.Entries { if a.Revision != nil && a.Desired == "present" { - if e := m.Payment.Compatible(a.Revision.Definition); e != nil { + if e := m.Onchain.Compatible(a.Revision.Definition); e != nil { err = e break } @@ -122,9 +122,9 @@ func addManagedApps(files map[string][]byte, m Desired) error { } if prior, e := transport.ReadMetadata(m.RetainedFiles["runtime.json"]); e == nil { metadata.ConfigDigest = prior.ConfigDigest - metadata.Payment = prior.Payment - metadata.PaymentCredentialsRef = prior.PaymentCredentialsRef - metadata.PaymentActive = false + metadata.Onchain = prior.Onchain + metadata.OnchainCredentialsRef = prior.OnchainCredentialsRef + metadata.OnchainActive = false // Retained connectors may restart while the backend still authorizes app cleanup. metadata.TunnelID, metadata.TokenGeneration, metadata.ProviderVersion, metadata.ConnectorTokenRef = prior.TunnelID, prior.TokenGeneration, prior.ProviderVersion, prior.ConnectorTokenRef files["runtime.json"], err = json.Marshal(metadata) diff --git a/api/internal/controlplane/machineconfig/bundle.go b/api/internal/controlplane/machineconfig/bundle.go index c6d6669..62246f2 100644 --- a/api/internal/controlplane/machineconfig/bundle.go +++ b/api/internal/controlplane/machineconfig/bundle.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "github.com/livepeer/control-center/runtime/artifact" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "io/fs" "strings" "time" @@ -22,16 +22,16 @@ func Build(m Desired) ([]byte, string, error) { if m.NodeImage != "" && !ValidConnectorImage(m.NodeImage) { return nil, "", fmt.Errorf("Node image is not pinned") } - if m.PaymentError != nil { - return nil, "", m.PaymentError + if m.OnchainError != nil { + return nil, "", m.OnchainError } - if m.Payment.Version == 0 { - m.Payment = payment.Offchain() + if m.Onchain.Version == 0 { + m.Onchain = onchain.Offchain() } - if m.State.HeldOrchestrator != "" && m.State.HeldPayment != "" { - var held payment.Config - if json.Unmarshal([]byte(m.State.HeldPayment), &held) != nil { - return nil, "", fmt.Errorf("invalid held payment identity") + if m.State.HeldOrchestrator != "" && m.State.HeldOnchain != "" { + var held onchain.Config + if json.Unmarshal([]byte(m.State.HeldOnchain), &held) != nil { + return nil, "", fmt.Errorf("invalid held onchain identity") } if held.Version != 0 { if err := held.Validate(); err != nil { @@ -39,7 +39,7 @@ func Build(m Desired) ([]byte, string, error) { } } } - if err := m.Payment.Validate(); err != nil { + if err := m.Onchain.Validate(); err != nil { return nil, "", err } files := map[string][]byte{} diff --git a/api/internal/controlplane/machineconfig/manager.go b/api/internal/controlplane/machineconfig/manager.go index 8c8490c..c4f0eb2 100644 --- a/api/internal/controlplane/machineconfig/manager.go +++ b/api/internal/controlplane/machineconfig/manager.go @@ -7,7 +7,7 @@ import ( "errors" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" "github.com/livepeer/control-center/runtime/artifact" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/schema" "log/slog" "time" @@ -24,7 +24,7 @@ type Config struct { } type Dependencies struct { - Payment func(context.Context, Machine) (payment.Config, error) + Onchain func(context.Context, Machine) (onchain.Config, error) DB *sql.DB Logger *slog.Logger Exposure func(json.RawMessage) (*Exposure, error) @@ -53,20 +53,20 @@ func (s *Manager) Desired(m Machine, state State, exposure *Exposure) Desired { if s.config.Connector.Image != "" { connector.Image = s.config.Connector.Image } - p := payment.Offchain() + p := onchain.Offchain() var err error - if s.deps.Payment != nil { + if s.deps.Onchain != nil { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - p, err = s.deps.Payment(ctx, m) + p, err = s.deps.Onchain(ctx, m) cancel() } - d := Desired{Payment: p, PaymentError: err, Machine: m, State: state, Exposure: exposure, Connector: connector, ControlAPIURL: s.config.APIURL, RuntimeImage: s.config.RuntimeImage, NodeImage: s.config.NodeImage, NodeDrainTimeout: s.config.NodeDrainTimeout, StopSignals: s.config.StopSignals, DrainTimeout: s.drainTimeout()} + d := Desired{Onchain: p, OnchainError: err, Machine: m, State: state, Exposure: exposure, Connector: connector, ControlAPIURL: s.config.APIURL, RuntimeImage: s.config.RuntimeImage, NodeImage: s.config.NodeImage, NodeDrainTimeout: s.config.NodeDrainTimeout, StopSignals: s.config.StopSignals, DrainTimeout: s.drainTimeout()} if p.Onchain() && s.store.DB != nil { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) r, at, e := s.store.Report(ctx, m, "runtime") cancel() - d.PaymentReady = e == nil && !r.ClockUncertain && time.Since(ObservationTime(r, at)) <= s.config.StatusTTL && r.Ready && r.Payment != nil && r.Payment.Ready && r.Payment.Applied && r.Payment.Generation == p.Generation && r.ConfigDigest == Digest(d) + d.OnchainReady = e == nil && !r.ClockUncertain && time.Since(ObservationTime(r, at)) <= s.config.StatusTTL && r.Ready && r.Onchain != nil && r.Onchain.Ready && r.Onchain.Applied && r.Onchain.Generation == p.Generation && r.ConfigDigest == Digest(d) } return d } @@ -216,7 +216,7 @@ func (s *Manager) planManagement(ctx context.Context, m Machine, record *Record) } record.State = before record.HeldOrchestrator = manifest - record.HeldPayment = paymentJSON(old.Payment) + record.HeldOnchain = onchainJSON(old.Onchain) s.holdUpgrade(ctx, m, &record.State) record.RolloutReason = "lifecycle_observation_failed" if old.IngressDigest != "" { @@ -246,7 +246,7 @@ func (s *Manager) plan(ctx context.Context, m Machine, record *Record) (*Exposur return nil, false, e } record.HeldOrchestrator = manifest - record.HeldPayment = paymentJSON(old.Payment) + record.HeldOnchain = onchainJSON(old.Onchain) } if record.Lifecycle == "draining" { done, e := s.removalComplete(ctx, m, &record.State) diff --git a/api/internal/controlplane/machineconfig/observations.go b/api/internal/controlplane/machineconfig/observations.go index f16fa72..61487d2 100644 --- a/api/internal/controlplane/machineconfig/observations.go +++ b/api/internal/controlplane/machineconfig/observations.go @@ -19,18 +19,18 @@ func validCode(s string) bool { return s == "" || statusCode.MatchString(s) } func optionalID(s string) bool { return s == "" || statusID.MatchString(s) } func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) error { - if p := r.Payment; p != nil { + if p := r.Onchain; p != nil { if r.Component != "runtime" || (p.Mode != "onchain" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || p.Unsettled < 0 || p.Unsettled > 10000000 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { return ErrStaleStatus } if p.Applied { meta, _, err := s.applied(ctx, m) - if err != nil || r.ConfigDigest != meta.ConfigDigest || p.Generation != meta.Payment.Generation || p.Mode != meta.Payment.Mode || p.PodUID == "" { + if err != nil || r.ConfigDigest != meta.ConfigDigest || p.Generation != meta.Onchain.Generation || p.Mode != meta.Onchain.Mode || p.PodUID == "" { return ErrStaleStatus } if p.Mode == "onchain" { var known bool - err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.payment_grants WHERE grant_id::text=$1 AND node_id=$2 AND epoch=$3 AND payment_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, m.Epoch, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) + err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.onchain_grants WHERE grant_id::text=$1 AND node_id=$2 AND epoch=$3 AND onchain_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, m.Epoch, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) if err != nil { return err } diff --git a/api/internal/controlplane/machineconfig/payment.go b/api/internal/controlplane/machineconfig/onchain.go similarity index 77% rename from api/internal/controlplane/machineconfig/payment.go rename to api/internal/controlplane/machineconfig/onchain.go index cfc737c..48383f2 100644 --- a/api/internal/controlplane/machineconfig/payment.go +++ b/api/internal/controlplane/machineconfig/onchain.go @@ -9,35 +9,35 @@ import ( "strings" "github.com/BurntSushi/toml" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" ) -func effectivePayment(m Desired) payment.Config { - c := m.Payment - if m.State.HeldOrchestrator != "" && m.State.HeldPayment != "" { - c = payment.Config{} - _ = json.Unmarshal([]byte(m.State.HeldPayment), &c) +func effectiveOnchain(m Desired) onchain.Config { + c := m.Onchain + if m.State.HeldOrchestrator != "" && m.State.HeldOnchain != "" { + c = onchain.Config{} + _ = json.Unmarshal([]byte(m.State.HeldOnchain), &c) } if c.Version == 0 { - c = payment.Offchain() + c = onchain.Offchain() } return c } -func specializePayment(raw string, m Desired) string { +func specializeOnchain(raw string, m Desired) string { if !strings.Contains(raw, " orchestrator.toml: |\n") { return raw } // The Service remains a private route to a live process during dependency loss. raw = strings.Replace(raw, "spec:\n selector:\n app: orchestrator", "spec:\n publishNotReadyAddresses: true\n selector:\n app: orchestrator", 1) - c := m.Payment + c := m.Onchain if !c.Onchain() { return raw } endpoint, _ := url.Parse(c.RedeemerURL) meta, _ := json.Marshal(c) hash := sha256.Sum256(meta) - raw = strings.Replace(raw, "livepeer.io/config-sha256:", fmt.Sprintf("livepeer.io/payment-sha256: '%x'\n livepeer.io/config-sha256:", hash), 1) - settings := map[string]any{"Network": c.Network, "ChainID": c.ChainID, "Controller": c.Controller, "OrchestratorAddress": c.Recipient, "RPCURLFile": "/run/payment/private/rpc", "RedeemerGrants": c.RedeemerGrants, "RedeemerHeadersFile": "/run/payment/private/headers", "RedeemerDB": "/data/payments.sqlite", "TicketFaceValue": c.TicketFaceValue, "TicketWinProb": c.TicketWinProb, "MaxPendingTickets": c.MaxPendingTickets, "MaxTicketsPerRecipient": c.MaxTicketsPerRecipient} + raw = strings.Replace(raw, "livepeer.io/config-sha256:", fmt.Sprintf("livepeer.io/onchain-sha256: '%x'\n livepeer.io/config-sha256:", hash), 1) + settings := map[string]any{"Network": c.Network, "ChainID": c.ChainID, "Controller": c.Controller, "OrchestratorAddress": c.Recipient, "RPCURLFile": "/run/onchain/private/rpc", "RedeemerGrants": c.RedeemerGrants, "RedeemerHeadersFile": "/run/onchain/private/headers", "RedeemerDB": "/data/onchain.sqlite", "TicketFaceValue": c.TicketFaceValue, "TicketWinProb": c.TicketWinProb, "MaxPendingTickets": c.MaxPendingTickets, "MaxTicketsPerRecipient": c.MaxTicketsPerRecipient} if c.WeiPerUSD != "" { settings["WeiPerUSD"] = c.WeiPerUSD } else { @@ -67,16 +67,16 @@ func specializePayment(raw string, m Desired) string { args: `, 1) // The wrapper executes /usr/local/bin/livepeer with these same Node arguments. - raw = strings.Replace(raw, " - name: config\n mountPath:", " - {name: payment, mountPath: /run/payment}\n - {name: management, mountPath: /management, readOnly: true}\n - name: config\n mountPath:", 1) - raw = strings.Replace(raw, " volumes:\n", fmt.Sprintf(" volumes:\n - name: payment\n emptyDir: {medium: Memory, sizeLimit: 1Mi}\n - name: management\n hostPath: {path: '%s/volumes/management-sockets/orchestrator', type: Directory}\n", m.InstallDir), 1) + raw = strings.Replace(raw, " - name: config\n mountPath:", " - {name: onchain, mountPath: /run/onchain}\n - {name: management, mountPath: /management, readOnly: true}\n - name: config\n mountPath:", 1) + raw = strings.Replace(raw, " volumes:\n", fmt.Sprintf(" volumes:\n - name: onchain\n emptyDir: {medium: Memory, sizeLimit: 1Mi}\n - name: management\n hostPath: {path: '%s/volumes/management-sockets/orchestrator', type: Directory}\n", m.InstallDir), 1) raw = strings.Replace(raw, " readinessProbe:\n httpGet:\n path: /readyz\n port: metrics", " readinessProbe:\n timeoutSeconds: 5\n periodSeconds: 5\n exec:\n command: [/usr/local/bin/livepeer-runtime, orchestrator-probe]", 1) return raw } -func paymentNetwork(c payment.Config) string { +func onchainNetwork(c onchain.Config) string { var b strings.Builder for _, g := range append(append([]string{}, c.RPCGrants...), c.RedeemerGrants...) { - a, p, e := payment.Grant(g) + a, p, e := onchain.Grant(g) if e != nil { continue } diff --git a/api/internal/controlplane/machineconfig/payment_test.go b/api/internal/controlplane/machineconfig/onchain_test.go similarity index 80% rename from api/internal/controlplane/machineconfig/payment_test.go rename to api/internal/controlplane/machineconfig/onchain_test.go index feb169b..90afa75 100644 --- a/api/internal/controlplane/machineconfig/payment_test.go +++ b/api/internal/controlplane/machineconfig/onchain_test.go @@ -12,14 +12,14 @@ import ( "testing" "github.com/livepeer/control-center/runtime/artifact" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/transport" "go.yaml.in/yaml/v3" ) func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { - c := payment.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} - m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} + c := onchain.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} + m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} b, d, e := Build(m) if e != nil { t.Fatal(e) @@ -50,7 +50,7 @@ func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) if binary := os.Getenv("NODE_BINARY"); binary != "" { dir := t.TempDir() config := configurationFromManifest(node) - for key, value := range map[string]string{"/run/payment/private/rpc": "https://rpc.example", "/run/payment/private/headers": "Authorization: Bearer test-only", "/credentials/secret": "bootstrap-test-only"} { + for key, value := range map[string]string{"/run/onchain/private/rpc": "https://rpc.example", "/run/onchain/private/headers": "Authorization: Bearer test-only", "/credentials/secret": "bootstrap-test-only"} { file := filepath.Join(dir, filepath.Base(key)) if e := os.WriteFile(file, []byte(value), 0600); e != nil { t.Fatal(e) @@ -64,7 +64,7 @@ func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) t.Fatal("actual Node rejected onchain configuration", e, string(output)) } } - for _, want := range []string{"orchestrator-start", "orchestrator-probe", "publishNotReadyAddresses: true", "fsGroupChangePolicy: OnRootMismatch", "RPCURLFile", "RedeemerHeadersFile", "/data/payments.sqlite", "medium: Memory"} { + for _, want := range []string{"orchestrator-start", "orchestrator-probe", "publishNotReadyAddresses: true", "fsGroupChangePolicy: OnRootMismatch", "RPCURLFile", "RedeemerHeadersFile", "/data/onchain.sqlite", "medium: Memory"} { if !strings.Contains(node, want) { t.Fatal("missing", want) } @@ -86,49 +86,49 @@ func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) if Digest(refreshed) == original { t.Fatal("re-enrollment reused a previous lifetime's Node workload") } - m.Payment.Generation++ - m.Payment.CredentialRevision++ + m.Onchain.Generation++ + m.Onchain.CredentialRevision++ if Digest(m) == original { t.Fatal("credential generation failed to restart Node") } m.State.HeldOrchestrator = node - m.State.HeldPayment = paymentJSON(c) + m.State.HeldOnchain = onchainJSON(c) meta := DesiredRuntime(m) - if meta.Payment.Generation != c.Generation || meta.ConfigDigest != original { - t.Fatal("held workload borrowed desired payment identity", meta) + if meta.Onchain.Generation != c.Generation || meta.ConfigDigest != original { + t.Fatal("held workload borrowed desired onchain identity", meta) } var parsed Runtime - if json.Unmarshal(files["runtime.json"], &parsed) != nil || parsed.Payment.Recipient != c.Recipient { - t.Fatal("payment metadata absent") + if json.Unmarshal(files["runtime.json"], &parsed) != nil || parsed.Onchain.Recipient != c.Recipient { + t.Fatal("onchain metadata absent") } // Fields omitted by a held offchain identity must not survive from the // desired onchain configuration while the existing workload drains. free := m - free.State.HeldOrchestrator, free.State.HeldPayment = "", "" - free.Payment = payment.Offchain() + free.State.HeldOrchestrator, free.State.HeldOnchain = "", "" + free.Onchain = onchain.Offchain() freeBundle, _, e := Build(free) if e != nil { t.Fatal(e) } freeFiles, _ := artifact.Read(freeBundle) m.State.HeldOrchestrator = string(freeFiles["system/node/orchestrator.yaml"]) - m.State.HeldPayment = paymentJSON(payment.Offchain()) + m.State.HeldOnchain = onchainJSON(onchain.Offchain()) b, _, e = Build(m) if e != nil { t.Fatal(e) } files, _ = artifact.Read(b) parsed, e = transport.ReadMetadata(files["runtime.json"]) - if e != nil || parsed.Payment.Onchain() || parsed.Payment.Recipient != "" || parsed.Payment.RPCSecret != "" { - t.Fatal("held offchain workload inherited desired onchain inputs", parsed.Payment, e) + if e != nil || parsed.Onchain.Onchain() || parsed.Onchain.Recipient != "" || parsed.Onchain.RPCSecret != "" { + t.Fatal("held offchain workload inherited desired onchain inputs", parsed.Onchain, e) } } -func TestPaymentLookupFailureDoesNotBeginWithdrawal(t *testing.T) { +func TestOnchainLookupFailureDoesNotBeginWithdrawal(t *testing.T) { manager := New(Config{}, Dependencies{}) state := State{Lifecycle: "active", Generation: 4, ApprovedConfigDigest: strings.Repeat("a", 64)} before := state - desired := Desired{PaymentError: fmt.Errorf("payment lookup unavailable")} + desired := Desired{OnchainError: fmt.Errorf("onchain lookup unavailable")} if _, e := manager.Gate(t.Context(), Machine{}, &state, desired); e == nil || state != before { t.Fatal("failed lookup changed rollout", e, state) } diff --git a/api/internal/controlplane/machineconfig/reports.go b/api/internal/controlplane/machineconfig/reports.go index 832239b..5932c8f 100644 --- a/api/internal/controlplane/machineconfig/reports.go +++ b/api/internal/controlplane/machineconfig/reports.go @@ -47,7 +47,7 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b return false, ErrStaleStatus } } - reasons := map[string]bool{"payment_not_ready": true, "ready": true, "applying": true, "offline": true, "failed": true, "drain_pending": true, "removed": true, "tls_pending": true} + reasons := map[string]bool{"onchain_not_ready": true, "ready": true, "applying": true, "offline": true, "failed": true, "drain_pending": true, "removed": true, "tls_pending": true} if !reasons[report.Reason] { report.Reason = "failed" } @@ -95,8 +95,8 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b if previous.Drained && previous.Generation == report.Generation && previous.Evidence != nil && report.Evidence != nil && previous.Evidence.Target == report.Evidence.Target && time.Now().Before(previous.Evidence.ExpiresAt) { drainWake = false } - paymentWake := report.Component == "runtime" && report.Payment != nil && (record.RolloutReason == "payment_drain_pending" || (report.Payment.Mode == "onchain" && record.ApprovedConfigDigest != report.ConfigDigest)) - return paymentWake || drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil + onchainWake := report.Component == "runtime" && report.Onchain != nil && (record.RolloutReason == "onchain_drain_pending" || (report.Onchain.Mode == "onchain" && record.ApprovedConfigDigest != report.ConfigDigest)) + return onchainWake || drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil } func validDrainEvidence(m Machine, state State, report Report, now time.Time) bool { diff --git a/api/internal/controlplane/machineconfig/rollout.go b/api/internal/controlplane/machineconfig/rollout.go index f9f27b7..0ffbde7 100644 --- a/api/internal/controlplane/machineconfig/rollout.go +++ b/api/internal/controlplane/machineconfig/rollout.go @@ -7,7 +7,7 @@ import ( "errors" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" "github.com/livepeer/control-center/runtime/artifact" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "time" ) @@ -26,11 +26,11 @@ func (s *Manager) applied(ctx context.Context, m Machine) (Runtime, string, erro // Gate holds the applied workload until a fresh report completes its drain. // The caller saves this state under the enrollment's lease before publication. func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Desired) (bool, error) { - if desired.PaymentError != nil { - return false, desired.PaymentError + if desired.OnchainError != nil { + return false, desired.OnchainError } - if desired.Payment.Onchain() { - state.PaymentSettled = false + if desired.Onchain.Onchain() { + state.OnchainSettled = false } old, manifest, err := s.applied(ctx, m) if err != nil { @@ -42,10 +42,10 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des digest := Digest(desired) // Admission has never opened for this onchain target. Its image or rendering // can be repaired without asking the failed process to drain again, while - // retaining the exact payment/storage binding and the admission freeze. - frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested && !state.PaymentDrainAfter.IsZero() + // retaining the exact onchain/storage binding and the admission freeze. + frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested && !state.OnchainDrainAfter.IsZero() initial := state.ApplyingConfigDigest == "" && state.ApprovedConfigDigest == "" - if old.ConfigDigest != digest && old.Payment.Onchain() && !old.PaymentActive && state.ApprovedConfigDigest != old.ConfigDigest && paymentJSON(old.Payment) == paymentJSON(desired.Payment) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { + if old.ConfigDigest != digest && old.Onchain.Onchain() && !old.OnchainActive && state.ApprovedConfigDigest != old.ConfigDigest && onchainJSON(old.Onchain) == onchainJSON(desired.Onchain) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { state.HeldOrchestrator, state.HeldUpgradePlan = "", "" state.ApplyingConfigDigest = digest state.ApplyingUpgradeVersion = upgradeVersion(desired) @@ -76,9 +76,9 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des state.ApplyingUpgradeVersion = "" } if state.HeldOrchestrator == "" && (state.ApprovedConfigDigest == digest || old.ConfigDigest == digest) { - if desired.Payment.Onchain() && state.ApprovedConfigDigest != digest { - if !desired.PaymentReady { - state.RolloutReason = "payment_startup_pending" + if desired.Onchain.Onchain() && state.ApprovedConfigDigest != digest { + if !desired.OnchainReady { + state.RolloutReason = "onchain_startup_pending" return false, nil } state.ApprovedConfigDigest = digest @@ -94,7 +94,7 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des state.DrainRequested = true state.DrainStartedAt = time.Now().UTC() state.HeldOrchestrator = manifest - state.HeldPayment = paymentJSON(old.Payment) + state.HeldOnchain = onchainJSON(old.Onchain) s.holdUpgrade(ctx, m, state) } if old.ConfigDigest != digest { @@ -103,13 +103,13 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des return true, err } } - if old.Payment.Onchain() && (!desired.Payment.Onchain() || desired.Payment.RedeemerURL != old.Payment.RedeemerURL) { - if !s.paymentDrained(ctx, m, old, state.PaymentDrainAfter) { - state.RolloutReason = "payment_drain_pending" + if old.Onchain.Onchain() && (!desired.Onchain.Onchain() || desired.Onchain.RedeemerURL != old.Onchain.RedeemerURL) { + if !s.onchainDrained(ctx, m, old, state.OnchainDrainAfter) { + state.RolloutReason = "onchain_drain_pending" return true, nil } - if !desired.Payment.Onchain() { - state.PaymentSettled = true + if !desired.Onchain.Onchain() { + state.OnchainSettled = true } } state.HeldOrchestrator = "" @@ -124,8 +124,8 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des // StageTarget drains for a change whose external prerequisites are prepared by // another subsystem. Gate releases the held workload once those facts are ready. func (s *Manager) StageTarget(ctx context.Context, m Machine, state *State, desired Desired, target string) (bool, error) { - if desired.PaymentError != nil { - return false, desired.PaymentError + if desired.OnchainError != nil { + return false, desired.OnchainError } old, manifest, err := s.applied(ctx, m) if err != nil { @@ -147,7 +147,7 @@ func (s *Manager) StageTarget(ctx context.Context, m Machine, state *State, desi state.DrainStartedAt = time.Now().UTC() state.PendingConfigDigest = digest state.HeldOrchestrator = manifest - state.HeldPayment = paymentJSON(old.Payment) + state.HeldOnchain = onchainJSON(old.Onchain) s.holdUpgrade(ctx, m, state) } done, err := s.drainComplete(ctx, m, state) @@ -188,7 +188,7 @@ func (s *Manager) drainComplete(ctx context.Context, m Machine, state *State) (b return false, err } if report.Drained && report.Generation == state.Generation && time.Since(at) <= s.config.StatusTTL && validDrainEvidence(m, *state, report, time.Now()) { - state.PaymentDrainAfter = evidenceTime(report) + state.OnchainDrainAfter = evidenceTime(report) state.RolloutReason = "" return true, nil } @@ -214,8 +214,8 @@ func (s *Manager) removalComplete(ctx context.Context, m Machine, state *State) if e != nil { return false, e } - if !s.paymentDrained(ctx, m, old, state.PaymentDrainAfter) { - state.RolloutReason = "payment_drain_pending" + if !s.onchainDrained(ctx, m, old, state.OnchainDrainAfter) { + state.RolloutReason = "onchain_drain_pending" return false, nil } state.RolloutReason = "" @@ -247,7 +247,7 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { if err != nil { return false, err } - if _, err = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET drained=true WHERE node_id=$1`, l.Machine.NodeID); err != nil { + if _, err = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET drained=true WHERE node_id=$1`, l.Machine.NodeID); err != nil { return false, err } if _, err = tx.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2`, l.Machine.NodeID, l.Machine.Epoch); err != nil { @@ -256,13 +256,13 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { return true, tx.Commit() } -func paymentJSON(c payment.Config) string { b, _ := json.Marshal(c); return string(b) } -func (s *Manager) paymentDrained(ctx context.Context, m Machine, old Runtime, after time.Time) bool { - if !old.Payment.Onchain() { +func onchainJSON(c onchain.Config) string { b, _ := json.Marshal(c); return string(b) } +func (s *Manager) onchainDrained(ctx context.Context, m Machine, old Runtime, after time.Time) bool { + if !old.Onchain.Onchain() { return true } r, at, e := s.store.Report(ctx, m, "runtime") - return e == nil && !after.IsZero() && !r.ObservedAt.Before(after) && r.Generation == old.Generation && !r.ClockUncertain && time.Since(at) <= s.config.StatusTTL && time.Since(r.ObservedAt) <= s.config.StatusTTL && r.ConfigDigest == old.ConfigDigest && r.Payment != nil && r.Payment.Generation == old.Payment.Generation && r.Payment.Applied && r.Payment.QueueKnown && r.Payment.Unsettled == 0 + return e == nil && !after.IsZero() && !r.ObservedAt.Before(after) && r.Generation == old.Generation && !r.ClockUncertain && time.Since(at) <= s.config.StatusTTL && time.Since(r.ObservedAt) <= s.config.StatusTTL && r.ConfigDigest == old.ConfigDigest && r.Onchain != nil && r.Onchain.Generation == old.Onchain.Generation && r.Onchain.Applied && r.Onchain.QueueKnown && r.Onchain.Unsettled == 0 } func evidenceTime(r Report) time.Time { diff --git a/api/internal/controlplane/machineconfig/runtime.go b/api/internal/controlplane/machineconfig/runtime.go index 645674c..0c65734 100644 --- a/api/internal/controlplane/machineconfig/runtime.go +++ b/api/internal/controlplane/machineconfig/runtime.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "regexp" "strings" "time" @@ -78,7 +78,7 @@ func specializeNode(raw string, m Desired) string { if m.NodeDrainTimeout != nil { timeout = *m.NodeDrainTimeout } - raw = specializePayment(raw, m) + raw = specializeOnchain(raw, m) raw = strings.ReplaceAll(raw, "@NODE_DRAIN_TIMEOUT@", timeout.String()) if m.NodeImage != "" { raw = regexp.MustCompile(`(?m)^ image: ghcr.io/livepeer/node:[^\n]+`).ReplaceAllString(raw, " image: "+m.NodeImage) @@ -96,13 +96,13 @@ type Runtime = contract.Metadata func DesiredRuntime(m Desired) Runtime { d := Runtime{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Generation: 1, Terminal: m.Terminal, ConfigDigest: Digest(m), ServiceURL: PrivateOrchestrator, APIURL: m.ControlAPIURL} - d.Payment = effectivePayment(m) - if d.Payment.Version == 0 { - d.Payment = payment.Offchain() + d.Onchain = effectiveOnchain(m) + if d.Onchain.Version == 0 { + d.Onchain = onchain.Offchain() } - d.PaymentActive = !m.State.DrainRequested && m.State.ApplyingConfigDigest == "" && (!d.Payment.Onchain() || (m.PaymentReady && m.State.ApprovedConfigDigest == d.ConfigDigest)) - if d.Payment.Onchain() { - d.PaymentCredentialsRef = "/v1/nodes/" + m.NodeID + "/payment/credentials" + d.OnchainActive = !m.State.DrainRequested && m.State.ApplyingConfigDigest == "" && (!d.Onchain.Onchain() || (m.OnchainReady && m.State.ApprovedConfigDigest == d.ConfigDigest)) + if d.Onchain.Onchain() { + d.OnchainCredentialsRef = "/v1/nodes/" + m.NodeID + "/onchain/credentials" } d.RunnerServiceURL = PrivateOrchestrator d.Generation = max(m.State.Generation, 1) diff --git a/api/internal/controlplane/machineconfig/system.go b/api/internal/controlplane/machineconfig/system.go index a3e5263..4ed4db8 100644 --- a/api/internal/controlplane/machineconfig/system.go +++ b/api/internal/controlplane/machineconfig/system.go @@ -80,8 +80,8 @@ func addSystemWorkloads(files map[string][]byte, m Desired) error { continue } files[prefix+"system/node/network.yaml"] = []byte(nodeNetwork()) - if effectivePayment(m).Onchain() { - files[prefix+"management/app-reconciler.yaml"] = append(files[prefix+"management/app-reconciler.yaml"], []byte("\n---\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata: {name: orchestrator-payment-egress, namespace: livepeer}\nspec:\n podSelector: {matchLabels: {app: orchestrator}}\n policyTypes: [Egress]\n egress:\n"+paymentNetwork(effectivePayment(m)))...) + if effectiveOnchain(m).Onchain() { + files[prefix+"management/app-reconciler.yaml"] = append(files[prefix+"management/app-reconciler.yaml"], []byte("\n---\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata: {name: orchestrator-onchain-egress, namespace: livepeer}\nspec:\n podSelector: {matchLabels: {app: orchestrator}}\n policyTypes: [Egress]\n egress:\n"+onchainNetwork(effectiveOnchain(m)))...) } files[prefix+"system/node/kustomization.yaml"] = kustomize("orchestrator.yaml", "network.yaml") connectorResources := []string{} diff --git a/api/internal/controlplane/machineconfig/types.go b/api/internal/controlplane/machineconfig/types.go index e202058..7d733f4 100644 --- a/api/internal/controlplane/machineconfig/types.go +++ b/api/internal/controlplane/machineconfig/types.go @@ -4,7 +4,7 @@ package machineconfig import ( "github.com/livepeer/control-center/runtime/appbundle" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/schema" "regexp" "time" @@ -30,9 +30,9 @@ type State struct { DrainStartedAt time.Time `json:"drain_started_at,omitempty"` DrainedGeneration int64 `json:"drained_generation,omitempty"` Target string `json:"target,omitempty"` - PaymentSettled bool `json:"payment_settled,omitempty"` - PaymentDrainAfter time.Time `json:"payment_drain_after,omitempty"` - HeldPayment string `json:"held_payment,omitempty"` + OnchainSettled bool `json:"onchain_settled,omitempty"` + OnchainDrainAfter time.Time `json:"onchain_drain_after,omitempty"` + HeldOnchain string `json:"held_onchain,omitempty"` HeldOrchestrator string `json:"held_orchestrator,omitempty"` PendingConfigDigest string `json:"pending_config_digest,omitempty"` ApprovedConfigDigest string `json:"approved_config_digest,omitempty"` @@ -59,9 +59,9 @@ type ConnectorConfig struct { } type Desired struct { - Payment payment.Config - PaymentError error - PaymentReady bool + Onchain onchain.Config + OnchainError error + OnchainReady bool Machine Apps *schema.AppAssignmentSetV1 State State @@ -84,7 +84,7 @@ var imageDigestPattern = regexp.MustCompile(`^[a-zA-Z0-9./:_-]+@sha256:[0-9a-f]{ func ValidConnectorImage(image string) bool { return imageDigestPattern.MatchString(image) } type Report struct { - Payment *payment.Observation `json:"payment,omitempty"` + Onchain *onchain.Observation `json:"onchain,omitempty"` ObserverID string `json:"observer_id,omitempty"` ObserverStartedAt time.Time `json:"observer_started_at,omitempty"` ClockUncertain bool `json:"clock_uncertain,omitempty"` diff --git a/api/internal/controlplane/migrations/009_onchain.sql b/api/internal/controlplane/migrations/009_onchain.sql new file mode 100644 index 0000000..6d16b5d --- /dev/null +++ b/api/internal/controlplane/migrations/009_onchain.sql @@ -0,0 +1,70 @@ +-- UP +-- Retain storage identity and recovery state after the active machine is removed. +CREATE TABLE lpcc.onchain_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); +INSERT INTO lpcc.onchain_revision DEFAULT VALUES; +CREATE TABLE lpcc.onchain_configs ( + node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, + PRIMARY KEY(node_id,generation) +); +CREATE TABLE lpcc.onchain_state ( + node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), + recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', + generation BIGINT NOT NULL CHECK(generation>0), + initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false, + FOREIGN KEY(node_id,generation) REFERENCES lpcc.onchain_configs(node_id,generation) +); +CREATE TABLE lpcc.onchain_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); +CREATE TABLE lpcc.onchain_grants ( + grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, + onchain_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, + pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, + observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, + UNIQUE(node_id,epoch,onchain_generation,pod_uid,launch_id,process_id) +); +CREATE INDEX onchain_grants_machine ON lpcc.onchain_grants(node_id,epoch); + +CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER + SET search_path=pg_catalog,lpcc AS $$ +BEGIN + UPDATE lpcc.onchain_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + UPDATE lpcc.onchain_state b SET recovery_required=b.recovery_required OR (NOT b.drained AND (b.initialized OR c.config->>'mode'='onchain') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'onchain_settled'='true')) + FROM lpcc.onchain_configs c WHERE b.node_id=OLD.node_id AND c.node_id=b.node_id AND c.generation=b.generation; + UPDATE lpcc.enrollments e SET retained_bundle=c.bundle + FROM lpcc.machine_configs c + WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + AND e.retained_bundle IS NULL; + RETURN OLD; +END $$; +ALTER TABLE lpcc.onchain_revision ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.onchain_state ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.onchain_configs ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.onchain_secrets ENABLE ROW LEVEL SECURITY; +ALTER TABLE lpcc.onchain_grants ENABLE ROW LEVEL SECURITY; +REVOKE ALL ON lpcc.onchain_revision,lpcc.onchain_state,lpcc.onchain_configs,lpcc.onchain_secrets,lpcc.onchain_grants FROM PUBLIC; +REVOKE ALL ON SEQUENCE lpcc.onchain_grants_issued_sequence_seq FROM PUBLIC; +DO $$ DECLARE r TEXT; +BEGIN + FOREACH r IN ARRAY ARRAY['anon','authenticated'] LOOP + IF EXISTS(SELECT FROM pg_roles WHERE rolname=r) THEN + EXECUTE format('REVOKE ALL ON lpcc.onchain_revision,lpcc.onchain_state,lpcc.onchain_configs,lpcc.onchain_secrets,lpcc.onchain_grants FROM %I',r); + EXECUTE format('REVOKE ALL ON SEQUENCE lpcc.onchain_grants_issued_sequence_seq FROM %I',r); + END IF; + END LOOP; +END $$; +-- DOWN +DO $$ BEGIN + IF EXISTS(SELECT FROM lpcc.onchain_state) OR EXISTS(SELECT FROM lpcc.onchain_configs) + OR EXISTS(SELECT FROM lpcc.onchain_secrets) OR EXISTS(SELECT FROM lpcc.onchain_grants) THEN + RAISE EXCEPTION 'retain onchain schema while onchain history exists'; + END IF; +END $$; +CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER + SET search_path=pg_catalog,lpcc AS $$ +BEGIN + UPDATE lpcc.enrollments e SET retained_bundle=c.bundle + FROM lpcc.machine_configs c + WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + AND e.retained_bundle IS NULL; + RETURN OLD; +END $$; +DROP TABLE lpcc.onchain_revision,lpcc.onchain_state,lpcc.onchain_configs,lpcc.onchain_secrets,lpcc.onchain_grants; diff --git a/api/internal/controlplane/migrations/009_onchain_payments.sql b/api/internal/controlplane/migrations/009_onchain_payments.sql deleted file mode 100644 index ca4b747..0000000 --- a/api/internal/controlplane/migrations/009_onchain_payments.sql +++ /dev/null @@ -1,68 +0,0 @@ --- UP --- Payment bindings deliberately survive enrollment and Auth account deletion. -CREATE TABLE lpcc.payment_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); -INSERT INTO lpcc.payment_revision DEFAULT VALUES; -CREATE TABLE lpcc.payment_machines ( - node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), - recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', - generation BIGINT NOT NULL CHECK(generation>0), config JSONB NOT NULL, - initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false -); -CREATE TABLE lpcc.payment_versions ( - node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, - PRIMARY KEY(node_id,generation) -); -CREATE TABLE lpcc.payment_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); -CREATE TABLE lpcc.payment_grants ( - grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, - payment_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, - pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, - observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, - UNIQUE(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) -); -CREATE INDEX payment_grants_machine ON lpcc.payment_grants(node_id,epoch); - -CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER - SET search_path=pg_catalog,lpcc AS $$ -BEGIN - UPDATE lpcc.payment_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; - UPDATE lpcc.payment_machines SET recovery_required=recovery_required OR (NOT drained AND (initialized OR config->>'mode'='onchain') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'payment_settled'='true')) WHERE node_id=OLD.node_id; - UPDATE lpcc.enrollments e SET retained_bundle=c.bundle - FROM lpcc.machine_configs c - WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id - AND e.retained_bundle IS NULL; - RETURN OLD; -END $$; -ALTER TABLE lpcc.payment_revision ENABLE ROW LEVEL SECURITY; -ALTER TABLE lpcc.payment_machines ENABLE ROW LEVEL SECURITY; -ALTER TABLE lpcc.payment_versions ENABLE ROW LEVEL SECURITY; -ALTER TABLE lpcc.payment_secrets ENABLE ROW LEVEL SECURITY; -ALTER TABLE lpcc.payment_grants ENABLE ROW LEVEL SECURITY; -REVOKE ALL ON lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants FROM PUBLIC; -REVOKE ALL ON SEQUENCE lpcc.payment_grants_issued_sequence_seq FROM PUBLIC; -DO $$ DECLARE r TEXT; -BEGIN - FOREACH r IN ARRAY ARRAY['anon','authenticated'] LOOP - IF EXISTS(SELECT FROM pg_roles WHERE rolname=r) THEN - EXECUTE format('REVOKE ALL ON lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants FROM %I',r); - EXECUTE format('REVOKE ALL ON SEQUENCE lpcc.payment_grants_issued_sequence_seq FROM %I',r); - END IF; - END LOOP; -END $$; --- DOWN -DO $$ BEGIN - IF EXISTS(SELECT FROM lpcc.payment_machines) OR EXISTS(SELECT FROM lpcc.payment_versions) - OR EXISTS(SELECT FROM lpcc.payment_secrets) OR EXISTS(SELECT FROM lpcc.payment_grants) THEN - RAISE EXCEPTION 'retain payment schema while payment history exists'; - END IF; -END $$; -CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER - SET search_path=pg_catalog,lpcc AS $$ -BEGIN - UPDATE lpcc.enrollments e SET retained_bundle=c.bundle - FROM lpcc.machine_configs c - WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id - AND e.retained_bundle IS NULL; - RETURN OLD; -END $$; -DROP TABLE lpcc.payment_revision,lpcc.payment_machines,lpcc.payment_versions,lpcc.payment_secrets,lpcc.payment_grants; diff --git a/api/internal/controlplane/observed_state.go b/api/internal/controlplane/observed_state.go index 72a140e..837d39b 100644 --- a/api/internal/controlplane/observed_state.go +++ b/api/internal/controlplane/observed_state.go @@ -14,16 +14,15 @@ import ( fleet "github.com/livepeer/control-center/api/internal/controlplane/discovery" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" - "github.com/livepeer/control-center/api/internal/controlplane/payments" "github.com/livepeer/control-center/api/internal/controlplane/tunnel" "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/schema" ) type componentObservation struct { - Payment *payment.Observation `json:"payment,omitempty"` + Onchain *onchain.Observation `json:"onchain,omitempty"` ObserverID string `json:"observer_id,omitempty"` ObserverStartedAt *time.Time `json:"observer_started_at,omitempty"` Component string `json:"component"` @@ -83,7 +82,7 @@ type tunnelObservation struct { } type machineObservation struct { - Payment paymentView `json:"payment"` + Onchain onchainView `json:"onchain"` NodeID string `json:"node_id"` Epoch string `json:"epoch"` Hostname string `json:"hostname"` @@ -177,7 +176,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse } else if err != nil { return v, err } - v.Payment, err = s.paymentView(ctx, m) + v.Onchain, err = s.onchainView(ctx, m) if err != nil { return v, err } @@ -239,9 +238,9 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse expires = timePointer(effective.Add(ttl)) } c := componentObservation{Component: name, Generation: report.Generation, ObservedAt: report.ObservedAt, ReceivedAt: &received, ExpiresAt: expires, Fresh: expires != nil && now.Before(*expires), Current: report.Generation == record.Generation, Ready: report.Ready, Reason: safeObservationReason(report.Reason), ClockUncertain: report.ClockUncertain, BundleSHA256: report.BundleSHA256, ConfigDigest: report.ConfigDigest, DeliveryReason: safeObservationReason(report.DeliveryReason)} - c.Payment = report.Payment - if c.Payment != nil { - copy := *c.Payment + c.Onchain = report.Onchain + if c.Onchain != nil { + copy := *c.Onchain copy.GrantID = "" if !c.Fresh || !c.Current || c.ClockUncertain { copy.Ready = false @@ -249,7 +248,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse copy.QueueKnown = false copy.Handoff = "unverified" } - c.Payment = © + c.Onchain = © } c.AppsError = safeObservationReason(report.AppsError) c.Apps, c.Downloaded, c.DownloadedAt = report.Apps, report.Downloaded, timePointer(report.DownloadedAt) @@ -436,23 +435,23 @@ func (s *Server) observedMachineList(ctx context.Context, owner string, admin bo return result, rows.Err() } -type paymentView struct { - Desired payment.Config `json:"desired"` +type onchainView struct { + Desired onchain.Config `json:"desired"` DeliveredGeneration int64 `json:"delivered_generation"` RecoveryRequired bool `json:"recovery_required"` } -func (s *Server) paymentView(ctx context.Context, m Machine) (paymentView, error) { - var v paymentView +func (s *Server) onchainView(ctx context.Context, m Machine) (onchainView, error) { + var v onchainView var err error - v.Desired, err = payments.Load(ctx, s.db, m.NodeID) + v.Desired, err = loadOnchain(ctx, s.db, m.NodeID) if err != nil { return v, err } v.Desired.RPCSecret = "" v.Desired.RPCGrants = nil v.Desired.RedeemerGrants = nil - _ = s.db.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, m.NodeID).Scan(&v.RecoveryRequired) + _ = s.db.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, m.NodeID).Scan(&v.RecoveryRequired) var b []byte if m.Terminal { err = s.db.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&b) @@ -464,7 +463,7 @@ func (s *Server) paymentView(ctx context.Context, m Machine) (paymentView, error if e == nil { var meta contract.Metadata if json.Unmarshal(files["runtime.json"], &meta) == nil { - v.DeliveredGeneration = meta.Payment.Generation + v.DeliveredGeneration = meta.Onchain.Generation } } } diff --git a/api/internal/controlplane/payment_credentials.go b/api/internal/controlplane/onchain_credentials.go similarity index 72% rename from api/internal/controlplane/payment_credentials.go rename to api/internal/controlplane/onchain_credentials.go index 1d492f3..5ef1083 100644 --- a/api/internal/controlplane/payment_credentials.go +++ b/api/internal/controlplane/onchain_credentials.go @@ -15,8 +15,8 @@ import ( "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/orchestrator" - "github.com/livepeer/control-center/runtime/payment" "github.com/livepeer/control-center/runtime/transport" ) @@ -25,15 +25,15 @@ func (s *Server) submissionToken(id string) string { h.Write([]byte("livepeer-redemption-submit-v1\x00" + id)) return id + "." + hex.EncodeToString(h.Sum(nil)) } -func (s *Server) paymentCredentials(w http.ResponseWriter, r *http.Request) { +func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { m, e := s.authenticateMachine(r.Context(), r.PathValue("node_id"), bearer(r), false) if e != nil { s.respondError(w, e) return } var in orchestrator.Request - if boundedMachineInput(r, &in, 4096) != nil || !orchestrator.ValidLaunch(in.Launch) || in.PaymentGeneration < 1 || !fingerprintPattern.MatchString(in.ConfigDigest) || !strings.HasPrefix(s.params.PublicAPIURL, "https://") { - fail(w, 403, "payment delivery refused") + if boundedMachineInput(r, &in, 4096) != nil || !orchestrator.ValidLaunch(in.Launch) || in.OnchainGeneration < 1 || !fingerprintPattern.MatchString(in.ConfigDigest) || !strings.HasPrefix(s.params.PublicAPIURL, "https://") { + fail(w, 403, "onchain delivery refused") return } tx, e := s.db.BeginTx(r.Context(), nil) @@ -59,30 +59,30 @@ func (s *Server) paymentCredentials(w http.ResponseWriter, r *http.Request) { if e == nil { metadata, e = transport.ReadMetadata(files["runtime.json"]) } - if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Payment.Onchain() || metadata.Payment.Generation != in.PaymentGeneration || metadata.ConfigDigest != in.ConfigDigest { - fail(w, 409, "payment configuration changed") + if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Onchain.Onchain() || metadata.Onchain.Generation != in.OnchainGeneration || metadata.ConfigDigest != in.ConfigDigest { + fail(w, 409, "onchain configuration changed") return } - rpc, e := s.readPaymentRPC(metadata.Payment.RPCSecret) + rpc, e := s.readOnchainRPC(metadata.Onchain.RPCSecret) if e != nil { - fail(w, 503, "payment secret unavailable") + fail(w, 503, "onchain secret unavailable") return } hash := sha256.Sum256(rpc) var fingerprint string - e = tx.QueryRowContext(r.Context(), `SELECT fingerprint FROM lpcc.payment_secrets WHERE reference=$1`, metadata.Payment.RPCSecret).Scan(&fingerprint) + e = tx.QueryRowContext(r.Context(), `SELECT fingerprint FROM lpcc.onchain_secrets WHERE reference=$1`, metadata.Onchain.RPCSecret).Scan(&fingerprint) if e != nil || fingerprint != hex.EncodeToString(hash[:]) { - fail(w, 503, "payment secret version changed") + fail(w, 503, "onchain secret version changed") return } var initialized bool - if e = tx.QueryRowContext(r.Context(), `SELECT initialized FROM lpcc.payment_machines WHERE node_id=$1`, m.NodeID).Scan(&initialized); e != nil { + if e = tx.QueryRowContext(r.Context(), `SELECT initialized FROM lpcc.onchain_state WHERE node_id=$1`, m.NodeID).Scan(&initialized); e != nil { s.databaseError(w, e) return } id := uuid.New().String() var revoked sql.NullTime - e = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.payment_grants(grant_id,node_id,epoch,payment_generation,config_digest,pod_uid,launch_id,process_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(node_id,epoch,payment_generation,pod_uid,launch_id,process_id) DO UPDATE SET grant_id=lpcc.payment_grants.grant_id RETURNING grant_id::text,revoked_at`, id, m.NodeID, m.Epoch, in.PaymentGeneration, in.ConfigDigest, in.PodUID, in.LaunchID, in.ProcessID).Scan(&id, &revoked) + e = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.onchain_grants(grant_id,node_id,epoch,onchain_generation,config_digest,pod_uid,launch_id,process_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(node_id,epoch,onchain_generation,pod_uid,launch_id,process_id) DO UPDATE SET grant_id=lpcc.onchain_grants.grant_id RETURNING grant_id::text,revoked_at`, id, m.NodeID, m.Epoch, in.OnchainGeneration, in.ConfigDigest, in.PodUID, in.LaunchID, in.ProcessID).Scan(&id, &revoked) if e != nil { s.databaseError(w, e) return @@ -95,11 +95,11 @@ func (s *Server) paymentCredentials(w http.ResponseWriter, r *http.Request) { s.databaseError(w, e) return } - respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, PaymentGeneration: in.PaymentGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) + respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, OnchainGeneration: in.OnchainGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) } func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { - secret := s.params.PaymentWebhookSecret + secret := s.params.OnchainWebhookSecret if len(secret) < 32 || len(r.Header.Values("Authorization")) != 1 || subtle.ConstantTimeCompare([]byte(bearer(r)), []byte(secret)) != 1 { fail(w, 401, "webhook authentication required") return @@ -129,10 +129,10 @@ func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { var ticket struct { Recipient string `json:"recipient"` } - allowed := count == 1 && ok && appID(id) && len(s.params.MachineTokenSecret) >= 32 && hmac.Equal([]byte(token), []byte(s.submissionToken(id))) && json.Unmarshal(in.Ticket, &ticket) == nil && payment.Address.MatchString(ticket.Recipient) + allowed := count == 1 && ok && appID(id) && len(s.params.MachineTokenSecret) >= 32 && hmac.Equal([]byte(token), []byte(s.submissionToken(id))) && json.Unmarshal(in.Ticket, &ticket) == nil && onchain.Address.MatchString(ticket.Recipient) if allowed { var recipient string - e := s.db.QueryRowContext(r.Context(), `SELECT v.config->>'recipient' FROM lpcc.payment_grants g JOIN lpcc.payment_versions v ON v.node_id=g.node_id AND v.generation=g.payment_generation JOIN lpcc.machines m ON m.node_id=g.node_id AND m.enrollment_epoch=g.epoch WHERE g.grant_id=$1 AND g.revoked_at IS NULL`, id).Scan(&recipient) + e := s.db.QueryRowContext(r.Context(), `SELECT v.config->>'recipient' FROM lpcc.onchain_grants g JOIN lpcc.onchain_configs v ON v.node_id=g.node_id AND v.generation=g.onchain_generation JOIN lpcc.machines m ON m.node_id=g.node_id AND m.enrollment_epoch=g.epoch WHERE g.grant_id=$1 AND g.revoked_at IS NULL`, id).Scan(&recipient) allowed = e == nil && strings.EqualFold(recipient, ticket.Recipient) } status := 403 @@ -145,8 +145,8 @@ func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { // Accept only a fresh, matching observation of the issued grant. This permits a // held Node's grant across ordinary management refresh, without allowing it to // authenticate to any management endpoint. -func (s *Server) observePaymentGrant(ctx context.Context, m Machine, reportPayment *payment.Observation, digest string) error { - p := reportPayment +func (s *Server) observeOnchainGrant(ctx context.Context, m Machine, reportOnchain *onchain.Observation, digest string) error { + p := reportOnchain if p == nil || !p.Applied || p.PodUID == "" { return nil } @@ -174,32 +174,32 @@ func (s *Server) observePaymentGrant(ctx context.Context, m Machine, reportPayme if e != nil { return e } - if meta.ConfigDigest != digest || meta.Payment.Generation != p.Generation || meta.Payment.Mode != p.Mode { + if meta.ConfigDigest != digest || meta.Onchain.Generation != p.Generation || meta.Onchain.Mode != p.Mode { return nil } if p.Mode == "offchain" { // The replacement has no submission bearer to observe. Retire the held // onchain workload's grants only after its offchain successor is applied. - _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, m.NodeID, m.Epoch) + _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, m.NodeID, m.Epoch) if e != nil { return e } return tx.Commit() } var id string - e = tx.QueryRowContext(ctx, `UPDATE lpcc.payment_grants SET observed_at=now() WHERE grant_id=$1 AND node_id=$2 AND epoch=$3 AND payment_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL RETURNING grant_id::text`, p.GrantID, m.NodeID, m.Epoch, p.Generation, digest, p.PodUID).Scan(&id) + e = tx.QueryRowContext(ctx, `UPDATE lpcc.onchain_grants SET observed_at=now() WHERE grant_id=$1 AND node_id=$2 AND epoch=$3 AND onchain_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL RETURNING grant_id::text`, p.GrantID, m.NodeID, m.Epoch, p.Generation, digest, p.PodUID).Scan(&id) if errors.Is(e, sql.ErrNoRows) { return nil } if e != nil { return e } - _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND grant_id<>$3 AND revoked_at IS NULL AND issued_sequence<(SELECT issued_sequence FROM lpcc.payment_grants WHERE grant_id=$3)`, m.NodeID, m.Epoch, id) + _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND grant_id<>$3 AND revoked_at IS NULL AND issued_sequence<(SELECT issued_sequence FROM lpcc.onchain_grants WHERE grant_id=$3)`, m.NodeID, m.Epoch, id) if e != nil { return e } if p.Ready { - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET initialized=true WHERE node_id=$1`, m.NodeID); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET initialized=true WHERE node_id=$1`, m.NodeID); e != nil { return e } } diff --git a/api/internal/controlplane/payment_settings.go b/api/internal/controlplane/onchain_settings.go similarity index 58% rename from api/internal/controlplane/payment_settings.go rename to api/internal/controlplane/onchain_settings.go index 8e86e73..dfd28a5 100644 --- a/api/internal/controlplane/payment_settings.go +++ b/api/internal/controlplane/onchain_settings.go @@ -22,59 +22,75 @@ import ( "github.com/j0sh/boa/pkg/boa" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" - "github.com/livepeer/control-center/api/internal/controlplane/payments" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/spf13/cobra" ) -type paymentInput struct { +func loadOnchain(ctx context.Context, q rowQuerier, node string) (onchain.Config, error) { + c := onchain.Offchain() + var b []byte + err := q.QueryRowContext(ctx, `SELECT c.config FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.node_id=b.node_id AND c.generation=b.generation WHERE b.node_id=$1`, node).Scan(&b) + if errors.Is(err, sql.ErrNoRows) { + return c, nil + } + if err != nil { + return c, err + } + err = json.Unmarshal(b, &c) + if err == nil { + err = c.Validate() + } + return c, err +} + +type onchainInput struct { Version int `json:"version"` - Machines map[string]payment.Config `json:"machines"` + Machines map[string]onchain.Config `json:"machines"` } -type paymentApplyParams struct { +type onchainApplyParams struct { ConfigFile string `name:"config" env:"CONTROL_CENTER_CONFIG" configfile:"optional-default" basepath:"source" default:"config.toml" boa:"noconfig"` DatabaseParams - PaymentSecretsDir string `optional:"true"` - PaymentWebhookSecret string `secret:"true" optional:"true"` - PaymentWebhookSecretFile string `secretfor:"PaymentWebhookSecret" basepath:"source"` + OnchainSecretsDir string `optional:"true"` + OnchainWebhookSecret string `secret:"true" optional:"true"` + OnchainWebhookSecretFile string `secretfor:"OnchainWebhookSecret" basepath:"source"` RuntimeNodeImage string `env:"RUNTIME_NODE_IMAGE" optional:"true"` - File string `name:"file" boa:"noconfig" descr:"Payment infrastructure JSON file"` + File string `name:"file" boa:"noconfig" descr:"Onchain infrastructure JSON file"` AcknowledgeRecovery string `name:"acknowledge-recovery" optional:"true" boa:"noconfig" descr:"Confirm restored retained state after a fresh empty-queue observation"` ExpectedRevision int64 `name:"expected-revision" min:"0" boa:"noconfig"` } -func PaymentsCommand() *cobra.Command { - apply := boa.Cmd[paymentApplyParams]{Use: "apply", Short: "Apply deployment-owned payment infrastructure", Args: cobra.NoArgs, RunFuncE: func(p *paymentApplyParams, cmd *cobra.Command, _ []string) error { +func OnchainCommand() *cobra.Command { + apply := boa.Cmd[onchainApplyParams]{Use: "apply", Short: "Apply deployment-owned onchain infrastructure", Args: cobra.NoArgs, RunFuncE: func(p *onchainApplyParams, cmd *cobra.Command, _ []string) error { b, e := os.ReadFile(p.File) if e != nil { - return errors.New("payment input unavailable") + return errors.New("onchain input unavailable") } - var input paymentInput + var input onchainInput if len(b) > 128<<10 || jsonv2.Unmarshal(b, &input, jsonv2.RejectUnknownMembers(true), jsontext.AllowDuplicateNames(false)) != nil || input.Version != 1 || len(input.Machines) == 0 || len(input.Machines) > 1000 { - return errors.New("invalid payment infrastructure document") + return errors.New("invalid onchain infrastructure document") } db, e := OpenDB(cmd.Context(), p.PGConnstr, p.PGPassword) if e != nil { return e } defer db.Close() - s := New(db, Params{PaymentSecretsDir: p.PaymentSecretsDir, PaymentWebhookSecret: p.PaymentWebhookSecret, RuntimeNodeImage: p.RuntimeNodeImage}, slog.New(slog.NewTextHandler(io.Discard, nil))) - rev, e := s.applyPayments(cmd.Context(), input, p.ExpectedRevision, p.AcknowledgeRecovery) + s := New(db, Params{OnchainSecretsDir: p.OnchainSecretsDir, OnchainWebhookSecret: p.OnchainWebhookSecret, RuntimeNodeImage: p.RuntimeNodeImage}, slog.New(slog.NewTextHandler(io.Discard, nil))) + rev, e := s.applyOnchain(cmd.Context(), input, p.ExpectedRevision, p.AcknowledgeRecovery) if e == nil { fmt.Fprintln(cmd.OutOrStdout(), rev) } return e }}.ToCobra() - return boa.Cmd[boa.NoParams]{Use: "payments", Short: "Deployment payment configuration", SubCmds: []*cobra.Command{apply}}.ToCobra() + return boa.Cmd[boa.NoParams]{Use: "onchain", Short: "Deployment onchain configuration", SubCmds: []*cobra.Command{apply}}.ToCobra() } -// readPaymentRPC never exposes a path or a URL in its errors. -func (s *Server) readPaymentRPC(ref string) ([]byte, error) { - bad := errors.New("payment RPC secret unavailable") - if !payment.SecretRef.MatchString(ref) || !filepath.IsAbs(s.params.PaymentSecretsDir) { +// readOnchainRPC never exposes a path or a URL in its errors. +func (s *Server) readOnchainRPC(ref string) ([]byte, error) { + bad := errors.New("onchain RPC secret unavailable") + if !onchain.SecretRef.MatchString(ref) || !filepath.IsAbs(s.params.OnchainSecretsDir) { return nil, bad } - path := filepath.Join(s.params.PaymentSecretsDir, ref) + path := filepath.Join(s.params.OnchainSecretsDir, ref) info, e := os.Lstat(path) if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { return nil, bad @@ -100,9 +116,9 @@ func (s *Server) readPaymentRPC(ref string) ([]byte, error) { return b, nil } -func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected int64, acknowledge ...string) (int64, error) { +func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected int64, acknowledge ...string) (int64, error) { if input.Version != 1 || len(input.Machines) == 0 || len(input.Machines) > 1000 { - return 0, errors.New("invalid payment document") + return 0, errors.New("invalid onchain document") } nodes := make([]string, 0, len(input.Machines)) fingerprints := map[string]string{} @@ -112,24 +128,24 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected c.ETHUSDFeed = strings.ToLower(c.ETHUSDFeed) input.Machines[node] = c if !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(node) || c.Generation != 0 { - return 0, errors.New("invalid payment machine identity") + return 0, errors.New("invalid onchain machine identity") } if e := c.Validate(); e != nil { return 0, e } nodes = append(nodes, node) if c.Onchain() { - if len(s.params.PaymentWebhookSecret) < 32 { + if len(s.params.OnchainWebhookSecret) < 32 { return 0, errors.New("onchain operation requires a webhook service credential") } if !machineconfigImage(s.params.RuntimeNodeImage) { return 0, errors.New("onchain operation requires a pinned wrapper/Node image") } - b, e := s.readPaymentRPC(c.RPCSecret) + b, e := s.readOnchainRPC(c.RPCSecret) if e != nil { return 0, e } - if e := payment.ValidateEndpoint(string(b), c.RPCGrants); e != nil { + if e := onchain.ValidateEndpoint(string(b), c.RPCGrants); e != nil { return 0, e } h := sha256.Sum256(b) @@ -143,12 +159,12 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected } defer tx.Rollback() var revision int64 - if e = tx.QueryRowContext(ctx, `SELECT revision FROM lpcc.payment_revision WHERE id=true FOR UPDATE`).Scan(&revision); e != nil { + if e = tx.QueryRowContext(ctx, `SELECT revision FROM lpcc.onchain_revision WHERE id=true FOR UPDATE`).Scan(&revision); e != nil { return 0, e } // Import is a complete desired snapshot: omission never silently disables onchain service. - rows, e := tx.QueryContext(ctx, `SELECT node_id FROM lpcc.payment_machines WHERE config->>'mode'='onchain'`) + rows, e := tx.QueryContext(ctx, `SELECT b.node_id FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.node_id=b.node_id AND c.generation=b.generation WHERE c.config->>'mode'='onchain'`) if e != nil { return 0, e } @@ -171,21 +187,21 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected } for ref, digest := range fingerprints { var old string - e = tx.QueryRowContext(ctx, `SELECT fingerprint FROM lpcc.payment_secrets WHERE reference=$1`, ref).Scan(&old) + e = tx.QueryRowContext(ctx, `SELECT fingerprint FROM lpcc.onchain_secrets WHERE reference=$1`, ref).Scan(&old) if e == nil && old != digest { - return 0, errors.New("referenced payment secret versions are immutable") + return 0, errors.New("referenced onchain secret versions are immutable") } if e != nil && !errors.Is(e, sql.ErrNoRows) { return 0, e } - if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_secrets(reference,fingerprint) VALUES($1,$2) ON CONFLICT DO NOTHING`, ref, digest); e != nil { + if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_secrets(reference,fingerprint) VALUES($1,$2) ON CONFLICT DO NOTHING`, ref, digest); e != nil { return 0, e } } changed := false for _, node := range nodes { c := input.Machines[node] - old, e := payments.Load(ctx, tx, node) + old, e := loadOnchain(ctx, tx, node) if e != nil { return 0, e } @@ -218,13 +234,13 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected } var recipient, controller string var chain uint64 - e = tx.QueryRowContext(ctx, `SELECT recipient,chain_id,controller FROM lpcc.payment_machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&recipient, &chain, &controller) + e = tx.QueryRowContext(ctx, `SELECT recipient,chain_id,controller FROM lpcc.onchain_state WHERE node_id=$1 FOR UPDATE`, node).Scan(&recipient, &chain, &controller) if e != nil && !errors.Is(e, sql.ErrNoRows) { return 0, e } if c.Onchain() { if recipient != "" && (!strings.EqualFold(recipient, c.Recipient) || chain != c.ChainID || !strings.EqualFold(controller, c.Controller)) { - return 0, errors.New("payment recipient and chain binding are immutable") + return 0, errors.New("onchain recipient and chain binding are immutable") } recipient = strings.ToLower(c.Recipient) chain = c.ChainID @@ -234,17 +250,17 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected } c.Generation = old.Generation + 1 after, _ = json.Marshal(c) - _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_machines(node_id,recipient,chain_id,controller,generation,config) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation,config=EXCLUDED.config,drained=false`, node, recipient, chain, controller, c.Generation, string(after)) - if e != nil { + if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_configs VALUES($1,$2,$3)`, node, c.Generation, string(after)); e != nil { return 0, e } - if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.payment_versions VALUES($1,$2,$3)`, node, c.Generation, string(after)); e != nil { + _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_state(node_id,recipient,chain_id,controller,generation) VALUES($1,$2,$3,$4,$5) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation,drained=false`, node, recipient, chain, controller, c.Generation) + if e != nil { return 0, e } if _, e = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, node); e != nil { return 0, e } - if e = writeAudit(ctx, tx, "system", "deployment:payments", "payment.apply", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(c.Generation)}, "success", "changed"); e != nil { + if e = writeAudit(ctx, tx, "system", "deployment:onchain", "onchain.apply", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(c.Generation)}, "success", "changed"); e != nil { return 0, e } changed = true @@ -265,33 +281,33 @@ func (s *Server) applyPayments(ctx context.Context, input paymentInput, expected return 0, e } var required bool - if e = tx.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&required); e != nil { + if e = tx.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1 FOR UPDATE`, node).Scan(&required); e != nil { return 0, e } if required { var ready bool - e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machines m JOIN lpcc.machine_reports r ON r.node_id=m.node_id AND r.epoch=m.enrollment_epoch AND r.credential_version=m.credential_version JOIN lpcc.payment_machines p ON p.node_id=m.node_id JOIN lpcc.payment_grants g ON g.grant_id::text=r.report#>>'{payment,grant_id}' AND g.node_id=m.node_id AND g.epoch=m.enrollment_epoch WHERE m.node_id=$1 AND r.component='runtime' AND r.generation=$2 AND r.report->>'config_digest'=$3 AND g.config_digest=$3 AND g.pod_uid=r.report#>>'{payment,pod_uid}' AND g.payment_generation=p.generation AND r.received_at>now()-interval '2 minutes' AND (r.report->>'observed_at')::timestamptz>now()-interval '2 minutes' AND NOT COALESCE((r.report->>'clock_uncertain')::boolean,false) AND r.report#>>'{payment,applied}'='true' AND r.report#>>'{payment,queue_known}'='true' AND r.report#>>'{payment,unsettled}'='0' AND (r.report#>>'{payment,generation}')::bigint=p.generation AND g.observed_at IS NOT NULL AND g.revoked_at IS NULL)`, node, metadata.Generation, metadata.ConfigDigest).Scan(&ready) + e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machines m JOIN lpcc.machine_reports r ON r.node_id=m.node_id AND r.epoch=m.enrollment_epoch AND r.credential_version=m.credential_version JOIN lpcc.onchain_state p ON p.node_id=m.node_id JOIN lpcc.onchain_grants g ON g.grant_id::text=r.report#>>'{onchain,grant_id}' AND g.node_id=m.node_id AND g.epoch=m.enrollment_epoch WHERE m.node_id=$1 AND r.component='runtime' AND r.generation=$2 AND r.report->>'config_digest'=$3 AND g.config_digest=$3 AND g.pod_uid=r.report#>>'{onchain,pod_uid}' AND g.onchain_generation=p.generation AND r.received_at>now()-interval '2 minutes' AND (r.report->>'observed_at')::timestamptz>now()-interval '2 minutes' AND NOT COALESCE((r.report->>'clock_uncertain')::boolean,false) AND r.report#>>'{onchain,applied}'='true' AND r.report#>>'{onchain,queue_known}'='true' AND r.report#>>'{onchain,unsettled}'='0' AND (r.report#>>'{onchain,generation}')::bigint=p.generation AND g.observed_at IS NOT NULL AND g.revoked_at IS NULL)`, node, metadata.Generation, metadata.ConfigDigest).Scan(&ready) if e != nil { return 0, e } if !ready { - return 0, errors.New("restore payment state and obtain fresh zero-unsettled evidence before acknowledging recovery") + return 0, errors.New("restore onchain state and obtain fresh zero-unsettled evidence before acknowledging recovery") } - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_machines SET recovery_required=false WHERE node_id=$1`, node); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET recovery_required=false WHERE node_id=$1`, node); e != nil { return 0, e } - if e = writeAudit(ctx, tx, "system", "deployment:payments", "payment.recover", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(revision + 1)}, "success", "recovery_acknowledged"); e != nil { + if e = writeAudit(ctx, tx, "system", "deployment:onchain", "onchain.recover", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(revision + 1)}, "success", "recovery_acknowledged"); e != nil { return 0, e } changed = true } } if expected > revision || (changed && expected != revision) { - return 0, problem(409, "payment_revision_changed", "Payment infrastructure changed.") + return 0, problem(409, "onchain_revision_changed", "Onchain infrastructure changed.") } if changed { revision++ - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.payment_revision SET revision=$1 WHERE id=true`, revision); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_revision SET revision=$1 WHERE id=true`, revision); e != nil { return 0, e } } diff --git a/api/internal/controlplane/payment_test.go b/api/internal/controlplane/onchain_test.go similarity index 66% rename from api/internal/controlplane/payment_test.go rename to api/internal/controlplane/onchain_test.go index 2ffd062..1e7607b 100644 --- a/api/internal/controlplane/payment_test.go +++ b/api/internal/controlplane/onchain_test.go @@ -8,84 +8,83 @@ import ( "testing" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" - "github.com/livepeer/control-center/api/internal/controlplane/payments" "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/connector" "github.com/livepeer/control-center/runtime/contract" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/orchestrator" - "github.com/livepeer/control-center/runtime/payment" ) -func onchainSettings(t *testing.T, s *Server) payment.Config { +func onchainSettings(t *testing.T, s *Server) onchain.Config { t.Helper() dir := t.TempDir() - s.params.PaymentSecretsDir = dir - s.params.PaymentWebhookSecret = strings.Repeat("w", 32) + s.params.OnchainSecretsDir = dir + s.params.OnchainWebhookSecret = strings.Repeat("w", 32) if e := os.WriteFile(filepath.Join(dir, "rpc-v1"), []byte("https://rpc.example/private-token"), 0600); e != nil { t.Fatal(e) } - return payment.Config{Version: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://api.example/redemption", WeiPerUSD: "1000000000000000", TicketFaceValue: "1000", TicketWinProb: "100", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} + return onchain.Config{Version: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 123, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://api.example/redemption", WeiPerUSD: "1000000000000000", TicketFaceValue: "1000", TicketWinProb: "100", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} } -func TestPaymentApplyAtomicBindingAndSecretVersions(t *testing.T) { +func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" - in := paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}} - if rev, e := s.applyPayments(t.Context(), in, 0); e != nil || rev != 1 { + in := onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}} + if rev, e := s.applyOnchain(t.Context(), in, 0); e != nil || rev != 1 { t.Fatal(rev, e) } - if rev, e := s.applyPayments(t.Context(), in, 1); e != nil || rev != 1 { + if rev, e := s.applyOnchain(t.Context(), in, 1); e != nil || rev != 1 { t.Fatal("retry", rev, e) } - if rev, e := s.applyPayments(t.Context(), in, 0); e != nil || rev != 1 { + if rev, e := s.applyOnchain(t.Context(), in, 0); e != nil || rev != 1 { t.Fatal("lost response retry", rev, e) } stale := c stale.CredentialRevision++ - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: stale}}, 0); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: stale}}, 0); e == nil { t.Fatal("stale edit accepted") } var n int - if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`).Scan(&n); e != nil || n != 1 { + if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='onchain.apply'`).Scan(&n); e != nil || n != 1 { t.Fatal(n, e) } // Omission and immutable bindings fail without committing another audit event. - other := payment.Offchain() - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{"lp-bbbbbbbbbbbbbbbb": other}}, 1); e == nil { + other := onchain.Offchain() + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{"lp-bbbbbbbbbbbbbbbb": other}}, 1); e == nil { t.Fatal("omission disabled onchain machine") } - for _, mutate := range []func(*payment.Config){func(c *payment.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *payment.Config) { c.ChainID++ }, func(c *payment.Config) { c.TicketWinProb = "0" }} { + for _, mutate := range []func(*onchain.Config){func(c *onchain.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *onchain.Config) { c.ChainID++ }, func(c *onchain.Config) { c.TicketWinProb = "0" }} { next := c mutate(&next) - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: next}}, 1); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: next}}, 1); e == nil { t.Fatal("invalid change accepted") } } - if e := os.WriteFile(filepath.Join(s.params.PaymentSecretsDir, "rpc-v1"), []byte("https://rpc.example/changed-secret"), 0600); e != nil { + if e := os.WriteFile(filepath.Join(s.params.OnchainSecretsDir, "rpc-v1"), []byte("https://rpc.example/changed-secret"), 0600); e != nil { t.Fatal(e) } - if _, e := s.applyPayments(t.Context(), in, 1); e == nil { + if _, e := s.applyOnchain(t.Context(), in, 1); e == nil { t.Fatal("overwritten secret version accepted") } - if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`).Scan(&n); e != nil || n != 1 { + if e := s.db.QueryRow(`SELECT count(*) FROM lpcc.admin_audit_events WHERE action='onchain.apply'`).Scan(&n); e != nil || n != 1 { t.Fatal("partial commit", n, e) } } -func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { +func TestOnchainCredentialsWebhookAndForcedRecovery(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) node := machine["node_id"] - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}}, 0); e != nil { t.Fatal(e) } - cfg, e := payments.Load(t.Context(), s.db, node) + cfg, e := loadOnchain(t.Context(), s.db, node) if e != nil { t.Fatal(e) } // Install an applying bundle; this test exercises the real API boundary, not // Kubernetes attestation (covered by the Runtime consumer tests). - desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: machine["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: cfg, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: machine["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: cfg, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} b, digest, e := machineconfig.Build(desired) if e != nil { t.Fatal(e) @@ -97,8 +96,8 @@ func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { var meta contract.Metadata json.Unmarshal(files["runtime.json"], &meta) launch := connector.Launch{PodName: "orchestrator-test", PodUID: "uid-test", LaunchID: strings.Repeat("a", 32), ProcessID: strings.Repeat("b", 64)} - in := orchestrator.Request{Launch: launch, PaymentGeneration: cfg.Generation, ConfigDigest: meta.ConfigDigest} - path := "/v1/nodes/" + node + "/payment/credentials" + in := orchestrator.Request{Launch: launch, OnchainGeneration: cfg.Generation, ConfigDigest: meta.ConfigDigest} + path := "/v1/nodes/" + node + "/onchain/credentials" requireStatus(t, request(t, s, "POST", path, "session-a", in), 401) w := request(t, s, "POST", path, machine["token"], in) requireStatus(t, w, 200) @@ -123,17 +122,17 @@ func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { return d.Status } h := map[string][]string{"Authorization": {strings.TrimPrefix(g.Headers, "Authorization: ")}} - if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 200 { + if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 200 { t.Fatal("valid submission denied") } - if webhook("0x"+strings.Repeat("3", 40), h, s.params.PaymentWebhookSecret) != 403 { + if webhook("0x"+strings.Repeat("3", 40), h, s.params.OnchainWebhookSecret) != 403 { t.Fatal("cross recipient allowed") } if webhook(c.Recipient, h, "wrong-service-secret") != 401 { t.Fatal("service authentication bypass") } h["authorization"] = h["Authorization"] - if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 403 { + if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 403 { t.Fatal("duplicate authorization allowed") } delete(h, "authorization") @@ -141,17 +140,17 @@ func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { if _, e = s.db.Exec(`UPDATE lpcc.machines SET credential_version=credential_version+1 WHERE node_id=$1`, node); e != nil { t.Fatal(e) } - if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 200 { + if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 200 { t.Fatal("refresh revoked retained grant") } if e = s.RetireMachine(t.Context(), node); e != nil { t.Fatal(e) } - if webhook(c.Recipient, h, s.params.PaymentWebhookSecret) != 403 { + if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 403 { t.Fatal("forced retirement did not revoke") } var recovery bool - if e = s.db.QueryRow(`SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&recovery); e != nil || !recovery { + if e = s.db.QueryRow(`SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&recovery); e != nil || !recovery { t.Fatal(recovery, e) } fresh := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -159,16 +158,16 @@ func TestPaymentCredentialsWebhookAndForcedRecovery(t *testing.T) { t.Fatal("enrollment not replaced") } c.Recipient = "0x" + strings.Repeat("3", 40) - if _, e = s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: c}}, 1); e == nil { + if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}}, 1); e == nil { t.Fatal("re-enrollment reset pinned recipient") } } -func TestOnchainActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *testing.T) { +func TestOnchainActivationAndRemovalRequireFreshPostDrainOnchainEvidence(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { t.Fatal(e) } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -191,48 +190,48 @@ func TestOnchainActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *test } return m } - if metadata().PaymentActive { + if metadata().OnchainActive { t.Fatal("saved setting treated as active onchain operation") } m0 := metadata() launch := orchestrator.Launch{PodName: "orchestrator-test", PodUID: "node-pod", LaunchID: strings.Repeat("a", 32), ProcessID: strings.Repeat("b", 64)} - w := request(t, s, "POST", "/v1/nodes/"+node+"/payment/credentials", c["token"], orchestrator.Request{Launch: launch, PaymentGeneration: m0.Payment.Generation, ConfigDigest: m0.ConfigDigest}) + w := request(t, s, "POST", "/v1/nodes/"+node+"/onchain/credentials", c["token"], orchestrator.Request{Launch: launch, OnchainGeneration: m0.Onchain.Generation, ConfigDigest: m0.ConfigDigest}) requireStatus(t, w, 200) var grant orchestrator.Grant json.Unmarshal(w.Body.Bytes(), &grant) report := func(known bool, n int64) { t.Helper() m := metadata() - r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Payment: &payment.Observation{Generation: m.Payment.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) + r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Onchain: &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) requireStatus(t, request(t, s, "POST", "/v1/nodes/"+node+"/status", c["token"], r), 200) } - if _, e := s.db.Exec(`UPDATE lpcc.payment_machines SET recovery_required=true WHERE node_id=$1`, node); e != nil { + if _, e := s.db.Exec(`UPDATE lpcc.onchain_state SET recovery_required=true WHERE node_id=$1`, node); e != nil { t.Fatal(e) } - in := paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}} - if _, e := s.applyPayments(t.Context(), in, 1, node); e == nil { - t.Fatal("recovery acknowledged without fresh payment evidence") + in := onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}} + if _, e := s.applyOnchain(t.Context(), in, 1, node); e == nil { + t.Fatal("recovery acknowledged without fresh onchain evidence") } report(true, 0) // A fresh report from a previously delivered configuration cannot clear - // recovery after publication changes, even within the same payment generation. + // recovery after publication changes, even within the same onchain generation. if _, e := s.db.Exec(`UPDATE lpcc.machine_reports SET report=jsonb_set(report,'{config_digest}',to_jsonb(repeat('f',64))) WHERE node_id=$1 AND component='runtime'`, node); e != nil { t.Fatal(e) } - if _, e := s.applyPayments(t.Context(), in, 1, node); e == nil { + if _, e := s.applyOnchain(t.Context(), in, 1, node); e == nil { t.Fatal("recovery acknowledged evidence for a different delivered configuration") } report(true, 0) - if rev, e := s.applyPayments(t.Context(), in, 1, node); e != nil || rev != 2 { + if rev, e := s.applyOnchain(t.Context(), in, 1, node); e != nil || rev != 2 { t.Fatal("explicit restored-state acknowledgement", rev, e) } - if rev, e := s.applyPayments(t.Context(), in, 1, node); e != nil || rev != 2 { + if rev, e := s.applyOnchain(t.Context(), in, 1, node); e != nil || rev != 2 { t.Fatal("recovery acknowledgement retry", rev, e) } if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } - if !metadata().PaymentActive { + if !metadata().OnchainActive { t.Fatal("fresh applied Node did not activate") } adminA(t, s) @@ -268,7 +267,7 @@ func TestOnchainActivationAndRemovalRequireFreshPostDrainPaymentEvidence(t *test t.Fatal("settled ordinary removal did not complete") } var drained, recovery bool - if e := s.db.QueryRow(`SELECT drained,recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&drained, &recovery); e != nil || !drained || recovery { + if e := s.db.QueryRow(`SELECT drained,recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&drained, &recovery); e != nil || !drained || recovery { t.Fatal("ordinary retirement misclassified", drained, recovery, e) } } @@ -277,7 +276,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { t.Fatal(e) } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -291,7 +290,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { issue := func(nonce string) orchestrator.Grant { t.Helper() l := orchestrator.Launch{PodName: "orchestrator-test", PodUID: "same-pod", LaunchID: strings.Repeat(nonce, 32), ProcessID: strings.Repeat(nonce, 64)} - w := request(t, s, "POST", "/v1/nodes/"+node+"/payment/credentials", c["token"], orchestrator.Request{Launch: l, PaymentGeneration: m.Payment.Generation, ConfigDigest: m.ConfigDigest}) + w := request(t, s, "POST", "/v1/nodes/"+node+"/onchain/credentials", c["token"], orchestrator.Request{Launch: l, OnchainGeneration: m.Onchain.Generation, ConfigDigest: m.ConfigDigest}) requireStatus(t, w, 200) var g orchestrator.Grant if e := json.Unmarshal(w.Body.Bytes(), &g); e != nil { @@ -307,27 +306,27 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { } observe := func(g orchestrator.Grant) { t.Helper() - if e := s.observePaymentGrant(t.Context(), machine, &payment.Observation{Generation: m.Payment.Generation, Mode: "onchain", PodUID: "same-pod", GrantID: g.GrantID, Applied: true, Ready: true}, m.ConfigDigest); e != nil { + if e := s.observeOnchainGrant(t.Context(), machine, &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "same-pod", GrantID: g.GrantID, Applied: true, Ready: true}, m.ConfigDigest); e != nil { t.Fatal(e) } } observe(old) var revoked bool - if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, newer.GrantID).Scan(&revoked); e != nil || revoked { + if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.onchain_grants WHERE grant_id=$1`, newer.GrantID).Scan(&revoked); e != nil || revoked { t.Fatal("old observation revoked an applying grant", e) } observe(newer) observe(old) - if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, old.GrantID).Scan(&revoked); e != nil || !revoked { + if e := s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.onchain_grants WHERE grant_id=$1`, old.GrantID).Scan(&revoked); e != nil || !revoked { t.Fatal("replacement did not retire predecessor", e) } third := issue("c") if !third.RequireState { t.Fatal("initialized onchain database can be silently recreated") } - off := payment.Offchain() - off.Generation = m.Payment.Generation + 1 - desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: c["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Payment: off, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + off := onchain.Offchain() + off.Generation = m.Onchain.Generation + 1 + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: c["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: off, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} b, digest, e := machineconfig.Build(desired) if e != nil { t.Fatal(e) @@ -335,29 +334,29 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { files, _ = artifact.Read(b) var replacement contract.Metadata json.Unmarshal(files["runtime.json"], &replacement) - o := &payment.Observation{Generation: off.Generation, Mode: "offchain", PodUID: "offchain-pod", Applied: true} - if e = s.observePaymentGrant(t.Context(), machine, o, m.ConfigDigest); e != nil { + o := &onchain.Observation{Generation: off.Generation, Mode: "offchain", PodUID: "offchain-pod", Applied: true} + if e = s.observeOnchainGrant(t.Context(), machine, o, m.ConfigDigest); e != nil { t.Fatal(e) } - if e = s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.payment_grants WHERE grant_id=$1`, third.GrantID).Scan(&revoked); e != nil || revoked { + if e = s.db.QueryRow(`SELECT revoked_at IS NOT NULL FROM lpcc.onchain_grants WHERE grant_id=$1`, third.GrantID).Scan(&revoked); e != nil || revoked { t.Fatal("offchain observation revoked a still-held onchain grant", e) } if _, e = s.db.Exec(`UPDATE lpcc.machine_configs SET bundle=$2,sha256=$3 WHERE node_id=$1`, node, b, digest); e != nil { t.Fatal(e) } - if e = s.observePaymentGrant(t.Context(), machine, o, replacement.ConfigDigest); e != nil { + if e = s.observeOnchainGrant(t.Context(), machine, o, replacement.ConfigDigest); e != nil { t.Fatal(e) } - if count(t, s, `SELECT count(*) FROM lpcc.payment_grants WHERE revoked_at IS NULL`) != 0 { + if count(t, s, `SELECT count(*) FROM lpcc.onchain_grants WHERE revoked_at IS NULL`) != 0 { t.Fatal("applied offchain replacement retained submission grants") } } -func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { +func TestOnchainIsolationAndGenericCatalogCompatibility(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) onchainNode := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{onchainNode: cfg}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{onchainNode: cfg}}, 0); e != nil { t.Fatal(e) } a := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -378,15 +377,15 @@ func TestPaymentIsolationAndGenericCatalogCompatibility(t *testing.T) { } var meta contract.Metadata json.Unmarshal(files["runtime.json"], &meta) - if meta.Payment.Onchain() || strings.Contains(string(files["runtime.json"]), cfg.Recipient) { - t.Fatal("cross-machine payment delivery") + if meta.Onchain.Onchain() || strings.Contains(string(files["runtime.json"]), cfg.Recipient) { + t.Fatal("cross-machine onchain delivery") } - requireStatus(t, request(t, s, "POST", "/v1/nodes/"+a["node_id"]+"/payment/credentials", b["token"], map[string]any{}), 401) - // Browser administration has no payment-settings mutation interface. - requireStatus(t, request(t, s, "PUT", "/api/admin/machines/"+a["node_id"]+"/payment", "session-a", cfg), 404) + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+a["node_id"]+"/onchain/credentials", b["token"], map[string]any{}), 401) + // Browser administration has no onchain-settings mutation interface. + requireStatus(t, request(t, s, "PUT", "/api/admin/machines/"+a["node_id"]+"/onchain", "session-a", cfg), 404) } -func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { +func TestConcurrentOnchainApplyCannotCommitTwoDifferentTargets(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" @@ -395,7 +394,7 @@ func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { copy := c copy.CredentialRevision = uint64(n + 1) go func() { - _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: copy}}, 0) + _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: copy}}, 0) errors <- e }() } @@ -408,7 +407,7 @@ func TestConcurrentPaymentApplyCannotCommitTwoDifferentTargets(t *testing.T) { if successes != 1 { t.Fatal("concurrent edits both committed", successes) } - if count(t, s, `SELECT count(*) FROM lpcc.payment_versions`) != 1 || count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events WHERE action='payment.apply'`) != 1 { + if count(t, s, `SELECT count(*) FROM lpcc.onchain_configs`) != 1 || count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events WHERE action='onchain.apply'`) != 1 { t.Fatal("configuration and audit diverged") } } @@ -417,7 +416,7 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) s := newTestServer(t) cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { t.Fatal(e) } enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -441,16 +440,16 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) t.Fatal(e) } after := read() - if after.ConfigDigest == before.ConfigDigest || !after.Payment.Onchain() || after.PaymentActive || after.Payment.Generation != before.Payment.Generation { - t.Fatal("unapproved onchain target could not repair its image under the same payment binding", after) + if after.ConfigDigest == before.ConfigDigest || !after.Onchain.Onchain() || after.OnchainActive || after.Onchain.Generation != before.Onchain.Generation { + t.Fatal("unapproved onchain target could not repair its image under the same onchain binding", after) } - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: payment.Offchain()}}, 1); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: onchain.Offchain()}}, 1); e != nil { t.Fatal(e) } if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } - if !read().Payment.Onchain() { + if !read().Onchain.Onchain() { t.Fatal("failed onchain startup bypassed the settlement gate to offchain") } } @@ -459,21 +458,21 @@ func TestForcedRetirementCannotUseDesiredOffchainAsSettlementProof(t *testing.T) s := newTestServer(t) cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: cfg}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { t.Fatal(e) } _ = enroll(t, s, ownerA, strings.Repeat("a", 64)) - if _, e := s.db.Exec(`UPDATE lpcc.payment_machines SET initialized=true WHERE node_id=$1`, node); e != nil { + if _, e := s.db.Exec(`UPDATE lpcc.onchain_state SET initialized=true WHERE node_id=$1`, node); e != nil { t.Fatal(e) } - if _, e := s.applyPayments(t.Context(), paymentInput{Version: 1, Machines: map[string]payment.Config{node: payment.Offchain()}}, 1); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: onchain.Offchain()}}, 1); e != nil { t.Fatal(e) } if e := s.RetireMachine(t.Context(), node); e != nil { t.Fatal(e) } var required bool - if e := s.db.QueryRow(`SELECT recovery_required FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&required); e != nil || !required { + if e := s.db.QueryRow(`SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&required); e != nil || !required { t.Fatal("pending disable hid retained onchain state", required, e) } } diff --git a/api/internal/controlplane/payments/store.go b/api/internal/controlplane/payments/store.go deleted file mode 100644 index 8f8ac0e..0000000 --- a/api/internal/controlplane/payments/store.go +++ /dev/null @@ -1,31 +0,0 @@ -package payments - -import ( - "context" - "database/sql" - "encoding/json" - "errors" - - "github.com/livepeer/control-center/runtime/payment" -) - -type Querier interface { - QueryRowContext(context.Context, string, ...any) *sql.Row -} - -func Load(ctx context.Context, q Querier, node string) (payment.Config, error) { - c := payment.Offchain() - var b []byte - err := q.QueryRowContext(ctx, `SELECT config FROM lpcc.payment_machines WHERE node_id=$1`, node).Scan(&b) - if errors.Is(err, sql.ErrNoRows) { - return c, nil - } - if err != nil { - return c, err - } - err = json.Unmarshal(b, &c) - if err == nil { - err = c.Validate() - } - return c, err -} diff --git a/api/internal/controlplane/registry_store.go b/api/internal/controlplane/registry_store.go index 9c81fd8..428c7ed 100644 --- a/api/internal/controlplane/registry_store.go +++ b/api/internal/controlplane/registry_store.go @@ -9,7 +9,6 @@ import ( "time" "uuid" - "github.com/livepeer/control-center/api/internal/controlplane/payments" "github.com/livepeer/control-center/schema" ) @@ -95,7 +94,7 @@ func revisionForBinding(ctx context.Context, tx *sql.Tx, current *schema.Revisio if err != nil { return r, err } - config, err := payments.Load(ctx, tx, node) + config, err := loadOnchain(ctx, tx, node) if err != nil { return r, err } diff --git a/api/internal/controlplane/server.go b/api/internal/controlplane/server.go index d25e8f2..3abae63 100644 --- a/api/internal/controlplane/server.go +++ b/api/internal/controlplane/server.go @@ -118,7 +118,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /v1/nodes/{node_id}/apps/{revision_id}/status", s.assignmentStatus) mux.HandleFunc("POST /v1/nodes/register", s.register) mux.HandleFunc("GET /v1/nodes/{node_id}/config", s.configuration) - mux.HandleFunc("POST /v1/nodes/{node_id}/payment/credentials", s.paymentCredentials) + mux.HandleFunc("POST /v1/nodes/{node_id}/onchain/credentials", s.onchainCredentials) mux.HandleFunc("POST /internal/redemption/authorize", s.redemptionAuthorize) mux.HandleFunc("POST /v1/nodes/{node_id}/credentials/refresh", s.refreshCredentials) mux.HandleFunc("POST /v1/nodes/{node_id}/tunnel/connector-token", s.connectorToken) diff --git a/deploy/README.md b/deploy/README.md index 9ef8fe3..5845ddd 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -49,8 +49,6 @@ docker build -f ../runtime/services/Dockerfile.tunnel \ --build-arg RUNTIME_IMAGE=127.0.0.1:63812/controlcenter/runtime@sha256: \ -t 127.0.0.1:63812/controlcenter/connector:staging ../runtime/services docker push 127.0.0.1:63812/controlcenter/connector:staging -# For onchain operation, build a compatible Node binary and package its image with -# the Runtime startup wrapper (see docs/onchain-operation.md). # Set RuntimeImage, RuntimeConnectorImage, and RuntimeNodeImage in config.toml # using the public registry hostname and the digests returned by the pushes. docker compose config --quiet @@ -63,14 +61,37 @@ and node address exclusions. Update `TunnelNodeAddresses` with the public and management addresses of every machine before enrollment; the bootstrap installer's origin firewall remains required. -For fresh managed onchain installations, follow [the payment runbook](../docs/onchain-operation.md) -for the redeemer Compose profile, credential mounts and deployment settings. +## Onchain setup -The deployed image digests and source provenance are recorded in -[`staging-images.json`](staging-images.json). The initial staging build includes -the existing working tree changes. Its matching Node source snapshot is retained -on the server at `/opt/controlcenter/node-source`. Publish a compatible Node image -before changing `RuntimeNodeImage`. +Package the Node image with Runtime's startup wrapper and set `RuntimeNodeImage` +to the pushed digest. Use the same Node build for `LIVEPEER_REDEEMER_IMAGE`. + +```sh +docker build -f ../runtime/services/Dockerfile.node \ + --build-arg NODE_IMAGE= \ + --build-arg RUNTIME_IMAGE= \ + -t ../runtime/services +docker push +``` + +Copy `redeemer.example.toml` to `redeemer.toml`. Create owner-only files readable +by UID 65532: + +- `secrets/onchain-rpc/`: HTTPS RPC URL. +- `secrets/onchain-webhook-auth`: random secret of at least 32 bytes. +- `secrets/redeemer/keystore.json`, `password`, and `rpc`: redeemer wallet inputs. +- `secrets/redeemer/auth-url`: `http://api:43812/internal/redemption/authorize`. +- `secrets/redeemer/auth-headers`: `Authorization: Bearer `. + +Set `OnchainSecretsDir` and `OnchainWebhookSecretFile` in `config.toml`, then start: + +```sh +docker compose -f compose.yaml -f compose.onchain.yaml --profile onchain up -d +``` + +The wallet is mounted only into the redeemer, which uses the separate +`redeemer-data` volume. Only HTTPS ticket submission is exposed through ingress. +Apply machine settings using the [operations runbook](../docs/operations.md#onchain-operation). ## Operate diff --git a/deploy/compose.onchain.yaml b/deploy/compose.onchain.yaml index 531f156..17a9a14 100644 --- a/deploy/compose.onchain.yaml +++ b/deploy/compose.onchain.yaml @@ -17,12 +17,12 @@ services: api: volumes: - - ./secrets/payment-rpc:/run/payment-rpc:ro + - ./secrets/onchain-rpc:/run/onchain-rpc:ro secrets: - - payment-webhook-auth + - onchain-webhook-auth secrets: - payment-webhook-auth: - file: ./secrets/payment-webhook-auth + onchain-webhook-auth: + file: ./secrets/onchain-webhook-auth volumes: redeemer-data: diff --git a/deploy/config.example.toml b/deploy/config.example.toml index 74405ea..0e8da86 100644 --- a/deploy/config.example.toml +++ b/deploy/config.example.toml @@ -35,6 +35,6 @@ TunnelNodeAddresses = [""] DiscoveryRefreshInterval = "5m" DiscoveryMaxFailedRefreshes = 6 -# Enable with compose.onchain.yaml after applying deployment-owned payment settings. -# PaymentSecretsDir = "/run/payment-rpc" -# PaymentWebhookSecretFile = "/run/secrets/payment-webhook-auth" +# Enable with compose.onchain.yaml after applying deployment-owned onchain settings. +# OnchainSecretsDir = "/run/onchain-rpc" +# OnchainWebhookSecretFile = "/run/secrets/onchain-webhook-auth" diff --git a/deploy/payments.example.json b/deploy/onchain.example.json similarity index 100% rename from deploy/payments.example.json rename to deploy/onchain.example.json diff --git a/docs/acceptance/119-managed-payments.json b/docs/acceptance/119-managed-payments.json deleted file mode 100644 index b30aed3..0000000 --- a/docs/acceptance/119-managed-payments.json +++ /dev/null @@ -1,298 +0,0 @@ -{ - "version": 1, - "run": "cc-e2e-1112071043-bcbd", - "date": "2026-11-12", - "scope": "fresh installations", - "implementation_revision": "fa744f162a4aea818a6031ada21ed10ee49f351a", - "source_tree_sha256": "88e91434d846bf03a328ec75dff4f76322dadd6eccb49da9c03350038eb98b36", - "api_binary_sha256": "2373492e60bf6e6ddd1e99a6878e72deba1faaa0c5de1d6e98587dcc1f7b1c61", - "management_runtime_binary_sha256": "3dcb8489a68907629de585dad25a5cb11cb13b38c62236954922ebf25592deef", - "functional_node_source": { - "mode": "working-tree", - "revision": "0ee73c000bed553f5a02e40c972c1b5bd2d0ba80", - "sha256": "b9e54ae392831706c3ce85baa9cd12ecd227d90e807376bcb74262c767f3bd90" - }, - "functional_images": { - "runtime": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", - "connector": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/connector@sha256:4174086c856a6b85a42be12cd09becf37e75ee8ba54d72949f3a141235156226", - "node": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/node@sha256:a3dab72b2f364f88bc64bcc954e1ede32d43bcb7c6c288165c25a71740e2b57a", - "echo": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/echo@sha256:b20ba6e917c81842f707a3fa4a581c073ceff7c22782b7ec993abe5c27d7863b" - }, - "landed_wrapper_build": { - "node_commit": "3533951e66584531a54a771d21c1388873439099", - "node_image": "ghcr.io/livepeer/node@sha256:8c13bbd6abf8d7879c4999ea10d537996a6d54b330cfd5303ebf03b3e4782be9", - "runtime_image": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", - "wrapper_image": "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/managed-node@sha256:cc0a711c242df53a1d621082f11876cdad3b04983afe0e87c89fa7529ac28fb9", - "actual_dockerfile_built": true, - "nonroot": true - }, - "catalog": [ - { - "revision_id": "9a96a95f-ff0d-42b3-8ebb-5c6893ba4adb", - "digest": "sha256:2253e9cf61444a3da745db4ca77d3c973378b88f43d50bebfaa357ef79597d05", - "price": { - "amount": "0.001", - "currency": "usd", - "unit": "hour" - } - }, - { - "revision_id": "e3b5ceb6-cb7f-4e40-b1c6-469f06d2901f", - "digest": "sha256:c8482a7f32e1cd6bd56e7a48e5ffc6fc612dc660a34226a5ec51a789d6fa4668", - "price": { - "amount": "0.001", - "currency": "usd", - "unit": "fixed" - } - } - ], - "workers": { - "count": 2, - "type": "e2-standard-4", - "k3s": "v1.37.2+k3s1", - "settings": [ - "private RPC and redemption", - "public RPC and redemption" - ] - }, - "checks": { - "routing-evidence": [ - { - "check": "orchestrator_exact_private_endpoint", - "role": "node-a", - "port": 41143, - "reachable": true - }, - { - "check": "orchestrator_exact_private_endpoint", - "role": "node-a", - "port": 41144, - "reachable": true - }, - { - "check": "all_app_workloads_isolated_from_private_payment_endpoints", - "role": "node-a", - "workloads": 3 - }, - { - "check": "orchestrator_exact_private_endpoint", - "role": "node-b", - "port": 41143, - "reachable": false - }, - { - "check": "orchestrator_exact_private_endpoint", - "role": "node-b", - "port": 41144, - "reachable": false - }, - { - "check": "all_app_workloads_isolated_from_private_payment_endpoints", - "role": "node-b", - "workloads": 3 - }, - { - "check": "unrelated_private_destination_blocked", - "role": "node-a", - "host_baseline_reachable": true - }, - { - "check": "unrelated_private_destination_blocked", - "role": "node-b", - "host_baseline_reachable": true - }, - { - "check": "unready_service_keeps_management_routing", - "same_pod": true, - "protected_discovery_status": 200, - "protected_stop_status": 404, - "sibling_payment_ready": true - }, - { - "check": "private_rpc_outage_recovered", - "same_pod": true - } - ], - "retained-outage-evidence": { - "onchain_session_survived_rpc_readiness_loss": true, - "protected_diagnostics_reachable": true, - "retained_session_stop_succeeded_while_unready": true - }, - "disable-rollback-evidence": [ - { - "check": "disable_blocked_by_real_queued_ticket", - "onchain_workload_retained": true, - "submission_grant_retained": true, - "sibling_unchanged": true - }, - { - "check": "rollback_reuses_immutable_inputs_with_new_grant", - "payment_generation": 4, - "retained_database_owner_only": true, - "sibling_unchanged": true - } - ], - "forced-recovery-evidence": [ - { - "check": "forced_retirement_with_queued_tickets", - "submission_grants_revoked_immediately": true, - "recovery_required": true, - "payment_drained": false, - "database_preserved": true, - "unhanded_tickets": 1 - }, - { - "check": "reenrollment_recovers_retained_payment_state", - "new_enrollment": true, - "recipient_pin_preserved": true, - "tickets_preserved": true, - "new_credentials_authorized": true, - "recovery_flag_preserved": true - } - ], - "management-refresh-evidence": { - "management_credential_version_advanced": true, - "node_replaced_after_managed_drain": true, - "replacement_grant_observed": true, - "older_submission_grants_revoked": true, - "payment_storage_preserved": true - }, - "backpressure-evidence": { - "queue_limit": 2, - "actual_unsettled": 2, - "onchain_mode_retained": true, - "local_admission_not_ready": true - }, - "lost-ack-evidence": { - "durable_redeemer_acceptances": 9, - "acknowledgements_lost": 6, - "remote_health_degraded_then_healthy": true - }, - "ordinary-retirement-evidence": { - "ordinary_removal_blocked_by_actual_unsettled_tickets": true, - "onchain_workload_retained": true, - "submission_grants_retained": true, - "completion_not_acknowledged": true - }, - "credential-log-scan-evidence": { - "sources_scanned": 8, - "known_credentials_absent": true, - "affected_sources": [] - }, - "settlement-restart-evidence": { - "transaction_hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780", - "same_signed_bytes_after_restart": true, - "same_nonce_after_restart": true, - "duplicate_transaction_identities": false - }, - "settlement-final-evidence": { - "transactions": [ - { - "hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780", - "nonce": "0", - "phase": "confirmed", - "raw_sha256": "0c6bb19ee1b6db7a9633f64884e71085e825521247ef81fa23da444671d35c28", - "acknowledged": true - } - ], - "settled": 1, - "tickets": 6 - } - }, - "settlement": { - "budget": { - "approved_maximum_usd": "0.40", - "ticket_liability_usd": "0.20", - "gas_usd": "0.20", - "internal_max_authorizations": 9, - "per_ticket_usd": "0.02", - "configured_face_value_wei": "8795613362832", - "replacements": 0, - "fee_ceiling_wei": "45000000" - }, - "additional_authorizations": 7, - "additional_winning_tickets": 1, - "receipt": { - "block_number": "523528218", - "chain_id": 42161, - "effective_gas_price_wei": "20000000", - "gas_cost_wei": "3796600000000", - "gas_used": 189830, - "redeemer_balance_wei": "496203400000000", - "status": 1, - "transaction_hash": "0x1c9c96fbdb8bc9e2ee538339dd53df937b839cee223643bfb621c66f74886780" - }, - "finalized": true, - "unique_redemption_transaction_identities": 1, - "remaining_small_unsettled_tickets": 5 - }, - "cleanup": { - "status": "verified_for_owned_resources", - "run": "cc-e2e-1112071043-bcbd", - "audit_source": "saved post-cleanup final-audit.json and all-runs-audit.json", - "source_inventory_recorded_at": "2026-11-12T10:12:53.350733+00:00", - "cleanup_verified_at": "2026-11-12T10:09:25.022063+00:00", - "owned_gcp_resources": { - "instances": [], - "disks": [], - "firewall-rules": [], - "networks": [], - "subnets": [] - }, - "owned_cloudflare_resources": { - "cfd_tunnel": [], - "access/apps": [], - "access/policies": [], - "access/service_tokens": [], - "dns": [], - "certificates": [] - }, - "temporary_access_credentials_removed": true, - "all_four_attempts_cleaned": true, - "baseline_gcp_instances_missing": [], - "baseline_preservation_exception": { - "unrelated_tunnel_deleted_before_cleanup": true, - "deleted_at": "2026-11-12T08:13:03.063799Z", - "recorded_in_owned_intents": false, - "unconditional_baseline_preservation_passed": false - }, - "other_active_test_run_excluded_from_scope": true, - "owned_cleanup_passed": true, - "payment_backups": "owner-only local recovery archive" - }, - "remaining_acceptance": [ - "#90 responder/verifier and #44 collection contract", - "#93/#118 full verifier/fleet acceptance matrix", - "production image promotion and full production Compose networking acceptance" - ], - "recovery_archive": { - "sqlite_integrity_verified": true, - "postgres_dump_catalog_verified": true, - "component_images": { - "archive_bytes": 188944124, - "sha256": "d4721fe28cb056f4fc3ba670266c520056e95c8f8cb0f843c74e6e0bcf658f22", - "references": [ - "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/managed-node@sha256:cc0a711c242df53a1d621082f11876cdad3b04983afe0e87c89fa7529ac28fb9", - "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/runtime@sha256:1c2ab03692f97ebd36a77edfcfe554fa675f36bfda51fec616e28cc9c27402f1", - "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/connector@sha256:4174086c856a6b85a42be12cd09becf37e75ee8ba54d72949f3a141235156226", - "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/node@sha256:a3dab72b2f364f88bc64bcc954e1ede32d43bcb7c6c288165c25a71740e2b57a", - "cc-e2e-1112071043-bcbd-registry.livepeer.vip/cc/echo@sha256:b20ba6e917c81842f707a3fa4a581c073ceff7c22782b7ec993abe5c27d7863b" - ], - "pinned_manifests_preserved": true - }, - "unsettled_small_tickets": 5, - "payment_drain_complete": false - }, - "evidence_kind": "historical funded run before rebase and onchain terminology revision", - "post_rebase_validation": { - "base_revision": "b45110364d0a9c187c4497f524e3b0b93b4707be", - "mode": "onchain", - "schema_migration": "009_onchain_payments.sql", - "historical_migrations_unchanged": true, - "postgresql_race_suite": "passed", - "go_vet": "passed", - "ui_browser_tests": 41, - "ui_build": "passed", - "funded_rerun": false - } -} diff --git a/docs/acceptance/119-managed-payments.md b/docs/acceptance/119-managed-payments.md deleted file mode 100644 index f18bb52..0000000 --- a/docs/acceptance/119-managed-payments.md +++ /dev/null @@ -1,124 +0,0 @@ -# Managed onchain operation: fresh-install evidence - -Date: 2026-11-12. Run: `cc-e2e-1112071043-bcbd`. - -This records payment/configuration integration for #119. The broader #93/#118 -acceptance gate remains open: #90's versioned responder, trusted verifier and -collection/report contract are still open work. The nonce-echo fixture used here -checks transport and execution correctness; it is not that benchmark verifier. - -This is historical evidence for the recorded source hashes, before the branch -was rebased and its configuration terminology standardized to `onchain`. It is -not a funded rerun of the revised branch. Catalog revision IDs and digests retain -their original values; nonessential fixture names are omitted from the JSON. - -## Environment and provenance - -Two fresh `e2-standard-4` CPU workers ran actual K3s, gVisor app workloads and -keyless Node. A third disposable GCP VM ran the isolated Control Center fixture, -registry, TLS routing and the actual hardened standalone redeemer. Worker A used -private RPC/redemption endpoints with exact IP/port grants; worker B used public -endpoints. Their shared immutable catalog revisions retained exact `0.001 USD` -prices, respectively `hour` and `fixed`, throughout infrastructure changes. - -The redeemer used the actual Compose service and separate persistent database, -UID 65532, read-only root, dropped capabilities and no-new-privileges. This harness -used host networking for the redeemer's loopback connection to the native API; -it does not establish the full production Compose networking acceptance case. -The signing key was mounted only into the redeemer. No application received -payment, RPC, enrollment or origin-access credentials. - -Node's outbound-header dependency landed in -[Node #85](https://github.com/livepeer/node/pull/85), commit -`3533951e66584531a54a771d21c1388873439099`. Its main-branch CI and both published -architectures passed. The committed wrapper Dockerfile was also built against -that landed Node image and the tested Runtime. The accompanying JSON separates -that built package from the earlier functional fixture image and records exact -source/binary hashes and image digests. These disposable-registry pins are test -artifacts, not a production release promotion. Their OCI images were archived -before registry teardown. - -## Verified outcomes - -- Full PostgreSQL-backed API/Runtime/schema race suite, `go vet`, 41 UI browser - checks and the production UI build passed. All 45 Runtime Linux checks passed - on each worker, including kubectl manifest validation. The later Cloudflare - tombstone regression passed the tunnel race suite. -- Both workers applied payment generation 1 and registered the same catalog - revisions. Actual Node parsed the rendered onchain TOML. Failed onchain configuration - remained onchain/failed and retained the last valid configuration. -- Onchain persistent/hourly and single-shot/fixed calls executed ordinary sandboxed - HTTP requests. A verifier-generated nonce was checked in the response. Origin - access headers were absent from application requests. -- During private RPC loss, the same live Pod became unready while its funded - retained session, protected diagnostics and session stop remained reachable. - The public-RPC sibling remained ready. Recovery needed no Pod replacement. -- Both private endpoints were reachable only from the explicitly allowed - orchestrator. All three apps on each worker and the other orchestrator were - blocked. An unrelated neighboring port was reachable from the host and blocked - from the orchestrator. -- RPC/submission rotation and explicit rollback produced new generations and - grants and retained owner-only SQLite state. The disable/rollback cycle left - the sibling unchanged. A real - unsettled ticket blocked onchain disable; the live onchain workload/grant remained. -- A queue limit of two with two actual unsettled tickets closed local admission - while preserving onchain mode. Restoring capacity restored readiness. -- The redeemer durably accepted three ticket identities while six successful - acknowledgements were deliberately lost. Retries produced nine HTTP - acceptances, three unique stored tickets and degraded-then-healthy remote - handoff observations. Empty worker passes did not establish healthy handoff. -- Forced removal with one unhanded winning ticket immediately revoked grants, - retained payment storage and reported recovery required with drain incomplete. - Re-enrollment preserved all tickets and the recipient pin. Ordinary management - refresh drained/replaced Node and retired old grants after observing its - replacement. Public discovery recovered under the new enrollment. -- Real Cloudflare deletion returned a tunnel tombstone without `config_src`. - Matching its retained ID/name allowed predecessor cleanup; foreign/active - ownership checks and late-resource inventory remained enforced. -- Ordinary removal with unsettled tickets retained Node/storage/grants and did - not acknowledge completion. No forced-removal case was reported payment-drained. - -## Funded bounds and remaining gates - -The original campaign used a `0.003 USD` per-authorization ceiling and returned -three signed batches (five tickets). Two earlier unfunded signer requests returned -no signed batch. The five small winning tickets were durably handed off; their -face value did not cover the measured redemption gas ceiling, so settlement and -ordinary payment drain remained blocked by the existing economic guard. - -The operator then approved a maximum `0.40 USD`: `0.20` ticket liability and `0.20` -redeemer gas. The bounded extension allowed at most nine authorizations, each at -most `0.02 USD`, with no fee replacements and a `45,000,000 wei` gas-price ceiling. -Seven authorizations, about `0.018 USD` maximum payout each, produced one additional -winning ticket. Signing stopped immediately. Catalog prices were unchanged. - -Its transaction mined successfully and retained the same signed bytes/nonce -across redeemer restart, then reached finality. It used `189830` gas at -`20000000 wei`, totaling `0.0000037966 ETH`, with one durable transaction identity -and no fee replacement. Exact receipt and final cleanup evidence are recorded in -the accompanying JSON. The five small -unsettled tickets are preserved in separate owner-only Node/redeemer backups; -ordinary drain is not claimed complete for them. - -## Cleanup and recovery retention - -Cleanup was verified at `2026-11-12T10:09:25Z`. The saved post-cleanup inventory -contains no GCP or Cloudflare resources owned by this run; all four attempts -recorded verified cleanup and removed generated access credentials. A separate -active test run was excluded from this ownership scope and left untouched. - -The broader baseline check did not pass unconditionally: an unrelated baseline -tunnel had been deleted at `08:13:03Z`, before this run's `10:03:43Z` teardown. -It was absent from this run's ownership intents. The scoped cleanup result keeps -that exception visible rather than claiming full baseline preservation. - -Consistent Node/redeemer SQLite backups, a Control Center PostgreSQL dump, matching -private recovery inputs and the five pinned component images remain in an -owner-only operator archive. The OCI archive preserves the original pinned -manifests and has a recorded SHA-256. Cloud cleanup did not discard retained -financial state. Recover the five small tickets under their original bindings -and routing/trust inputs; removing infrastructure does not complete payment drain. - -Still outside the completed evidence: #90/#44 verifier/report integration and the -full #93/#118 attribution, offline, cancellation and fleet acceptance matrix. -No case depends on changing an existing installation into this implementation. diff --git a/docs/app-registry.md b/docs/app-registry.md index ec58573..7396a3c 100644 --- a/docs/app-registry.md +++ b/docs/app-registry.md @@ -113,8 +113,8 @@ private `path`, `capacity`, and `price`; paths must be unique and nonnested. ## Pricing policy Catalog prices remain generic and immutable. Assignment and registration compatibility -is evaluated against the target machine's desired and observed Node payment settings. -See [managed onchain operation](onchain-operation.md) for deployment configuration and +is evaluated against the target machine's desired and observed Node onchain settings. +See [operations](operations.md#onchain-operation) for deployment configuration and activation. Publishing a price does not activate onchain operation on a Node. ## Catalog API diff --git a/docs/development.md b/docs/development.md index 7a44110..9dfb37b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -61,3 +61,7 @@ transport, or cleanup failures. Interrupted runs may retain a remote container or temporary directory; inspect the resource identifiers printed by the helper before removing those resources or rerunning. Delete the local run directory when its results are no longer needed. + +## End-to-end tests + +Use the separate `e2e-clankery` harness; commands are in its `README.txt`. diff --git a/docs/fleet-discovery.md b/docs/fleet-discovery.md index 0ce4e21..b7d78a7 100644 --- a/docs/fleet-discovery.md +++ b/docs/fleet-discovery.md @@ -6,7 +6,7 @@ service or Node release. ## Enable and secure -1. Complete the protected ingress and fleet acceptance checks below. Discovery +1. Run the [end-to-end harness](development.md#end-to-end-tests). Discovery is disabled by default. 2. Mount the existing `CloudflareKeyringFile` privately, with directory mode 0700 and file mode 0600, readable by the API identity. All API replicas need @@ -105,11 +105,3 @@ interpret a failed read as an empty fleet. For Access failures, check credential availability, source state and rotation acknowledgement, then restore the correct version through the tunnel workflow. After correcting public routes, wait for collection. - -## Release checks - -Before production enablement, test two managed machines for Access, DNS, TLS, -direct-origin bypass, Node/SDK routing to private gVisor apps, enrollment and app -convergence, outages and recovery, rotation, removal and cold restart. Record -sanitized source timelines and check aggregate output against the consumer size -limit. diff --git a/docs/machine-status.md b/docs/machine-status.md index 32e09b3..edf3e02 100644 --- a/docs/machine-status.md +++ b/docs/machine-status.md @@ -87,10 +87,7 @@ credential recovery can establish a new scope. Retired enrollments have no new credential recovery protocol and remain unconfirmed if their ordering state is lost. A process restart alone does not reset report ordering. -## Release verification +## Verification -Run the Go race suite with `TEST_DATABASE_URL` pointing to disposable PostgreSQL, -the UI build and Playwright; skipped database tests do not establish acceptance. -For Runtime checks, follow [Runtime verification](../runtime/README.md#verification). -Record exact revisions and redacted evidence. Verify real Node/SDK/Flux/gVisor -integration and external reachability on two machines before production activation. +See [development checks](development.md#development-checks) and the +[end-to-end harness](development.md#end-to-end-tests). diff --git a/docs/machine-tunnels.md b/docs/machine-tunnels.md index a43ac96..7e409db 100644 --- a/docs/machine-tunnels.md +++ b/docs/machine-tunnels.md @@ -192,18 +192,10 @@ remain, with no active upgrade Plan. Terminal delivery persists through local acknowledgement; authentication/fetch errors never mean removal. Verify provider absence separately from local cleanup. -## Integration agreements and release evidence +## Integration checks App assignments follow the [delivery and cleanup contract](app-registry.md#runtime-delivery-and-completion-contract). -Before production, test with compatible Node and SDK images and two machines: - -1. Verify Cloudflare Access, DNS and TLS, including rejection of invalid or revoked - credentials and attempts to bypass the tunnel directly. -2. Exercise Node routing to private gVisor apps, including session, payment and - application paths. Test HTTP, SSE and WebSocket performance. -3. Test restart, reboot, provider and API outages, rotation, updates and offline - removal. Check local and provider cleanup, and test actual CNI/DNAT, NodePort, - host-port, direct Pod/Service and IPv6 access. +Run the [end-to-end harness](development.md#end-to-end-tests) for routing and isolation checks. Cloudflared normalization affects matching and can differ from the forwarded path; configuration inspection is not isolation evidence. Review Cloudflare diff --git a/docs/onchain-operation.md b/docs/onchain-operation.md deleted file mode 100644 index b58441e..0000000 --- a/docs/onchain-operation.md +++ /dev/null @@ -1,170 +0,0 @@ -# Managed onchain operation - -This workflow targets fresh Control Center databases and fresh Runtime installations. -The app catalog's exact decimal prices are the registration inputs. Deployment -configuration owns Node payment infrastructure; the machine UI inspects its state. -Offchain Node advertises free service even if a catalog revision has a positive quote. -Onchain Node requires positive USD prices with `hour` or `fixed` units for every app. - -## Fresh setup - -Build Node with the redeemer authorization webhook and `RedeemerHeadersFile` support. -Build Runtime, then build `runtime/services/Dockerfile.node` with digest-pinned -`NODE_IMAGE` and `RUNTIME_IMAGE` arguments. Publish the resulting image and set its -actual digest as `RuntimeNodeImage`. Use that same compatible Node build for -`LIVEPEER_REDEEMER_IMAGE`. Record all component revisions and image digests in the -acceptance evidence. An arbitrary image digest is not evidence of compatibility. - -```sh -docker build -f runtime/services/Dockerfile.node \ - --build-arg NODE_IMAGE= \ - --build-arg RUNTIME_IMAGE= \ - -t runtime/services -docker push -``` - -Use the digest returned by the push rather than the mutable build tag. The Pod's -volume policy preserves owner-only SQLite permissions on subsequent mounts; -retain that policy together with the database and its sidecars. - -Copy `deploy/redeemer.example.toml` to `deploy/redeemer.toml`. Mount a dedicated -redemption wallet, its password, and its chain RPC file only in the redeemer. -Its wallet must satisfy Node's standalone redeemer policy; the ticket recipient -is the registered orchestrator, not the dedicated transaction-signing wallet. -Use a separate persistent redeemer database. The orchestrator keeps its own -payment database and SQLite sidecars under its retained `/data` volume. - -Create owner-only files readable by container UID 65532: - -- `deploy/secrets/payment-rpc/`: an HTTPS RPC URL. -- `deploy/secrets/payment-webhook-auth`: a random secret of at least 32 bytes. -- `deploy/secrets/redeemer/keystore.json`, `password`, and `rpc`. -- `deploy/secrets/redeemer/auth-url`: `http://api:43812/internal/redemption/authorize`. -- `deploy/secrets/redeemer/auth-headers`: `Authorization: Bearer `. - -Set `PaymentSecretsDir` and `PaymentWebhookSecretFile` in the API deployment -configuration as shown in `deploy/config.example.toml`. Start the fresh deployment -with `docker compose -f compose.yaml -f compose.onchain.yaml --profile onchain up -d`. -Only `POST /redemption/tickets` is exposed through the verified HTTPS API ingress. -Keep the redeemer's raw listener, metrics and webhook inaccessible externally. -The same-host deployment accepts host compromise as a trust-boundary limitation. - -Copy and edit `deploy/payments.example.json`, using real machine IDs and recipient -addresses. The supplied ticket terms are illustrative, not an economic recommendation. -Select appropriate funded validation limits and ticket terms for your deployment. -Apply from the trusted API deployment environment: - -```sh -controlcenter payments apply --config /etc/controlcenter/config.toml \ - --file /operator/payments.json --expected-revision 0 -``` - -The command prints the current deployment revision. Use that revision on the next -apply. Imports are complete snapshots: retain all currently onchain machine entries, -or explicitly set one to `{"version":1,"mode":"offchain"}`. Do not supply generated -`generation` values. An identical retry is a no-op, including after a lost response. Stale changes conflict. -Settings, generations and audit records commit together. API processes consume -persisted desired settings rather than importing their own startup snapshot. - -The first recipient and chain/controller binding remain pinned to the machine -identity across offchain operation, removal and re-enrollment. Ordinary apply -cannot change those bindings. No operator price override or pricing profile exists. -Private RPC/redemption access requires explicit IP:port grants; use exact addresses -and ports in `rpc_grants` / `redeemer_grants`. Loopback and broad CIDRs are unsupported. -The grants are rendered only for orchestrator egress; app policies remain isolated. - -## Activation, changes and credentials - -The existing maintenance workflow withdraws new work, drains active work and holds -the previous workload before replacing Node. Failed startup stays failed; it never -switches to free service. Node remains reachable through its protected private -Service when payment readiness fails, allowing management and recovery. - -Runtime verifies the live Pod incarnation before fetching RPC and submission -credentials over its separate orchestrator socket. A private readiness probe also -matches the current PID 1 to the issued launch association before payment -observations can be current. Container restart cannot reuse an earlier process -observation. Files are owner-only and -memory-backed. The submission bearer authorizes only recipient-bound ticket -submission. It is distinct from machine management and the redeemer's webhook -service credential. Neither API nor app/Runtime pods receive the signing key. - -For RPC rotation, provision a new immutable secret filename and change `rpc_secret`. -Never replace a referenced file's bytes. Increment `credential_revision` to rotate -submission credentials. Retain old RPC files while held workloads or rollback -settings reference them. An observed replacement grant retires earlier submission -grants. Management credential refresh fences management immediately while a held -Node's submission grant may remain usable until replacement. Restarted Node fetches -credentials for its exact published configuration. - -Rollback to previous settings is an explicit new apply at the current revision; -generations never decrease. A previously retired submission bearer is not restored: -a new process obtains a new grant. Keep immutable RPC secret versions available. - -## Failure, retirement and recovery - -Configuration application, local onchain readiness and remote redemption handoff are -separate observations. A successful `/readyz`, download or empty worker pass does -not prove authorized handoff. `unverified` means no current successful handoff has -been observed; `degraded` reflects submission failures. Node's durable queue and -backpressure continue governing redemption outages. - -Disable, destination change and ordinary removal wait for app drain and fresh -successful evidence of zero unsettled tickets. Missing, stale or incomplete queue -evidence blocks completion. Drain expiry requires the existing audited retry. -Normal removal retains the onchain workload and credentials while settling tickets. -An observed offchain replacement revokes the previous onchain workload's submission -grants after the required drain completes. - -Forced removal or account deletion revokes submission grants immediately. Already -accepted tickets continue at the redeemer. Retained local tickets require explicit -recovery, reported as `recovery_required`; physical cleanup does not mean payments -drained. Preserve the orchestrator database and its sidecars. Re-enroll the same -machine identity and recover the retained database with its pinned recipient and -chain settings before resuming submission. Once the restored Node has reported a fresh successful -zero-unsettled observation, apply the same desired snapshot with -`--acknowledge-recovery ` and the current expected revision. This -records an explicit recovery audit event and clears the recovery-required flag. -After a onchain Node has initialized successfully, credential delivery requires its -existing payment database; a missing database fails startup instead of silently -creating a replacement. Do not discard databases to clear an -error or reinterpret retained state on a different chain or recipient. - -Back up SQLite through a consistent online backup or while the writer is stopped; -retain the matching database/WAL state. Back up the redeemer database separately -from the orchestrator's, and keep signing-key backups under operator control. -Retain the bound redemption origin and its private routing/trust inputs until -outstanding tickets are resolved. Restore those routes together with retained -state; changing destination still requires fresh zero-unsettled evidence. -Re-enrollment waits for authoritative cleanup of the preceding ingress resources -before publishing its new protected routes. - -## Acceptance evidence - -Use two freshly installed CPU machines with different infrastructure settings and -unchanged shared catalog revisions. Record component commits/digests, desired and -observed generations, bounded spending/runtime limits, and redacted outcomes. -Exercise onchain discovery/admission/execution/accounting, winning-ticket handoff, -lost acknowledgements, Node/redeemer restarts, webhook/redemption outages and -backpressure, rotation, ordinary/forced retirement and retained-state recovery. -Verify signing-key isolation, private endpoint reachability and blocked app access. -Keep application correctness, authorization, durable handoff and settlement results -separate. Local unit tests alone do not complete the funded #93/#118 gate. - -## Configuration and implementation ownership - -For #119, the deployment operator applies infrastructure settings through the -deployment CLI. Central administrator status, machine ownership and machine -credentials do not grant payment mutation authority. The browser exposes scoped -inspection only. PostgreSQL holds the authoritative desired settings. - -Control Center owns immutable recipient bindings, versioned secret references, -submission grants, the private authorization callback and configuration/audit -transactions. Runtime owns machine delivery, live Pod/process checks, private -credential files, activation/drain coordination and bounded observations. Node -owns price conversion, ticket validation, durable admission, acknowledgements, -retry and settlement. Its standalone redeemer alone holds the signing key. - -#93 owns funded challenge-app execution evidence using #90's responder/verifier; -#118 owns the broader fleet acceptance matrix. Record their remaining gates -separately from configuration integration and local verification. diff --git a/docs/operations.md b/docs/operations.md index 45d5b0a..525bc42 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -69,6 +69,40 @@ assignments, replica edits and sequential replacement/removal. Runtime completio is separate from current health; see the registry guide for the delivery and cleanup contract. +## Onchain operation + +Configure the redeemer and secret mounts using [deployment setup](../deploy/README.md#onchain-setup). +Edit [onchain.example.json](../deploy/onchain.example.json) and apply it from the +API deployment environment: + +```sh +controlcenter onchain apply --config /etc/controlcenter/config.toml \ + --file /operator/onchain.json --expected-revision 0 +``` + +Use the returned revision for the next apply. The file is a complete snapshot; +retain enabled machines or explicitly set `{"version":1,"mode":"offchain"}` to +disable one. Unconfigured machines default to offchain. App catalog prices remain +authoritative; every advertised onchain app needs a positive USD `hour` or `fixed` price. + +Provision a new immutable `rpc_secret` file for RPC rotation. Increment +`credential_revision` to rotate submission credentials. Retain referenced RPC +versions for held workloads and rollback. Reapply previous settings at the current +revision to roll back. Configuration changes use the normal withdrawal/drain flow. +Inspect configuration, local admission and remote handoff in **Runtime status**. + +Disabling onchain operation, changing redemption destination and normal removal +wait for app drain and zero unsettled tickets. Forced removal revokes submission +grants immediately and reports `recovery_required`. Re-enroll the same machine +with its retained state; after a fresh zero-unsettled report, apply with +`--acknowledge-recovery ` to clear the flag. + +Back up Node's `/data/onchain.sqlite` and sidecars consistently, and back up the +redeemer database and wallet separately. Keep the recipient/chain binding and +redemption routing/trust inputs while tickets remain unsettled. Private endpoints +require exact IP:port `rpc_grants` / `redeemer_grants`; these allow orchestrator +access only. + ## Machine ingress Per-enrollment Cloudflare tunnels and protected Collector discovery are opt-in. diff --git a/runtime/README.md b/runtime/README.md index 23c5830..027b441 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -372,12 +372,4 @@ The firewall test uses a disposable privileged Docker container and private network namespaces; it does not apply rules to the host. The installer also runs a gVisor smoke test and saves results in `logs/gvisor-smoke.log`. -Before production release, build and publish the Runtime image, then test on a -disposable supported host with the pinned K3s, Flux and gVisor versions. Verify -installation, rerun, reboot, persistent data and an alternate install directory. -Test management repair while app reconciliation is broken, including recovery -from missing committed state. With compatible Node and SDK revisions, run a -two-machine, two-capability fixture covering both protocol modes, multiple -replicas, routing, readiness loss, updates, removal, drain expiry and Node -unavailability. Confirm that deadlines and pending physical cleanup are reported -accurately. Unit tests and a mock Node do not replace this acceptance test. +See the [end-to-end harness](../docs/development.md#end-to-end-tests) for host and fleet checks. diff --git a/runtime/appreconciler/controller.go b/runtime/appreconciler/controller.go index d5683db..0a2e795 100644 --- a/runtime/appreconciler/controller.go +++ b/runtime/appreconciler/controller.go @@ -51,7 +51,7 @@ func (c *Controller) hooks() OwnerHooks { Eligibility: func(r Registration) (bool, bool) { member, ready := c.Journal.Eligibility(r) state := c.Journal.View() - if state.Metadata.Payment.Onchain() && !state.Metadata.PaymentActive { + if state.Metadata.Onchain.Onchain() && !state.Metadata.OnchainActive { ready = false } return member, ready && c.Probes != nil && c.Probes.Ready(r.InstanceID, r.PodUID) @@ -347,12 +347,12 @@ func (c *Controller) Tick(ctx context.Context) error { }) for _, g := range groups { a := assignments[g.RevisionID] - if s.Metadata.Payment.Onchain() && !s.Metadata.PaymentActive { - s.AssignmentReasons[a.RevisionID] = "payment_pending" + if s.Metadata.Onchain.Onchain() && !s.Metadata.OnchainActive { + s.AssignmentReasons[a.RevisionID] = "onchain_pending" continue } - if a.Revision != nil && s.Metadata.Payment.Compatible(a.Revision.Definition) != nil { - s.AssignmentReasons[a.RevisionID] = "payment_incompatible" + if a.Revision != nil && s.Metadata.Onchain.Compatible(a.Revision.Definition) != nil { + s.AssignmentReasons[a.RevisionID] = "onchain_incompatible" continue } if !a.StartAllowed { @@ -606,14 +606,14 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo continue } pod, exists := view.Pods[i.Name] - if s.Metadata.Payment.Onchain() && !s.Metadata.PaymentActive && i.AppID == "" { + if s.Metadata.Onchain.Onchain() && !s.Metadata.OnchainActive && i.AppID == "" { continue } if i.AppID == "" && (!exists || pod.UID != i.PodUID || pod.Deleting || pod.Phase != "Running") { continue } signalOK := i.Definition.Lifecycle.StopSignal == nil || (exists && pod.StopSignal == *i.Definition.Lifecycle.StopSignal) - if (!s.Metadata.Payment.Onchain() || s.Metadata.PaymentActive) && i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { + if (!s.Metadata.Onchain.Onchain() || s.Metadata.OnchainActive) && i.AppID != "" && ready[id] && signalOK && confirmed && !s.ClockUncertain && !recovery { for n := range registrations { registrations[n].Options.Status = "ready" } diff --git a/runtime/appreconciler/controller_test.go b/runtime/appreconciler/controller_test.go index 31706b4..f18d530 100644 --- a/runtime/appreconciler/controller_test.go +++ b/runtime/appreconciler/controller_test.go @@ -20,7 +20,7 @@ import ( "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" "github.com/livepeer/control-center/runtime/internal/testutil" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/transport" "github.com/livepeer/control-center/schema" runner "github.com/livepeer/golang-runner" @@ -43,7 +43,7 @@ func (i *testInputs) set(t *testing.T, set schema.AppAssignmentSetV1) { if err != nil { t.Fatal(err) } - i.value = Input{Metadata: contract.Metadata{Payment: payment.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} + i.value = Input{Metadata: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} } type testCluster struct { diff --git a/runtime/appreconciler/input.go b/runtime/appreconciler/input.go index 8d8d92d..151d31a 100644 --- a/runtime/appreconciler/input.go +++ b/runtime/appreconciler/input.go @@ -72,8 +72,8 @@ func (s Source) Read(ctx context.Context) (Input, error) { if err != nil || identity.Epoch != m.Epoch || identity.CredentialVersion != m.CredentialVersion { return input, errors.New("management_enrollment") } - if m.Payment.Onchain() && m.PaymentActive { - m.PaymentActive = s.paymentActive(ctx, m) + if m.Onchain.Onchain() && m.OnchainActive { + m.OnchainActive = s.onchainActive(ctx, m) } p, err := appbundle.Read(files, m) if err != nil { @@ -85,9 +85,9 @@ func (s Source) Read(ctx context.Context) (Input, error) { return Input{Metadata: m, Payload: p, Digest: a.Digest}, nil } -// Payment eligibility is checked against the live process, even when an offline +// Onchain eligibility is checked against the live process, even when an offline // artifact repeats an earlier approval. Dependency loss cannot suppress drain. -func (s Source) paymentActive(ctx context.Context, m contract.Metadata) bool { +func (s Source) onchainActive(ctx context.Context, m contract.Metadata) bool { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() var pods struct { diff --git a/runtime/appreconciler/payment_test.go b/runtime/appreconciler/onchain_test.go similarity index 73% rename from runtime/appreconciler/payment_test.go rename to runtime/appreconciler/onchain_test.go index 36319a4..e16f25f 100644 --- a/runtime/appreconciler/payment_test.go +++ b/runtime/appreconciler/onchain_test.go @@ -12,13 +12,13 @@ import ( "testing" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/transport" ) -type paymentTransport func(*http.Request) (*http.Response, error) +type onchainTransport func(*http.Request) (*http.Response, error) -func (f paymentTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +func (f onchainTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func TestOnchainAdmissionRequiresLiveMatchingNode(t *testing.T) { digest := strings.Repeat("a", 64) pods := 1 @@ -33,39 +33,39 @@ func TestOnchainAdmissionRequiresLiveMatchingNode(t *testing.T) { defer kube.Close() token := filepath.Join(t.TempDir(), "token") os.WriteFile(token, []byte("fixture"), 0600) - source := Source{Kube: &transport.Kube{Base: kube.URL, TokenFile: token, Client: kube.Client()}, Client: &http.Client{Transport: paymentTransport(func(*http.Request) (*http.Response, error) { + source := Source{Kube: &transport.Kube{Base: kube.URL, TokenFile: token, Client: kube.Client()}, Client: &http.Client{Transport: onchainTransport(func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: ready, Body: io.NopCloser(strings.NewReader("ready")), Header: make(http.Header)}, nil })}} m := contract.Metadata{ConfigDigest: digest} - if !source.paymentActive(context.Background(), m) { + if !source.onchainActive(context.Background(), m) { t.Fatal("matching ready Node rejected") } ready = 503 - if source.paymentActive(context.Background(), m) { + if source.onchainActive(context.Background(), m) { t.Fatal("cached approval admitted on unready Node") } ready = 200 digest = strings.Repeat("b", 64) - if source.paymentActive(context.Background(), m) { + if source.onchainActive(context.Background(), m) { t.Fatal("different generation admitted") } digest = m.ConfigDigest pods = 2 - if source.paymentActive(context.Background(), m) { + if source.onchainActive(context.Background(), m) { t.Fatal("ambiguous Node incarnation admitted") } } func TestPendingOnchainTargetDoesNotAllocateOrAdmit(t *testing.T) { c, input, cluster, owner, _, _ := fixtureController(t) - input.value.Metadata.Payment = payment.Config{Mode: "onchain", Generation: 1} - input.value.Metadata.PaymentActive = false + input.value.Metadata.Onchain = onchain.Config{Mode: "onchain", Generation: 1} + input.value.Metadata.OnchainActive = false tick(t, c) if len(c.Journal.View().Instances) != 0 { t.Fatal("pending onchain target allocated work") } - input.value.Metadata.PaymentActive = true + input.value.Metadata.OnchainActive = true registerApps(t, c, cluster) - input.value.Metadata.PaymentActive = false + input.value.Metadata.OnchainActive = false tick(t, c) for _, entry := range owner.accepted.Entries { if entry.Options.Status == "ready" { @@ -74,7 +74,7 @@ func TestPendingOnchainTargetDoesNotAllocateOrAdmit(t *testing.T) { } for _, instance := range c.Journal.View().Instances { if instance.WithdrawalID != "" { - t.Fatal("temporary payment readiness loss became terminal withdrawal") + t.Fatal("temporary onchain readiness loss became terminal withdrawal") } } } diff --git a/runtime/cmd/livepeer-runtime/main.go b/runtime/cmd/livepeer-runtime/main.go index a7377d4..178c345 100644 --- a/runtime/cmd/livepeer-runtime/main.go +++ b/runtime/cmd/livepeer-runtime/main.go @@ -256,10 +256,10 @@ func httpSource(ctx context.Context, args []string) error { socketErrors := make(chan error, 1) integration := &connector.Integration{Reporter: &transport.Reports{Client: control, Directory: filepath.Join(*directory, "reports")}, Control: control, Kube: kube, Desired: source.Desired, StateFile: filepath.Join(*directory, "connector-grant.json")} integration.Restore() - payments := &orchestrator.Integration{Control: control, Kube: kube, Desired: source.Desired, TokenFile: *token, StateFile: filepath.Join(*directory, "payment-grant.json"), AllowHTTP: control.AllowHTTP} - payments.Restore() - source.Payment = payments.Observe - sockets, err := management.Listen(*socketRoot, integration, management.AppReports{Control: control, Desired: source.Desired}, payments) + onchain := &orchestrator.Integration{Control: control, Kube: kube, Desired: source.Desired, TokenFile: *token, StateFile: filepath.Join(*directory, "onchain-grant.json"), AllowHTTP: control.AllowHTTP} + onchain.Restore() + source.Onchain = onchain.Observe + sockets, err := management.Listen(*socketRoot, integration, management.AppReports{Control: control, Desired: source.Desired}, onchain) if err != nil { return err } diff --git a/runtime/contract/contract.go b/runtime/contract/contract.go index 5e55f14..46371ef 100644 --- a/runtime/contract/contract.go +++ b/runtime/contract/contract.go @@ -2,16 +2,16 @@ package contract import ( - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "time" ) const BundleFormat = 3 type Metadata struct { - Payment payment.Config `json:"payment"` - PaymentCredentialsRef string `json:"payment_credentials_ref,omitempty"` - PaymentActive bool `json:"payment_active"` + Onchain onchain.Config `json:"onchain"` + OnchainCredentialsRef string `json:"onchain_credentials_ref,omitempty"` + OnchainActive bool `json:"onchain_active"` NodeID string `json:"node_id"` Epoch string `json:"epoch"` CredentialVersion int64 `json:"credential_version"` diff --git a/runtime/httpsource/source.go b/runtime/httpsource/source.go index 31fe6e4..045f7d2 100644 --- a/runtime/httpsource/source.go +++ b/runtime/httpsource/source.go @@ -19,7 +19,7 @@ import ( "github.com/livepeer/control-center/runtime/appbundle" "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/transport" ) @@ -31,7 +31,7 @@ type Kubernetes interface { Publish(context.Context, string, *transport.Artifact, bool, string) error } type Source struct { - Payment func(context.Context, contract.Metadata, bool, bool, string) *payment.Observation + Onchain func(context.Context, contract.Metadata, bool, bool, string) *onchain.Observation Control *transport.Control Reporter transport.Requester Kube Kubernetes @@ -384,8 +384,8 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr ready = ready && k3sVersion == m.UpgradeVersion } reason := "applying" - if m.Payment.Onchain() && applied && actual == m.ConfigDigest && !ready { - reason = "payment_not_ready" + if m.Onchain.Onchain() && applied && actual == m.ConfigDigest && !ready { + reason = "onchain_not_ready" } if ready { reason = "ready" @@ -396,8 +396,8 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr } payload := map[string]any{"epoch": m.Epoch, "credential_version": m.CredentialVersion, "component": "runtime", "generation": m.Generation, "bundle_sha256": strings.TrimPrefix(revision, "sha256:"), "config_digest": actual, "k3s_version": k3sVersion, "ready": ready, "https": strings.HasPrefix(s.Control.ConfigURL, "https://"), "reason": reason, "bundle_format": contract.BundleFormat, "apps_error": appErrorReason(appError), "observed_at": time.Now().UTC()} - if s.Payment != nil { - payload["payment"] = s.Payment(ctx, m, applied && actual == m.ConfigDigest && podUID != "", ready, podUID) + if s.Onchain != nil { + payload["onchain"] = s.Onchain(ctx, m, applied && actual == m.ConfigDigest && podUID != "", ready, podUID) } if d := s.reporting.Load(); d != nil { payload["downloaded"], payload["downloaded_at"] = d.Downloaded, d.DownloadedAt diff --git a/runtime/httpsource/source_test.go b/runtime/httpsource/source_test.go index 7bf8f22..ce9d626 100644 --- a/runtime/httpsource/source_test.go +++ b/runtime/httpsource/source_test.go @@ -19,7 +19,7 @@ import ( "github.com/livepeer/control-center/runtime/artifact" "github.com/livepeer/control-center/runtime/contract" "github.com/livepeer/control-center/runtime/internal/testutil" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/livepeer/control-center/runtime/transport" ) @@ -201,7 +201,7 @@ type sourceFixture struct { func newFixture(t *testing.T) *sourceFixture { t.Helper() set := testutil.Assignment(t) - f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{Payment: payment.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} + f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() @@ -484,7 +484,7 @@ func TestAppOnlyApplicationReportsActualAppliedArchive(t *testing.T) { func TestComponentComparisonCannotBorrowCrossEnrollmentOrCorruptEvidence(t *testing.T) { s := &Source{Store: artifact.Store{Directory: t.TempDir()}} cache := func(epoch, node, connector string) string { - m := contract.Metadata{Payment: payment.Offchain(), NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} + m := contract.Metadata{Onchain: onchain.Offchain(), NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} return cacheBundle(t, s.Store, m, map[string][]byte{"system/node/kustomization.yaml": []byte(node), "system/connector/kustomization.yaml": []byte(connector)}) } old := cache("11111111-1111-4111-8111-111111111111", "same node", "old connector") diff --git a/runtime/payment/config.go b/runtime/onchain/config.go similarity index 94% rename from runtime/payment/config.go rename to runtime/onchain/config.go index 922d522..1df9b15 100644 --- a/runtime/payment/config.go +++ b/runtime/onchain/config.go @@ -1,5 +1,5 @@ -// Package payment defines the nonsecret managed Node payment contract. -package payment +// Package onchain defines the nonsecret managed Node onchain contract. +package onchain import ( "errors" @@ -45,7 +45,7 @@ var SecretRef = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$`) func validAddress(s string) bool { return Address.MatchString(s) && strings.Trim(s[2:], "0") != "" } func (c Config) Validate() error { - bad := errors.New("invalid payment infrastructure settings") + bad := errors.New("invalid onchain infrastructure settings") if c.Version != 1 || c.Generation < 0 { return bad } @@ -101,7 +101,7 @@ func (c Config) Validate() error { } for _, g := range grants { if _, _, e := Grant(g); e != nil { - return errors.New("payment grants must be explicit non-loopback IP:port destinations") + return errors.New("onchain grants must be explicit non-loopback IP:port destinations") } } } @@ -113,7 +113,7 @@ func (c Config) Validate() error { func Grant(s string) (netip.Addr, uint16, error) { a, e := netip.ParseAddrPort(s) if e != nil || a.Port() == 0 || a.Addr().IsUnspecified() || a.Addr().IsMulticast() || a.Addr().IsLoopback() || a.Addr().Zone() != "" { - return netip.Addr{}, 0, errors.New("payment grants require IP:port") + return netip.Addr{}, 0, errors.New("onchain grants require IP:port") } return a.Addr().Unmap(), a.Port(), nil } @@ -142,10 +142,10 @@ type Observation struct { // ValidateEndpoint rejects destinations the rendered egress policy cannot reach. // Private DNS addresses still require exact grants at the Node/Kubernetes boundary. func ValidateEndpoint(raw string, grants []string) error { - bad := errors.New("private or nonstandard-port payment destinations require matching IP:port grants") + bad := errors.New("private or nonstandard-port onchain destinations require matching IP:port grants") u, e := url.Parse(raw) if e != nil || u.Scheme != "https" || u.Hostname() == "" { - return errors.New("payment destinations require HTTPS") + return errors.New("onchain destinations require HTTPS") } port := uint64(443) if u.Port() != "" { diff --git a/runtime/payment/config_test.go b/runtime/onchain/config_test.go similarity index 92% rename from runtime/payment/config_test.go rename to runtime/onchain/config_test.go index 130eefe..c68df55 100644 --- a/runtime/payment/config_test.go +++ b/runtime/onchain/config_test.go @@ -1,4 +1,4 @@ -package payment +package onchain import ( "strings" @@ -15,12 +15,12 @@ func TestCompleteOnchainConfigurationAndExplicitOffchain(t *testing.T) { if e := Offchain().Validate(); e != nil { t.Fatal(e) } - for name, mutate := range map[string]func(*Config){"missing recipient": func(c *Config) { c.Recipient = "" }, "mode only": func(c *Config) { *c = Config{Version: 1, Mode: "onchain"} }, "empty destination query": func(c *Config) { c.RedeemerURL += "?" }, "insecure destination": func(c *Config) { c.RedeemerURL = "http://redeemer.example" }, "inline destination secret": func(c *Config) { c.RedeemerURL = "https://secret@redeemer.example" }, "invalid winning probability": func(c *Config) { c.TicketWinProb = "0" }, "two rate policies": func(c *Config) { c.ETHUSDFeed = c.Controller; c.PriceMaxAge = "1h" }, "broad network": func(c *Config) { c.RedeemerGrants = []string{"10.0.0.0/8"} }, "wrong chain": func(c *Config) { c.Network = "arbitrum-one-mainnet" }, "offchain retains payment inputs": func(c *Config) { c.Mode = "offchain" }, "overflow": func(c *Config) { c.ChainID = ^uint64(0) }} { + for name, mutate := range map[string]func(*Config){"missing recipient": func(c *Config) { c.Recipient = "" }, "mode only": func(c *Config) { *c = Config{Version: 1, Mode: "onchain"} }, "empty destination query": func(c *Config) { c.RedeemerURL += "?" }, "insecure destination": func(c *Config) { c.RedeemerURL = "http://redeemer.example" }, "inline destination secret": func(c *Config) { c.RedeemerURL = "https://secret@redeemer.example" }, "invalid winning probability": func(c *Config) { c.TicketWinProb = "0" }, "two rate policies": func(c *Config) { c.ETHUSDFeed = c.Controller; c.PriceMaxAge = "1h" }, "broad network": func(c *Config) { c.RedeemerGrants = []string{"10.0.0.0/8"} }, "wrong chain": func(c *Config) { c.Network = "arbitrum-one-mainnet" }, "offchain retains onchain inputs": func(c *Config) { c.Mode = "offchain" }, "overflow": func(c *Config) { c.ChainID = ^uint64(0) }} { t.Run(name, func(t *testing.T) { c := validConfig() mutate(&c) if c.Validate() == nil { - t.Fatal("accepted invalid payment configuration") + t.Fatal("accepted invalid onchain configuration") } }) } diff --git a/runtime/orchestrator/integration.go b/runtime/orchestrator/integration.go index b065183..0f02b6c 100644 --- a/runtime/orchestrator/integration.go +++ b/runtime/orchestrator/integration.go @@ -1,4 +1,4 @@ -// Package orchestrator delivers payment credentials to a verified Node process. +// Package orchestrator delivers onchain credentials to a verified Node process. package orchestrator import ( @@ -25,13 +25,13 @@ type Association struct { Launch Epoch string `json:"epoch"` CredentialVersion int64 `json:"credential_version"` - PaymentGeneration int64 `json:"payment_generation"` + OnchainGeneration int64 `json:"onchain_generation"` ConfigDigest string `json:"config_digest"` GrantID string `json:"grant_id"` } type Request struct { Launch - PaymentGeneration int64 `json:"payment_generation"` + OnchainGeneration int64 `json:"onchain_generation"` ConfigDigest string `json:"config_digest"` } type Grant struct { @@ -105,10 +105,10 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, "request refused", 400) return } - if r.URL.Path == "/payment/observation" { + if r.URL.Path == "/onchain/observation" { var o ProcessObservation m, ok := i.Desired() - if transport.Decode(b, &o) != nil || !ok || m.TerminalCleanup || o.Epoch != m.Epoch || o.ConfigDigest != m.ConfigDigest || o.PaymentGeneration != m.Payment.Generation || time.Since(o.ObservedAt) > 15*time.Second || o.ObservedAt.After(time.Now().Add(5*time.Second)) || i.checkPod(r.Context(), o.Launch, m) != nil { + if transport.Decode(b, &o) != nil || !ok || m.TerminalCleanup || o.Epoch != m.Epoch || o.ConfigDigest != m.ConfigDigest || o.OnchainGeneration != m.Onchain.Generation || time.Since(o.ObservedAt) > 15*time.Second || o.ObservedAt.After(time.Now().Add(5*time.Second)) || i.checkPod(r.Context(), o.Launch, m) != nil { http.Error(w, "observation refused", 409) return } @@ -124,7 +124,7 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("{}\n")) return } - if r.URL.Path != "/payment/credentials" { + if r.URL.Path != "/onchain/credentials" { http.Error(w, "operation refused", 403) return } @@ -135,16 +135,16 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { } grant, e := i.fetch(r.Context(), l) if e != nil { - http.Error(w, "payment credential unavailable", 503) + http.Error(w, "onchain credential unavailable", 503) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(grant) } func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { - bad := errors.New("payment_credential_unavailable") + bad := errors.New("onchain_credential_unavailable") m, ok := i.Desired() - if !ok || i.AllowHTTP || !m.Payment.Onchain() || m.TerminalCleanup || m.PaymentCredentialsRef != "/v1/nodes/"+m.NodeID+"/payment/credentials" { + if !ok || i.AllowHTTP || !m.Onchain.Onchain() || m.TerminalCleanup || m.OnchainCredentialsRef != "/v1/nodes/"+m.NodeID+"/onchain/credentials" { return Grant{}, bad } before, e := os.ReadFile(i.TokenFile) @@ -155,12 +155,12 @@ func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { i.order++ order := i.order i.mu.Unlock() - b, _, e := i.Control.Request(ctx, "payment/credentials", Request{l, m.Payment.Generation, m.ConfigDigest}, 16384) + b, _, e := i.Control.Request(ctx, "onchain/credentials", Request{l, m.Onchain.Generation, m.ConfigDigest}, 16384) if e != nil { return Grant{}, bad } var g Grant - if transport.Decode(b, &g) != nil || g.Launch != l || g.Epoch != m.Epoch || g.CredentialVersion != m.CredentialVersion || g.PaymentGeneration != m.Payment.Generation || g.ConfigDigest != m.ConfigDigest || g.GrantID == "" || g.RPCURL == "" || g.Headers == "" { + if transport.Decode(b, &g) != nil || g.Launch != l || g.Epoch != m.Epoch || g.CredentialVersion != m.CredentialVersion || g.OnchainGeneration != m.Onchain.Generation || g.ConfigDigest != m.ConfigDigest || g.GrantID == "" || g.RPCURL == "" || g.Headers == "" { return Grant{}, bad } if i.checkPod(ctx, l, m) != nil { @@ -169,7 +169,7 @@ func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { authorized := func() bool { after, e := os.ReadFile(i.TokenFile) n, ok := i.Desired() - return ctx.Err() == nil && e == nil && ok && n.Epoch == m.Epoch && n.CredentialVersion == m.CredentialVersion && n.Generation == m.Generation && n.ConfigDigest == m.ConfigDigest && n.Payment.Generation == m.Payment.Generation && sha256.Sum256(before) == sha256.Sum256(after) + return ctx.Err() == nil && e == nil && ok && n.Epoch == m.Epoch && n.CredentialVersion == m.CredentialVersion && n.Generation == m.Generation && n.ConfigDigest == m.ConfigDigest && n.Onchain.Generation == m.Onchain.Generation && sha256.Sum256(before) == sha256.Sum256(after) } i.mu.Lock() defer i.mu.Unlock() diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go index cf20446..0dbad90 100644 --- a/runtime/orchestrator/integration_test.go +++ b/runtime/orchestrator/integration_test.go @@ -13,7 +13,7 @@ import ( "time" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" ) type kubeFunc func(context.Context, string, string, any, any) error @@ -36,7 +36,7 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) dir := t.TempDir() token := filepath.Join(dir, "token") os.WriteFile(token, []byte("machine-secret"), 0600) - m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Payment: payment.Config{Mode: "onchain", Generation: 2}, PaymentCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/payment/credentials"} + m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Onchain: onchain.Config{Mode: "onchain", Generation: 2}, OnchainCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/onchain/credentials"} l := Launch{PodName: "orchestrator-test", PodUID: "uid", LaunchID: strings.Repeat("b", 32), ProcessID: strings.Repeat("c", 64)} i := &Integration{TokenFile: token, StateFile: filepath.Join(dir, "grant.json"), Desired: func() (contract.Metadata, bool) { return m, true }} i.Kube = kubeFunc(func(_ context.Context, _, p string, _ any, out any) error { @@ -47,15 +47,15 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) return json.Unmarshal(b, out) }) i.Control = controlFunc(func(_ context.Context, p string, in any, _ int64) ([]byte, http.Header, error) { - if p != "payment/credentials" { + if p != "onchain/credentials" { t.Fatal(p) } - b, _ := json.Marshal(Grant{Association: Association{Launch: l, Epoch: m.Epoch, CredentialVersion: 1, PaymentGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) + b, _ := json.Marshal(Grant{Association: Association{Launch: l, Epoch: m.Epoch, CredentialVersion: 1, OnchainGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) return b, nil, nil }) return i, m, l } -func TestPaymentDeliveryFencesAndSecretPersistence(t *testing.T) { +func TestOnchainDeliveryFencesAndSecretPersistence(t *testing.T) { i, _, l := integrationFixture(t) g, e := i.fetch(t.Context(), l) if e != nil || g.Headers == "" { @@ -79,7 +79,7 @@ func TestPaymentDeliveryFencesAndSecretPersistence(t *testing.T) { t.Fatal("insecure delivery") } } -func TestPaymentQueueEvidenceAndHandoffAreIndependent(t *testing.T) { +func TestOnchainQueueEvidenceAndHandoffAreIndependent(t *testing.T) { i, m, l := integrationFixture(t) g, e := i.fetch(t.Context(), l) if e != nil { @@ -141,7 +141,7 @@ func processProof(t *testing.T, i *Integration, a Association, ready bool) { t.Helper() b, _ := json.Marshal(ProcessObservation{Association: a, ObservedAt: time.Now(), Ready: ready}) w := httptest.NewRecorder() - i.ServeHTTP(w, httptest.NewRequest("POST", "/payment/observation", strings.NewReader(string(b)))) + i.ServeHTTP(w, httptest.NewRequest("POST", "/onchain/observation", strings.NewReader(string(b)))) if w.Code != 200 { t.Fatal("process proof rejected", w.Code) } @@ -162,31 +162,31 @@ func TestProcessObservationCannotBorrowAnotherLaunchOrRenewOldEvidence(t *testin mutate(&o) b, _ := json.Marshal(o) w := httptest.NewRecorder() - i.ServeHTTP(w, httptest.NewRequest("POST", "/payment/observation", strings.NewReader(string(b)))) + i.ServeHTTP(w, httptest.NewRequest("POST", "/onchain/observation", strings.NewReader(string(b)))) if w.Code != 409 || i.observation != nil { t.Fatal("stale or foreign process observation accepted", w.Code) } } } -func TestInitializedPaymentStateMustSurviveReplacement(t *testing.T) { - path := filepath.Join(t.TempDir(), "payments.sqlite") - if checkPaymentState(path, false) != nil { +func TestInitializedOnchainStateMustSurviveReplacement(t *testing.T) { + path := filepath.Join(t.TempDir(), "onchain.sqlite") + if checkOnchainState(path, false) != nil { t.Fatal("fresh installation cannot create its first database") } - if checkPaymentState(path, true) == nil { + if checkOnchainState(path, true) == nil { t.Fatal("missing durable state silently recreated") } if e := os.WriteFile(path, nil, 0600); e != nil { t.Fatal(e) } - if checkPaymentState(path, true) == nil { + if checkOnchainState(path, true) == nil { t.Fatal("empty durable state accepted") } if e := os.WriteFile(path, []byte("retained database"), 0600); e != nil { t.Fatal(e) } - if e := checkPaymentState(path, true); e != nil { + if e := checkOnchainState(path, true); e != nil { t.Fatal(e) } } diff --git a/runtime/orchestrator/observation.go b/runtime/orchestrator/observation.go index 5ef8df8..1895b3a 100644 --- a/runtime/orchestrator/observation.go +++ b/runtime/orchestrator/observation.go @@ -9,21 +9,21 @@ import ( "time" "github.com/livepeer/control-center/runtime/contract" - "github.com/livepeer/control-center/runtime/payment" + "github.com/livepeer/control-center/runtime/onchain" "github.com/prometheus/common/expfmt" "github.com/prometheus/common/model" ) -func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, ready bool, podUID string) *payment.Observation { - o := &payment.Observation{Generation: m.Payment.Generation, Mode: m.Payment.Mode, PodUID: podUID, Applied: applied, Ready: ready, Handoff: "unverified"} - if !m.Payment.Onchain() { +func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, ready bool, podUID string) *onchain.Observation { + o := &onchain.Observation{Generation: m.Onchain.Generation, Mode: m.Onchain.Mode, PodUID: podUID, Applied: applied, Ready: ready, Handoff: "unverified"} + if !m.Onchain.Onchain() { return o } i.mu.Lock() a := i.grant proof := i.observation i.mu.Unlock() - if !applied || a == nil || proof == nil || proof.Association != *a || time.Since(proof.ObservedAt) > 30*time.Second || a.PodUID != podUID || a.Epoch != m.Epoch || a.PaymentGeneration != m.Payment.Generation || a.ConfigDigest != m.ConfigDigest || i.checkPod(ctx, a.Launch, m) != nil { + if !applied || a == nil || proof == nil || proof.Association != *a || time.Since(proof.ObservedAt) > 30*time.Second || a.PodUID != podUID || a.Epoch != m.Epoch || a.OnchainGeneration != m.Onchain.Generation || a.ConfigDigest != m.ConfigDigest || i.checkPod(ctx, a.Launch, m) != nil { o.Applied = false o.Ready = false return o diff --git a/runtime/orchestrator/process.go b/runtime/orchestrator/process.go index f3d1c25..52525f5 100644 --- a/runtime/orchestrator/process.go +++ b/runtime/orchestrator/process.go @@ -33,21 +33,21 @@ func Start(ctx context.Context, args []string) error { if !ValidLaunch(launch) { return errors.New("orchestrator_launch_identity") } - dir := "/run/payment/private" + dir := "/run/onchain/private" if info, e := os.Lstat(dir); e == nil && (info.Mode()&os.ModeSymlink != 0 || !info.IsDir()) { - return errors.New("payment_storage_unavailable") + return errors.New("onchain_storage_unavailable") } else if e != nil && !os.IsNotExist(e) { - return errors.New("payment_storage_unavailable") + return errors.New("onchain_storage_unavailable") } if e = os.MkdirAll(dir, 0700); e != nil { - return errors.New("payment_storage_unavailable") + return errors.New("onchain_storage_unavailable") } if os.Chmod(dir, 0700) != nil { - return errors.New("payment_storage_unavailable") + return errors.New("onchain_storage_unavailable") } for _, f := range []string{"rpc", "headers", "launch.json"} { if e = os.Remove(filepath.Join(dir, f)); e != nil && !os.IsNotExist(e) { - return errors.New("stale_payment_material") + return errors.New("stale_onchain_material") } } client := transport.NewLocal("/management/control.sock") @@ -55,23 +55,23 @@ func Start(ctx context.Context, args []string) error { defer cancel() var g Grant for { - b, _, err := client.Request(ctx, "payment/credentials", launch, 16384) + b, _, err := client.Request(ctx, "onchain/credentials", launch, 16384) if err == nil && transport.Decode(b, &g) == nil && g.Launch == launch && g.RPCURL != "" && g.Headers != "" { break } select { case <-ctx.Done(): - return errors.New("payment_credential_unavailable") + return errors.New("onchain_credential_unavailable") case <-time.After(time.Second): } } - if e := checkPaymentState("/data/payments.sqlite", g.RequireState); e != nil { + if e := checkOnchainState("/data/onchain.sqlite", g.RequireState); e != nil { return e } marker, _ := json.Marshal(g.Association) if artifact.AtomicWrite(filepath.Join(dir, "rpc"), []byte(g.RPCURL), 0600) != nil || artifact.AtomicWrite(filepath.Join(dir, "headers"), []byte(g.Headers), 0600) != nil || artifact.AtomicWrite(filepath.Join(dir, "launch.json"), marker, 0600) != nil { - return errors.New("payment_credential_write") + return errors.New("onchain_credential_write") } _ = syscall.Exec("/usr/local/bin/livepeer", append([]string{"/usr/local/bin/livepeer"}, args...), []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/nonexistent"}) _ = os.Remove(filepath.Join(dir, "rpc")) @@ -83,7 +83,7 @@ func Start(ctx context.Context, args []string) error { // Probe runs inside the Node container and proves the marker still names its // current PID 1. Pod UID alone cannot distinguish container restarts. func Probe(ctx context.Context) bool { - b, e := os.ReadFile("/run/payment/private/launch.json") + b, e := os.ReadFile("/run/onchain/private/launch.json") var a Association process, pe := connector.ProcessIdentity() if e != nil || pe != nil || len(b) > 16384 || transport.Decode(b, &a) != nil || !ValidLaunch(a.Launch) || a.ProcessID != process { @@ -100,17 +100,17 @@ func Probe(ctx context.Context) bool { } r.Body.Close() ready := r.StatusCode == 200 - _, _, e = transport.NewLocal("/management/control.sock").Request(ctx, "payment/observation", ProcessObservation{Association: a, ObservedAt: time.Now(), Ready: ready}, 1024) + _, _, e = transport.NewLocal("/management/control.sock").Request(ctx, "onchain/observation", ProcessObservation{Association: a, ObservedAt: time.Now(), Ready: ready}, 1024) return e == nil && ready } -func checkPaymentState(path string, required bool) error { +func checkOnchainState(path string, required bool) error { if !required { return nil } info, e := os.Lstat(path) if e != nil || !info.Mode().IsRegular() || info.Size() == 0 { - return errors.New("payment_state_recovery_required") + return errors.New("onchain_state_recovery_required") } return nil } diff --git a/runtime/transport/client.go b/runtime/transport/client.go index 8593e84..cde99e3 100644 --- a/runtime/transport/client.go +++ b/runtime/transport/client.go @@ -70,7 +70,7 @@ func (c *Control) Request(ctx context.Context, endpoint string, payload any, lim if c.ConfigURL != c.approvedURL || c.Base != c.approvedBase { return nil, nil, errors.New("control_origin_changed") } - if endpoint != "config" && endpoint != "status" && endpoint != "removal-ack" && endpoint != "tunnel/connector-token" && endpoint != "payment/credentials" && !appReportPath.MatchString(endpoint) { + if endpoint != "config" && endpoint != "status" && endpoint != "removal-ack" && endpoint != "tunnel/connector-token" && endpoint != "onchain/credentials" && !appReportPath.MatchString(endpoint) { return nil, nil, errors.New("control_endpoint") } token, err := os.ReadFile(c.TokenFile) @@ -144,8 +144,8 @@ func ReadMetadata(b []byte) (contract.Metadata, error) { if len(b) > 16384 || Decode(b, &m) != nil || !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(m.NodeID) || m.Generation < 1 || m.CredentialVersion < 1 || !epochPattern.MatchString(m.Epoch) || m.BundleFormat != contract.BundleFormat { return m, errors.New("metadata_invalid") } - if m.Payment.Validate() != nil { - return m, errors.New("metadata_payment_invalid") + if m.Onchain.Validate() != nil { + return m, errors.New("metadata_onchain_invalid") } return m, nil } diff --git a/runtime/transport/client_test.go b/runtime/transport/client_test.go index 701a027..461515c 100644 --- a/runtime/transport/client_test.go +++ b/runtime/transport/client_test.go @@ -37,8 +37,8 @@ func TestControlOriginsCredentialsAndRedirects(t *testing.T) { if _, _, err = c.Request(context.Background(), "config", nil, 1024); !IsStatus(err, 302) || calls != 0 { t.Fatal("redirect leaked request", err, calls) } - if _, _, err = c.Request(context.Background(), "payment/credentials", map[string]string{"pod_uid": "current"}, 1024); !IsStatus(err, 302) || calls != 0 { - t.Fatal("payment delivery was refused or redirected", err, calls) + if _, _, err = c.Request(context.Background(), "onchain/credentials", map[string]string{"pod_uid": "current"}, 1024); !IsStatus(err, 302) || calls != 0 { + t.Fatal("onchain delivery was refused or redirected", err, calls) } c.ConfigURL = receiver.URL if _, _, err = c.Request(context.Background(), "config", nil, 1024); err == nil || calls != 0 { diff --git a/schema/validate.go b/schema/validate.go index d79bd6f..ebebe97 100644 --- a/schema/validate.go +++ b/schema/validate.go @@ -35,7 +35,7 @@ func ValidateReplicaCount(n int) error { } // Validate checks the entire normalized v1 contract, including cross-field -// invariants. It applies neither defaults nor deployment/payment policy. +// invariants. It applies neither defaults nor deployment/onchain policy. func Validate(d DefinitionV1) error { if err := boa.Validate(d); err != nil { return schemaError(err) @@ -165,7 +165,7 @@ func refDigest(r reference.Reference) string { func ValidatePolicy(d DefinitionV1, mode PaymentMode) error { e := new(ValidationError) if mode != Offchain && mode != Onchain { - e.add("price", "Unknown target Node payment mode.") + e.add("price", "Unknown target Node onchain mode.") } else if mode == Onchain && len(d.Apps) == 0 && d.Price.Amount == "0" { e.add("price.amount", "Onchain Node assignments require an explicit positive price.") } diff --git a/ui/src/catalog.tsx b/ui/src/catalog.tsx index b8e7514..d54bb67 100644 --- a/ui/src/catalog.tsx +++ b/ui/src/catalog.tsx @@ -110,7 +110,7 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho }) } return
-

App catalog

Prices belong to each immutable app revision. Payment activation is configured per machine.

+

App catalog

Prices belong to each immutable app revision. Onchain activation is configured per machine.

{problem &&
{problem}{fields.length > 0 &&
    {fields.map((f, i) =>
  • {f.path}: {f.message}
  • )}
}
} {message &&
{message}
}
    {apps.map(app =>
  • Revision {app.head.revision} · version {app.head.app_version || '(unversioned)'} · {app.active_revision_count} active
  • )}
diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index df113dc..342f266 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -7,11 +7,11 @@ type Probe = { observed_at: string; due_at: string; expires_at: string; success: type Instance = { revision_id: string; generation: number; activation_generation: number; instance_id: string; pod_uid?: string; runner_id?: string; app_id?: string; phase: string; ready: boolean; registered: boolean; capacity: number; sessions: number; reason?: string; workload_reason?: string; deadline?: string; withdrawal_id?: string; drain_expired_at?: string; forced?: boolean; removal_published_at?: string; terminated_at?: string; registration_gone?: boolean; node_observed_at?: string; node_expires_at?: string; accepted_sequence?: number; startup_deadline?: string; probe?: Probe } type AssignmentObservation = { revision_id: string; generation: number; activation_generation: number; reason?: string; instances: number; ready: number; registered: number; cleanup_pending: number; node_expires_at?: string; probe_expires_at?: string } type Apps = { desired_generation: number; desired_digest?: string; staged?: Stage; published?: Stage; applied?: Stage; reason?: string; instances: Instance[]; assignments?: AssignmentObservation[]; instances_total?: number; instances_omitted?: number; owner_recreated_at?: string } -type PaymentEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; queue_known: boolean; unsettled: number; handoff: string } -type Component = { payment?: PaymentEvidence; observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } +type OnchainEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; queue_known: boolean; unsettled: number; handoff: string } +type Component = { onchain?: OnchainEvidence; observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } type Assignment = { revision_id: string; digest: string; name: string; version: string; revision: number; generation: number; activation_generation: number; desired: string; replicas: number; start_allowed: boolean; completed_at: string | null; failure?: string; health: { type: string; interval: string; timeout: string; failure_threshold: number } } type Membership = { state: string; provenance_current: boolean; queried_at?: string; observed_at?: string; expires_at?: string } -export type MachineObservation = { payment?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number; recovery_required: boolean }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } +export type MachineObservation = { onchain?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number; recovery_required: boolean }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } export function machineStatusSummary(machine: { terminal?: boolean; report_state?: string; last_config_fetch_at?: string | null }) { const labels: Record = { observed: 'Runtime observed', stale: 'Status stale', clock_uncertain: 'Clock uncertain' } @@ -19,8 +19,8 @@ export function machineStatusSummary(machine: { terminal?: boolean; report_state } const reasons: Record = { - payment_not_ready: 'Onchain Node is not ready; inspect credential delivery, retained payment state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', - payment_pending: 'Waiting for the target payment configuration', payment_incompatible: 'App price is incompatible with the target payment mode', payment_drain_pending: 'Waiting for payment settlement', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', + onchain_not_ready: 'Onchain Node is not ready; inspect credential delivery, retained onchain state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', + onchain_pending: 'Waiting for the target onchain configuration', onchain_incompatible: 'App price is incompatible with the target onchain mode', onchain_drain_pending: 'Waiting for onchain settlement', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', } function reason(code?: string) { return code ? reasons[code] || code.replaceAll('_', ' ') : '' } function date(value?: string | null) { return value && Date.parse(value) > 0 ? new Date(value).toLocaleString() : 'Unobserved' } @@ -83,13 +83,13 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: {problem &&
{problem}
} {!view && !problem &&

Loading observed state…

} {view && <> - {view.payment &&
-

Payment operation

-

Desired: {view.payment.desired.mode} · generation {view.payment.desired.generation}. Delivered generation: {view.payment.delivered_generation}.

- {view.payment.desired.recipient &&

Recipient: {view.payment.desired.recipient} · {view.payment.desired.network}

} -

Configuration: {fresh(runtime) && runtime?.payment?.applied ? `applied generation ${runtime.payment.generation}` : 'pending or unobserved'}. Local onchain admission: {fresh(runtime) && runtime?.payment?.mode === 'onchain' && runtime.payment.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.payment?.handoff || 'unverified' : 'unverified'}.

- {fresh(runtime) && runtime?.payment?.mode === 'offchain' &&

Effective service is free; catalog registration quotes are retained.

} - {view.payment.recovery_required &&

Payment recovery required. Retained tickets have not been confirmed drained.

} + {view.onchain &&
+

Onchain operation

+

Desired: {view.onchain.desired.mode} · generation {view.onchain.desired.generation}. Delivered generation: {view.onchain.delivered_generation}.

+ {view.onchain.desired.recipient &&

Recipient: {view.onchain.desired.recipient} · {view.onchain.desired.network}

} +

Configuration: {fresh(runtime) && runtime?.onchain?.applied ? `applied generation ${runtime.onchain.generation}` : 'pending or unobserved'}. Local onchain admission: {fresh(runtime) && runtime?.onchain?.mode === 'onchain' && runtime.onchain.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.onchain?.handoff || 'unverified' : 'unverified'}.

+ {fresh(runtime) && runtime?.onchain?.mode === 'offchain' &&

Effective service is free; catalog registration quotes are retained.

} + {view.onchain.recovery_required &&

Onchain recovery required. Retained tickets have not been confirmed drained.

}
}

{reason(view.lifecycle)} · rollout generation {view.rollout_generation}. External app reachability: unverified. Configured checks observe the private app endpoint.

diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index 9908cfd..8e3f573 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -41,7 +41,7 @@ async function setup(page: Page, admin = false, reportState = 'observed', termin if (path === '/api/bootstrap-token') return route.fulfill({ json: { token: 'fixture', expires_at: new Date(Date.now() + 3600000).toISOString() } }) if (path === '/api/me') return route.fulfill({ json: { user_id: user, is_admin: state.admin } }) if (path === '/api/admin/administrators') return route.fulfill({ json: { administrators: [] } }) - if (path === '/api/admin/apps') return route.fulfill({ json: { apps: [], payment_mode: 'offchain', next_after_name: null } }) + if (path === '/api/admin/apps') return route.fulfill({ json: { apps: [], onchain_mode: 'offchain', next_after_name: null } }) if (path === '/api/admin/machines') return route.fulfill({ json: { machines: [listedMachine] } }) if (path === '/api/machines') return route.fulfill({ json: { machines: admin ? [] : [listedMachine, { ...machine, node_id: 'lp-bbbbbbbbbbbbbbbb', hostname: 'second-worker', epoch: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' }] } }) if (path.startsWith('/api/admin/machines/') && path.endsWith('/apps')) return route.fulfill({ json: { epoch, assignments: [], apps_generation: 2, published_generation: 1, next_after_revision_id: null, last_config_fetch_at: null } }) @@ -231,15 +231,15 @@ test('expired inventory preserves its unverified source-version explanation', as test('onchain readiness stays separate from handoff and retirement recovery', async ({ page }) => { await page.clock.install() const state = await setup(page, false) - state.view.payment = { desired: { mode: 'onchain', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } - state.view.components[0].payment = { generation: 3, mode: 'onchain', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } + state.view.onchain = { desired: { mode: 'onchain', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } + state.view.components[0].onchain = { generation: 3, mode: 'onchain', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } await page.clock.fastForward(5100) - await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Local onchain admission: ready') - await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Remote handoff: degraded') - state.view.payment.recovery_required = true + await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Local onchain admission: ready') + await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Remote handoff: degraded') + state.view.onchain.recovery_required = true await page.clock.fastForward(5100) - await expect(page.getByRole('alert')).toContainText('Payment recovery required') + await expect(page.getByRole('alert')).toContainText('Onchain recovery required') state.view.components[0].fresh = false await page.clock.fastForward(5100) - await expect(page.getByRole('region', { name: 'Payment operation' })).toContainText('Remote handoff: unverified') + await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Remote handoff: unverified') }) From e9f744e68e4a837d5f4d6e2be63176a4bc016d17 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 08:40:21 -0800 Subject: [PATCH 09/15] Use Node drain for redeemer handoff and remove settlement workflow --- .../machineconfig/observations.go | 2 +- .../controlplane/machineconfig/reports.go | 2 +- .../controlplane/machineconfig/rollout.go | 64 +------------- .../controlplane/machineconfig/types.go | 2 - .../controlplane/migrations/009_onchain.sql | 6 +- api/internal/controlplane/observed_state.go | 3 - api/internal/controlplane/onchain_settings.go | 45 +--------- api/internal/controlplane/onchain_test.go | 88 ++----------------- deploy/README.md | 2 + docs/operations.md | 11 ++- runtime/appreconciler/onchain_test.go | 43 +++++++++ runtime/appreconciler/owner.go | 5 ++ runtime/appreconciler/report.go | 2 +- runtime/onchain/config.go | 2 - runtime/orchestrator/integration_test.go | 15 +--- runtime/orchestrator/observation.go | 29 ------ runtime/orchestrator/process.go | 2 +- ui/src/machine-status.tsx | 7 +- ui/tests/machine-status.spec.ts | 13 +-- 19 files changed, 87 insertions(+), 256 deletions(-) diff --git a/api/internal/controlplane/machineconfig/observations.go b/api/internal/controlplane/machineconfig/observations.go index 61487d2..874e9d0 100644 --- a/api/internal/controlplane/machineconfig/observations.go +++ b/api/internal/controlplane/machineconfig/observations.go @@ -20,7 +20,7 @@ func optionalID(s string) bool { return s == "" || statusID.MatchString(s) } func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) error { if p := r.Onchain; p != nil { - if r.Component != "runtime" || (p.Mode != "onchain" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || p.Unsettled < 0 || p.Unsettled > 10000000 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { + if r.Component != "runtime" || (p.Mode != "onchain" && p.Mode != "offchain") || p.Generation < 0 || len(p.PodUID) > 128 || (p.Handoff != "healthy" && p.Handoff != "degraded" && p.Handoff != "unverified") { return ErrStaleStatus } if p.Applied { diff --git a/api/internal/controlplane/machineconfig/reports.go b/api/internal/controlplane/machineconfig/reports.go index 5932c8f..f9ef348 100644 --- a/api/internal/controlplane/machineconfig/reports.go +++ b/api/internal/controlplane/machineconfig/reports.go @@ -95,7 +95,7 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b if previous.Drained && previous.Generation == report.Generation && previous.Evidence != nil && report.Evidence != nil && previous.Evidence.Target == report.Evidence.Target && time.Now().Before(previous.Evidence.ExpiresAt) { drainWake = false } - onchainWake := report.Component == "runtime" && report.Onchain != nil && (record.RolloutReason == "onchain_drain_pending" || (report.Onchain.Mode == "onchain" && record.ApprovedConfigDigest != report.ConfigDigest)) + onchainWake := report.Component == "runtime" && report.Onchain != nil && (report.Onchain.Mode == "onchain" && record.ApprovedConfigDigest != report.ConfigDigest) return onchainWake || drainWake || (report.Component == "runtime" && (report.Ready && record.ApplyingConfigDigest != "" && report.ConfigDigest == record.ApplyingConfigDigest && report.Generation == record.Generation)), nil } diff --git a/api/internal/controlplane/machineconfig/rollout.go b/api/internal/controlplane/machineconfig/rollout.go index 0ffbde7..98a6fca 100644 --- a/api/internal/controlplane/machineconfig/rollout.go +++ b/api/internal/controlplane/machineconfig/rollout.go @@ -29,9 +29,6 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des if desired.OnchainError != nil { return false, desired.OnchainError } - if desired.Onchain.Onchain() { - state.OnchainSettled = false - } old, manifest, err := s.applied(ctx, m) if err != nil { return false, err @@ -43,7 +40,7 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des // Admission has never opened for this onchain target. Its image or rendering // can be repaired without asking the failed process to drain again, while // retaining the exact onchain/storage binding and the admission freeze. - frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested && !state.OnchainDrainAfter.IsZero() + frozen := state.ApplyingConfigDigest == old.ConfigDigest && state.DrainRequested initial := state.ApplyingConfigDigest == "" && state.ApprovedConfigDigest == "" if old.ConfigDigest != digest && old.Onchain.Onchain() && !old.OnchainActive && state.ApprovedConfigDigest != old.ConfigDigest && onchainJSON(old.Onchain) == onchainJSON(desired.Onchain) && old.UpgradeVersion == upgradeVersion(desired) && (frozen || initial) { state.HeldOrchestrator, state.HeldUpgradePlan = "", "" @@ -103,15 +100,6 @@ func (s *Manager) Gate(ctx context.Context, m Machine, state *State, desired Des return true, err } } - if old.Onchain.Onchain() && (!desired.Onchain.Onchain() || desired.Onchain.RedeemerURL != old.Onchain.RedeemerURL) { - if !s.onchainDrained(ctx, m, old, state.OnchainDrainAfter) { - state.RolloutReason = "onchain_drain_pending" - return true, nil - } - if !desired.Onchain.Onchain() { - state.OnchainSettled = true - } - } state.HeldOrchestrator = "" state.HeldUpgradePlan = "" state.ApplyingConfigDigest = digest @@ -188,7 +176,6 @@ func (s *Manager) drainComplete(ctx context.Context, m Machine, state *State) (b return false, err } if report.Drained && report.Generation == state.Generation && time.Since(at) <= s.config.StatusTTL && validDrainEvidence(m, *state, report, time.Now()) { - state.OnchainDrainAfter = evidenceTime(report) state.RolloutReason = "" return true, nil } @@ -210,14 +197,6 @@ func (s *Manager) removalComplete(ctx context.Context, m Machine, state *State) state.RolloutReason = "app_cleanup_pending" return false, err } - old, _, e := s.applied(ctx, m) - if e != nil { - return false, e - } - if !s.onchainDrained(ctx, m, old, state.OnchainDrainAfter) { - state.RolloutReason = "onchain_drain_pending" - return false, nil - } state.RolloutReason = "" return true, nil } @@ -227,47 +206,12 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { if err != nil || !done { return false, err } - tx, err := s.store.DB.BeginTx(ctx, nil) - if err != nil { - return false, err - } - defer tx.Rollback() - var yes int - err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$3 FOR UPDATE`, l.Machine.NodeID, l.Machine.Epoch, l.Machine.CredentialVersion).Scan(&yes) - if errors.Is(err, sql.ErrNoRows) { - return false, nil - } - if err != nil { - return false, err - } - err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND lease_id=$3 AND revision=$4 AND lease_until>now() FOR UPDATE`, l.Machine.NodeID, l.Machine.Epoch, l.ID, l.Revision).Scan(&yes) - if errors.Is(err, sql.ErrNoRows) { - return false, nil - } + result, err := s.store.DB.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$5 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND lease_id=$3 AND revision=$4 AND lease_until>now())`, l.Machine.NodeID, l.Machine.Epoch, l.ID, l.Revision, l.Machine.CredentialVersion) if err != nil { return false, err } - if _, err = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET drained=true WHERE node_id=$1`, l.Machine.NodeID); err != nil { - return false, err - } - if _, err = tx.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2`, l.Machine.NodeID, l.Machine.Epoch); err != nil { - return false, err - } - return true, tx.Commit() + n, err := result.RowsAffected() + return n == 1, err } func onchainJSON(c onchain.Config) string { b, _ := json.Marshal(c); return string(b) } -func (s *Manager) onchainDrained(ctx context.Context, m Machine, old Runtime, after time.Time) bool { - if !old.Onchain.Onchain() { - return true - } - r, at, e := s.store.Report(ctx, m, "runtime") - return e == nil && !after.IsZero() && !r.ObservedAt.Before(after) && r.Generation == old.Generation && !r.ClockUncertain && time.Since(at) <= s.config.StatusTTL && time.Since(r.ObservedAt) <= s.config.StatusTTL && r.ConfigDigest == old.ConfigDigest && r.Onchain != nil && r.Onchain.Generation == old.Onchain.Generation && r.Onchain.Applied && r.Onchain.QueueKnown && r.Onchain.Unsettled == 0 -} - -func evidenceTime(r Report) time.Time { - if r.Evidence == nil { - return time.Time{} - } - return r.Evidence.ObservedAt -} diff --git a/api/internal/controlplane/machineconfig/types.go b/api/internal/controlplane/machineconfig/types.go index 7d733f4..43c1d3e 100644 --- a/api/internal/controlplane/machineconfig/types.go +++ b/api/internal/controlplane/machineconfig/types.go @@ -30,8 +30,6 @@ type State struct { DrainStartedAt time.Time `json:"drain_started_at,omitempty"` DrainedGeneration int64 `json:"drained_generation,omitempty"` Target string `json:"target,omitempty"` - OnchainSettled bool `json:"onchain_settled,omitempty"` - OnchainDrainAfter time.Time `json:"onchain_drain_after,omitempty"` HeldOnchain string `json:"held_onchain,omitempty"` HeldOrchestrator string `json:"held_orchestrator,omitempty"` PendingConfigDigest string `json:"pending_config_digest,omitempty"` diff --git a/api/internal/controlplane/migrations/009_onchain.sql b/api/internal/controlplane/migrations/009_onchain.sql index 6d16b5d..4ffe9be 100644 --- a/api/internal/controlplane/migrations/009_onchain.sql +++ b/api/internal/controlplane/migrations/009_onchain.sql @@ -1,5 +1,5 @@ -- UP --- Retain storage identity and recovery state after the active machine is removed. +-- Retain storage identity after the active machine is removed. CREATE TABLE lpcc.onchain_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); INSERT INTO lpcc.onchain_revision DEFAULT VALUES; CREATE TABLE lpcc.onchain_configs ( @@ -10,7 +10,7 @@ CREATE TABLE lpcc.onchain_state ( node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', generation BIGINT NOT NULL CHECK(generation>0), - initialized BOOLEAN NOT NULL DEFAULT false, drained BOOLEAN NOT NULL DEFAULT false, recovery_required BOOLEAN NOT NULL DEFAULT false, + initialized BOOLEAN NOT NULL DEFAULT false, FOREIGN KEY(node_id,generation) REFERENCES lpcc.onchain_configs(node_id,generation) ); CREATE TABLE lpcc.onchain_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); @@ -27,8 +27,6 @@ CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LAN SET search_path=pg_catalog,lpcc AS $$ BEGIN UPDATE lpcc.onchain_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; - UPDATE lpcc.onchain_state b SET recovery_required=b.recovery_required OR (NOT b.drained AND (b.initialized OR c.config->>'mode'='onchain') AND NOT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch AND rollout->>'onchain_settled'='true')) - FROM lpcc.onchain_configs c WHERE b.node_id=OLD.node_id AND c.node_id=b.node_id AND c.generation=b.generation; UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id diff --git a/api/internal/controlplane/observed_state.go b/api/internal/controlplane/observed_state.go index 837d39b..77fe8ce 100644 --- a/api/internal/controlplane/observed_state.go +++ b/api/internal/controlplane/observed_state.go @@ -245,7 +245,6 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse if !c.Fresh || !c.Current || c.ClockUncertain { copy.Ready = false copy.Applied = false - copy.QueueKnown = false copy.Handoff = "unverified" } c.Onchain = © @@ -438,7 +437,6 @@ func (s *Server) observedMachineList(ctx context.Context, owner string, admin bo type onchainView struct { Desired onchain.Config `json:"desired"` DeliveredGeneration int64 `json:"delivered_generation"` - RecoveryRequired bool `json:"recovery_required"` } func (s *Server) onchainView(ctx context.Context, m Machine) (onchainView, error) { @@ -451,7 +449,6 @@ func (s *Server) onchainView(ctx context.Context, m Machine) (onchainView, error v.Desired.RPCSecret = "" v.Desired.RPCGrants = nil v.Desired.RedeemerGrants = nil - _ = s.db.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, m.NodeID).Scan(&v.RecoveryRequired) var b []byte if m.Terminal { err = s.db.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&b) diff --git a/api/internal/controlplane/onchain_settings.go b/api/internal/controlplane/onchain_settings.go index dfd28a5..c4aef48 100644 --- a/api/internal/controlplane/onchain_settings.go +++ b/api/internal/controlplane/onchain_settings.go @@ -21,7 +21,6 @@ import ( "github.com/j0sh/boa/pkg/boa" "github.com/livepeer/control-center/api/internal/controlplane/machineapps" - "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" "github.com/livepeer/control-center/runtime/onchain" "github.com/spf13/cobra" ) @@ -55,7 +54,6 @@ type onchainApplyParams struct { OnchainWebhookSecretFile string `secretfor:"OnchainWebhookSecret" basepath:"source"` RuntimeNodeImage string `env:"RUNTIME_NODE_IMAGE" optional:"true"` File string `name:"file" boa:"noconfig" descr:"Onchain infrastructure JSON file"` - AcknowledgeRecovery string `name:"acknowledge-recovery" optional:"true" boa:"noconfig" descr:"Confirm restored retained state after a fresh empty-queue observation"` ExpectedRevision int64 `name:"expected-revision" min:"0" boa:"noconfig"` } @@ -75,7 +73,7 @@ func OnchainCommand() *cobra.Command { } defer db.Close() s := New(db, Params{OnchainSecretsDir: p.OnchainSecretsDir, OnchainWebhookSecret: p.OnchainWebhookSecret, RuntimeNodeImage: p.RuntimeNodeImage}, slog.New(slog.NewTextHandler(io.Discard, nil))) - rev, e := s.applyOnchain(cmd.Context(), input, p.ExpectedRevision, p.AcknowledgeRecovery) + rev, e := s.applyOnchain(cmd.Context(), input, p.ExpectedRevision) if e == nil { fmt.Fprintln(cmd.OutOrStdout(), rev) } @@ -116,7 +114,7 @@ func (s *Server) readOnchainRPC(ref string) ([]byte, error) { return b, nil } -func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected int64, acknowledge ...string) (int64, error) { +func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected int64) (int64, error) { if input.Version != 1 || len(input.Machines) == 0 || len(input.Machines) > 1000 { return 0, errors.New("invalid onchain document") } @@ -253,7 +251,7 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_configs VALUES($1,$2,$3)`, node, c.Generation, string(after)); e != nil { return 0, e } - _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_state(node_id,recipient,chain_id,controller,generation) VALUES($1,$2,$3,$4,$5) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation,drained=false`, node, recipient, chain, controller, c.Generation) + _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_state(node_id,recipient,chain_id,controller,generation) VALUES($1,$2,$3,$4,$5) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation`, node, recipient, chain, controller, c.Generation) if e != nil { return 0, e } @@ -265,43 +263,6 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected } changed = true } - if len(acknowledge) > 0 && acknowledge[0] != "" { - node := acknowledge[0] - if _, ok := input.Machines[node]; !ok { - return 0, errors.New("recovery acknowledgement requires the machine in the desired snapshot") - } - // Freeze publication and enrollment while checking the evidence against - // the currently delivered workload, including configuration-only changes. - var bundle []byte - if e = tx.QueryRowContext(ctx, `SELECT c.bundle FROM lpcc.machines m JOIN lpcc.machine_configs c USING(node_id) WHERE m.node_id=$1 FOR UPDATE OF m`, node).Scan(&bundle); e != nil { - return 0, errors.New("recovery acknowledgement requires a delivered configuration") - } - metadata, _, e := machineconfig.ReadApplied(bundle) - if e != nil { - return 0, e - } - var required bool - if e = tx.QueryRowContext(ctx, `SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1 FOR UPDATE`, node).Scan(&required); e != nil { - return 0, e - } - if required { - var ready bool - e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machines m JOIN lpcc.machine_reports r ON r.node_id=m.node_id AND r.epoch=m.enrollment_epoch AND r.credential_version=m.credential_version JOIN lpcc.onchain_state p ON p.node_id=m.node_id JOIN lpcc.onchain_grants g ON g.grant_id::text=r.report#>>'{onchain,grant_id}' AND g.node_id=m.node_id AND g.epoch=m.enrollment_epoch WHERE m.node_id=$1 AND r.component='runtime' AND r.generation=$2 AND r.report->>'config_digest'=$3 AND g.config_digest=$3 AND g.pod_uid=r.report#>>'{onchain,pod_uid}' AND g.onchain_generation=p.generation AND r.received_at>now()-interval '2 minutes' AND (r.report->>'observed_at')::timestamptz>now()-interval '2 minutes' AND NOT COALESCE((r.report->>'clock_uncertain')::boolean,false) AND r.report#>>'{onchain,applied}'='true' AND r.report#>>'{onchain,queue_known}'='true' AND r.report#>>'{onchain,unsettled}'='0' AND (r.report#>>'{onchain,generation}')::bigint=p.generation AND g.observed_at IS NOT NULL AND g.revoked_at IS NULL)`, node, metadata.Generation, metadata.ConfigDigest).Scan(&ready) - if e != nil { - return 0, e - } - if !ready { - return 0, errors.New("restore onchain state and obtain fresh zero-unsettled evidence before acknowledging recovery") - } - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET recovery_required=false WHERE node_id=$1`, node); e != nil { - return 0, e - } - if e = writeAudit(ctx, tx, "system", "deployment:onchain", "onchain.recover", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(revision + 1)}, "success", "recovery_acknowledged"); e != nil { - return 0, e - } - changed = true - } - } if expected > revision || (changed && expected != revision) { return 0, problem(409, "onchain_revision_changed", "Onchain infrastructure changed.") } diff --git a/api/internal/controlplane/onchain_test.go b/api/internal/controlplane/onchain_test.go index 1e7607b..786a70b 100644 --- a/api/internal/controlplane/onchain_test.go +++ b/api/internal/controlplane/onchain_test.go @@ -70,7 +70,7 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { t.Fatal("partial commit", n, e) } } -func TestOnchainCredentialsWebhookAndForcedRecovery(t *testing.T) { +func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) @@ -149,10 +149,6 @@ func TestOnchainCredentialsWebhookAndForcedRecovery(t *testing.T) { if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 403 { t.Fatal("forced retirement did not revoke") } - var recovery bool - if e = s.db.QueryRow(`SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&recovery); e != nil || !recovery { - t.Fatal(recovery, e) - } fresh := enroll(t, s, ownerA, strings.Repeat("a", 64)) if fresh["epoch"] == machine["epoch"] { t.Fatal("enrollment not replaced") @@ -163,7 +159,7 @@ func TestOnchainCredentialsWebhookAndForcedRecovery(t *testing.T) { } } -func TestOnchainActivationAndRemovalRequireFreshPostDrainOnchainEvidence(t *testing.T) { +func TestOnchainActivationAndNormalDrain(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) node := "lp-aaaaaaaaaaaaaaaa" @@ -199,35 +195,13 @@ func TestOnchainActivationAndRemovalRequireFreshPostDrainOnchainEvidence(t *test requireStatus(t, w, 200) var grant orchestrator.Grant json.Unmarshal(w.Body.Bytes(), &grant) - report := func(known bool, n int64) { + report := func() { t.Helper() m := metadata() - r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Onchain: &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, QueueKnown: known, Unsettled: n, Handoff: "unverified"}}) + r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Onchain: &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, Handoff: "unverified"}}) requireStatus(t, request(t, s, "POST", "/v1/nodes/"+node+"/status", c["token"], r), 200) } - if _, e := s.db.Exec(`UPDATE lpcc.onchain_state SET recovery_required=true WHERE node_id=$1`, node); e != nil { - t.Fatal(e) - } - in := onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}} - if _, e := s.applyOnchain(t.Context(), in, 1, node); e == nil { - t.Fatal("recovery acknowledged without fresh onchain evidence") - } - report(true, 0) - // A fresh report from a previously delivered configuration cannot clear - // recovery after publication changes, even within the same onchain generation. - if _, e := s.db.Exec(`UPDATE lpcc.machine_reports SET report=jsonb_set(report,'{config_digest}',to_jsonb(repeat('f',64))) WHERE node_id=$1 AND component='runtime'`, node); e != nil { - t.Fatal(e) - } - if _, e := s.applyOnchain(t.Context(), in, 1, node); e == nil { - t.Fatal("recovery acknowledged evidence for a different delivered configuration") - } - report(true, 0) - if rev, e := s.applyOnchain(t.Context(), in, 1, node); e != nil || rev != 2 { - t.Fatal("explicit restored-state acknowledgement", rev, e) - } - if rev, e := s.applyOnchain(t.Context(), in, 1, node); e != nil || rev != 2 { - t.Fatal("recovery acknowledgement retry", rev, e) - } + report() if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -239,37 +213,14 @@ func TestOnchainActivationAndRemovalRequireFreshPostDrainOnchainEvidence(t *test if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } - report(true, 0) // This zero predates authoritative completion of active work. reportRuntime(t, s, c, "runner", true) if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } - if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { - t.Fatal("pre-drain empty queue authorized retirement") - } - for _, sample := range []struct { - known bool - n int64 - }{{false, 0}, {true, 1}} { - report(sample.known, sample.n) - if e := s.reconcile(t.Context()); e != nil { - t.Fatal(e) - } - if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { - t.Fatal("unknown/nonempty queue authorized retirement") - } - } - report(true, 0) - if e := s.reconcile(t.Context()); e != nil { - t.Fatal(e) - } if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 0 { - t.Fatal("settled ordinary removal did not complete") - } - var drained, recovery bool - if e := s.db.QueryRow(`SELECT drained,recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&drained, &recovery); e != nil || !drained || recovery { - t.Fatal("ordinary retirement misclassified", drained, recovery, e) + t.Fatal("ordinary removal did not complete") } + } func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { @@ -450,29 +401,6 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) t.Fatal(e) } if !read().Onchain.Onchain() { - t.Fatal("failed onchain startup bypassed the settlement gate to offchain") - } -} - -func TestForcedRetirementCannotUseDesiredOffchainAsSettlementProof(t *testing.T) { - s := newTestServer(t) - cfg := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { - t.Fatal(e) - } - _ = enroll(t, s, ownerA, strings.Repeat("a", 64)) - if _, e := s.db.Exec(`UPDATE lpcc.onchain_state SET initialized=true WHERE node_id=$1`, node); e != nil { - t.Fatal(e) - } - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: onchain.Offchain()}}, 1); e != nil { - t.Fatal(e) - } - if e := s.RetireMachine(t.Context(), node); e != nil { - t.Fatal(e) - } - var required bool - if e := s.db.QueryRow(`SELECT recovery_required FROM lpcc.onchain_state WHERE node_id=$1`, node).Scan(&required); e != nil || !required { - t.Fatal("pending disable hid retained onchain state", required, e) + t.Fatal("failed onchain startup bypassed normal drain to offchain") } } diff --git a/deploy/README.md b/deploy/README.md index 5845ddd..987b0a8 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -65,6 +65,8 @@ installer's origin firewall remains required. Package the Node image with Runtime's startup wrapper and set `RuntimeNodeImage` to the pushed digest. Use the same Node build for `LIVEPEER_REDEEMER_IMAGE`. +The Node build must support `RPCURLFile`, `RedeemerHeadersFile` and unregister +acknowledgements that wait for durable redeemer handoff. ```sh docker build -f ../runtime/services/Dockerfile.node \ diff --git a/docs/operations.md b/docs/operations.md index 525bc42..35c0deb 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -91,15 +91,14 @@ versions for held workloads and rollback. Reapply previous settings at the curre revision to roll back. Configuration changes use the normal withdrawal/drain flow. Inspect configuration, local admission and remote handoff in **Runtime status**. -Disabling onchain operation, changing redemption destination and normal removal -wait for app drain and zero unsettled tickets. Forced removal revokes submission -grants immediately and reports `recovery_required`. Re-enroll the same machine -with its retained state; after a fresh zero-unsettled report, apply with -`--acknowledge-recovery ` to clear the flag. +Node's normal drain waits for durable redeemer handoff before acknowledging +retirement. Onchain confirmation continues independently at the redeemer. Forced +removal revokes submission grants immediately; preserve Node's database and +re-enroll with the same storage to resume any unfinished handoff. Back up Node's `/data/onchain.sqlite` and sidecars consistently, and back up the redeemer database and wallet separately. Keep the recipient/chain binding and -redemption routing/trust inputs while tickets remain unsettled. Private endpoints +redemption routing/trust inputs while handoff remains incomplete. Private endpoints require exact IP:port `rpc_grants` / `redeemer_grants`; these allow orchestrator access only. diff --git a/runtime/appreconciler/onchain_test.go b/runtime/appreconciler/onchain_test.go index e16f25f..cbb880f 100644 --- a/runtime/appreconciler/onchain_test.go +++ b/runtime/appreconciler/onchain_test.go @@ -19,6 +19,49 @@ import ( type onchainTransport func(*http.Request) (*http.Response, error) func (f onchainTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestOnchainEmptyOwnerStillRequiresNodeDrainAcknowledgement(t *testing.T) { + c, input, _, owner, reporter, _ := fixtureController(t) + input.value.Metadata.Onchain = onchain.Config{Version: 1, Mode: "onchain"} + input.value.Metadata.DrainRequested = true + input.value.Metadata.DrainTarget = "drain-target" + owner.unregisterFail = true + tick(t, c) + if reporter.reports[len(reporter.reports)-1].Drained || owner.unregisters == 0 { + t.Fatal("empty owner bypassed Node's durable handoff drain") + } + owner.unregisterFail = false + tick(t, c) + if !reporter.reports[len(reporter.reports)-1].Drained { + t.Fatal("Node's normal drain acknowledgement did not release maintenance") + } +} + +func TestEmptySDKOwnerUnregisterChecksNodeInsteadOfSkippingRequest(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != "POST" || !strings.HasSuffix(r.URL.Path, "/unregister") || r.Header.Get("Authorization") != "bootstrap" { + t.Error("invalid normal unregister request") + } + if calls == 1 { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + owner, err := NewSDKOwner(server.URL, "bootstrap", nil) + if err != nil { + t.Fatal(err) + } + if owner.Unregister(t.Context(), Identity{}) == nil { + t.Fatal("pending handoff was acknowledged") + } + if err := owner.Unregister(t.Context(), Identity{}); err != nil || calls != 2 { + t.Fatal("Node acknowledgement was not observed", err, calls) + } +} func TestOnchainAdmissionRequiresLiveMatchingNode(t *testing.T) { digest := strings.Repeat("a", 64) pods := 1 diff --git a/runtime/appreconciler/owner.go b/runtime/appreconciler/owner.go index 2b44d35..b81b197 100644 --- a/runtime/appreconciler/owner.go +++ b/runtime/appreconciler/owner.go @@ -308,6 +308,11 @@ func (o *SDKOwner) Unregister(ctx context.Context, id Identity) error { o.lifecycle.Lock() defer o.lifecycle.Unlock() credential := id.Credential + if id.RunnerID == "" { + // An absent owner still needs Node's normal unregister acknowledgement: + // a restarted Node may retain winners awaiting durable handoff. + id.RunnerID = randomID() + } if credential == "" { // A lost bootstrap response leaves an unknown issued credential. Retain // identity on 401 until Node expires it, then accept 404. Never Start. diff --git a/runtime/appreconciler/report.go b/runtime/appreconciler/report.go index 7f2996e..67dd84c 100644 --- a/runtime/appreconciler/report.go +++ b/runtime/appreconciler/report.go @@ -171,7 +171,7 @@ func (c *Controller) report(ctx context.Context, ready map[string]bool, view Vie report.Ready = false } report.Reason = "drain_pending" - if !s.Metadata.Terminal && clean && s.Identity.RunnerID == "" && s.MaintenanceWithdrawal != "" && !s.ClockUncertain { + if !s.Metadata.Terminal && clean && s.Identity.RunnerID == "" && s.MaintenanceWithdrawal != "" && !s.ClockUncertain && (!s.Metadata.Onchain.Onchain() || c.Owner.Unregister(ctx, s.Identity) == nil) { // No live owner can renew admission. This observation follows a successful Kube read // and durable owner retirement, rather than renewing an old heartbeat proof. report.Drained = true diff --git a/runtime/onchain/config.go b/runtime/onchain/config.go index 1df9b15..7f7f5cf 100644 --- a/runtime/onchain/config.go +++ b/runtime/onchain/config.go @@ -134,8 +134,6 @@ type Observation struct { GrantID string `json:"grant_id,omitempty"` Applied bool `json:"applied"` Ready bool `json:"ready"` - QueueKnown bool `json:"queue_known"` - Unsettled int64 `json:"unsettled"` Handoff string `json:"handoff"` } diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go index 0dbad90..098c476 100644 --- a/runtime/orchestrator/integration_test.go +++ b/runtime/orchestrator/integration_test.go @@ -79,7 +79,7 @@ func TestOnchainDeliveryFencesAndSecretPersistence(t *testing.T) { t.Fatal("insecure delivery") } } -func TestOnchainQueueEvidenceAndHandoffAreIndependent(t *testing.T) { +func TestOnchainReadinessAndHandoffAreIndependent(t *testing.T) { i, m, l := integrationFixture(t) g, e := i.fetch(t.Context(), l) if e != nil { @@ -91,16 +91,13 @@ func TestOnchainQueueEvidenceAndHandoffAreIndependent(t *testing.T) { processProof(t, i, g.Association, true) old := http.DefaultClient t.Cleanup(func() { http.DefaultClient = old }) - body := "# TYPE livepeer_collector_healthy gauge\n# TYPE livepeer_redemption_queue_tickets gauge\n# TYPE livepeer_redemption_transitions_total counter\nlivepeer_collector_healthy{component=\"orchestrator\",collector=\"redemptions\"} 1\n" - for _, s := range []string{"waiting", "eligible", "in_flight", "awaiting_finality", "rejected", "blocked", "unknown"} { - body += "livepeer_redemption_queue_tickets{component=\"orchestrator\",state=\"" + s + "\"} 0\n" - } + body := "# TYPE livepeer_redemption_transitions_total counter\n" metrics := body http.DefaultClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(metrics)), Header: make(http.Header)}, nil })} o := i.Observe(t.Context(), m, true, true, l.PodUID) - if !o.QueueKnown || o.Unsettled != 0 || !o.Ready || o.Handoff != "unverified" { + if !o.Ready || o.Handoff != "unverified" { t.Fatal(o) } metrics = body + "livepeer_redemption_transitions_total{component=\"orchestrator\",event=\"retryable\"} 1\n" @@ -124,11 +121,7 @@ func TestOnchainQueueEvidenceAndHandoffAreIndependent(t *testing.T) { t.Fatal("management restart renewed old handoff evidence") } - metrics = "livepeer_collector_healthy{component=\"orchestrator\",collector=\"redemptions\"} 1\n" - if i.Observe(t.Context(), m, true, true, l.PodUID).QueueKnown { - t.Fatal("missing samples fabricated empty queue") - } - if i.Observe(t.Context(), m, true, true, "replacement").QueueKnown { + if i.Observe(t.Context(), m, true, true, "replacement").Applied { t.Fatal("borrowed replaced pod evidence") } i.observation.ObservedAt = time.Now().Add(-31 * time.Second) diff --git a/runtime/orchestrator/observation.go b/runtime/orchestrator/observation.go index 1895b3a..cda0470 100644 --- a/runtime/orchestrator/observation.go +++ b/runtime/orchestrator/observation.go @@ -3,7 +3,6 @@ package orchestrator import ( "context" "io" - "math" "net/http" "strings" "time" @@ -53,9 +52,6 @@ func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, if e != nil { return o } - healthy := false - states := map[string]bool{} - var total int64 var ack, fail float64 for name, f := range families { for _, v := range f.Metric { @@ -67,24 +63,6 @@ func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, continue } switch name { - case "livepeer_collector_healthy": - if v.Gauge == nil { - return o - } - if labels["collector"] == "redemptions" && v.GetGauge().GetValue() == 1 { - healthy = true - } - case "livepeer_redemption_queue_tickets": - if v.Gauge == nil { - return o - } - n := v.GetGauge().GetValue() - s := labels["state"] - if states[s] || math.IsNaN(n) || math.IsInf(n, 0) || n < 0 || n > 10000000 || math.Trunc(n) != n { - return o - } - states[s] = true - total += int64(n) case "livepeer_redemption_transitions_total": if labels["event"] == "acknowledged" { ack += v.GetCounter().GetValue() @@ -95,11 +73,6 @@ func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, } } } - for _, s := range []string{"waiting", "eligible", "in_flight", "awaiting_finality", "rejected", "blocked", "unknown"} { - if !states[s] { - return o - } - } if i.checkPod(ctx, a.Launch, m) != nil { return o } @@ -108,8 +81,6 @@ func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, if i.grant != a { return o } - o.QueueKnown = healthy && len(states) == 7 - o.Unsettled = total now := time.Now() if i.metricsGrant == a.GrantID && (ack < i.lastAck || fail < i.lastErr) { return o diff --git a/runtime/orchestrator/process.go b/runtime/orchestrator/process.go index 52525f5..159c879 100644 --- a/runtime/orchestrator/process.go +++ b/runtime/orchestrator/process.go @@ -110,7 +110,7 @@ func checkOnchainState(path string, required bool) error { } info, e := os.Lstat(path) if e != nil || !info.Mode().IsRegular() || info.Size() == 0 { - return errors.New("onchain_state_recovery_required") + return errors.New("onchain_storage_missing") } return nil } diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index 342f266..e2a1480 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -7,11 +7,11 @@ type Probe = { observed_at: string; due_at: string; expires_at: string; success: type Instance = { revision_id: string; generation: number; activation_generation: number; instance_id: string; pod_uid?: string; runner_id?: string; app_id?: string; phase: string; ready: boolean; registered: boolean; capacity: number; sessions: number; reason?: string; workload_reason?: string; deadline?: string; withdrawal_id?: string; drain_expired_at?: string; forced?: boolean; removal_published_at?: string; terminated_at?: string; registration_gone?: boolean; node_observed_at?: string; node_expires_at?: string; accepted_sequence?: number; startup_deadline?: string; probe?: Probe } type AssignmentObservation = { revision_id: string; generation: number; activation_generation: number; reason?: string; instances: number; ready: number; registered: number; cleanup_pending: number; node_expires_at?: string; probe_expires_at?: string } type Apps = { desired_generation: number; desired_digest?: string; staged?: Stage; published?: Stage; applied?: Stage; reason?: string; instances: Instance[]; assignments?: AssignmentObservation[]; instances_total?: number; instances_omitted?: number; owner_recreated_at?: string } -type OnchainEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; queue_known: boolean; unsettled: number; handoff: string } +type OnchainEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; handoff: string } type Component = { onchain?: OnchainEvidence; observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } type Assignment = { revision_id: string; digest: string; name: string; version: string; revision: number; generation: number; activation_generation: number; desired: string; replicas: number; start_allowed: boolean; completed_at: string | null; failure?: string; health: { type: string; interval: string; timeout: string; failure_threshold: number } } type Membership = { state: string; provenance_current: boolean; queried_at?: string; observed_at?: string; expires_at?: string } -export type MachineObservation = { onchain?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number; recovery_required: boolean }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } +export type MachineObservation = { onchain?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } export function machineStatusSummary(machine: { terminal?: boolean; report_state?: string; last_config_fetch_at?: string | null }) { const labels: Record = { observed: 'Runtime observed', stale: 'Status stale', clock_uncertain: 'Clock uncertain' } @@ -20,7 +20,7 @@ export function machineStatusSummary(machine: { terminal?: boolean; report_state const reasons: Record = { onchain_not_ready: 'Onchain Node is not ready; inspect credential delivery, retained onchain state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', - onchain_pending: 'Waiting for the target onchain configuration', onchain_incompatible: 'App price is incompatible with the target onchain mode', onchain_drain_pending: 'Waiting for onchain settlement', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', + onchain_pending: 'Waiting for the target onchain configuration', onchain_incompatible: 'App price is incompatible with the target onchain mode', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', } function reason(code?: string) { return code ? reasons[code] || code.replaceAll('_', ' ') : '' } function date(value?: string | null) { return value && Date.parse(value) > 0 ? new Date(value).toLocaleString() : 'Unobserved' } @@ -89,7 +89,6 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: {view.onchain.desired.recipient &&

Recipient: {view.onchain.desired.recipient} · {view.onchain.desired.network}

}

Configuration: {fresh(runtime) && runtime?.onchain?.applied ? `applied generation ${runtime.onchain.generation}` : 'pending or unobserved'}. Local onchain admission: {fresh(runtime) && runtime?.onchain?.mode === 'onchain' && runtime.onchain.ready ? 'ready' : 'not verified'}. Remote handoff: {fresh(runtime) ? runtime?.onchain?.handoff || 'unverified' : 'unverified'}.

{fresh(runtime) && runtime?.onchain?.mode === 'offchain' &&

Effective service is free; catalog registration quotes are retained.

} - {view.onchain.recovery_required &&

Onchain recovery required. Retained tickets have not been confirmed drained.

}
}

{reason(view.lifecycle)} · rollout generation {view.rollout_generation}. External app reachability: unverified. Configured checks observe the private app endpoint.

diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index 8e3f573..decada9 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -228,18 +228,13 @@ test('expired inventory preserves its unverified source-version explanation', as await expect(page.getByText('Retained inventory has no confirmation for the current source version', { exact: false })).toBeVisible() }) -test('onchain readiness stays separate from handoff and retirement recovery', async ({ page }) => { +test('onchain readiness stays separate from remote handoff', async ({ page }) => { await page.clock.install() const state = await setup(page, false) - state.view.onchain = { desired: { mode: 'onchain', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3, recovery_required: false } - state.view.components[0].onchain = { generation: 3, mode: 'onchain', applied: true, ready: true, queue_known: true, unsettled: 1, handoff: 'degraded' } + state.view.onchain = { desired: { mode: 'onchain', generation: 3, recipient: `0x${'2'.repeat(40)}`, network: 'custom' }, delivered_generation: 3 } + state.view.components[0].onchain = { generation: 3, mode: 'onchain', applied: true, ready: true, handoff: 'degraded' } await page.clock.fastForward(5100) await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Local onchain admission: ready') await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Remote handoff: degraded') - state.view.onchain.recovery_required = true - await page.clock.fastForward(5100) - await expect(page.getByRole('alert')).toContainText('Onchain recovery required') - state.view.components[0].fresh = false - await page.clock.fastForward(5100) - await expect(page.getByRole('region', { name: 'Onchain operation' })).toContainText('Remote handoff: unverified') + }) From cbfe167eb91b3765eca9dab0178b9c72cd766359 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:15:01 -0800 Subject: [PATCH 10/15] Remove enrollment epochs and simplify fleet discovery --- api/cmd/controlcenter/main_test.go | 2 +- .../administrator_database_test.go | 2 +- .../controlplane/appreconciler_test.go | 26 +-- api/internal/controlplane/assignments.go | 113 +++++-------- api/internal/controlplane/assignments_test.go | 62 +++---- .../controlplane/certificates_test.go | 14 +- .../controlplane/controlplane_test.go | 8 +- api/internal/controlplane/discovery.go | 4 +- api/internal/controlplane/discovery/auth.go | 88 +++++----- .../controlplane/discovery/auth_test.go | 2 +- .../controlplane/discovery/manager.go | 29 +--- .../controlplane/discovery/manager_test.go | 107 ++++-------- .../controlplane/discovery/membership.go | 63 ++----- .../controlplane/discovery/membership_test.go | 73 ++------ .../controlplane/discovery/sources.go | 157 ++++-------------- api/internal/controlplane/discovery/status.go | 31 ++-- api/internal/controlplane/discovery/types.go | 2 - .../controlplane/discovery_database_test.go | 25 ++- api/internal/controlplane/machine_admin.go | 28 ++-- .../controlplane/machine_credentials.go | 62 +++---- .../controlplane/machineapps/store.go | 44 ++--- api/internal/controlplane/machineconfig.go | 5 +- .../controlplane/machineconfig/apps.go | 10 +- .../controlplane/machineconfig/apps_test.go | 6 +- .../controlplane/machineconfig/bundle_test.go | 2 +- .../controlplane/machineconfig/commands.go | 46 +++-- .../controlplane/machineconfig/manager.go | 26 +-- .../machineconfig/observations.go | 14 +- .../machineconfig/onchain_test.go | 4 +- .../controlplane/machineconfig/reports.go | 16 +- .../controlplane/machineconfig/rollout.go | 4 +- .../controlplane/machineconfig/runtime.go | 6 +- .../controlplane/machineconfig/store.go | 24 +-- .../controlplane/machineconfig/system_test.go | 14 +- .../templates/system/node/orchestrator.yaml | 1 - .../controlplane/machineconfig/types.go | 8 +- .../machineconfig_database_test.go | 22 +-- .../controlplane/migrations/001_initial.sql | 2 +- .../migrations/004_machine_tunnels.sql | 32 ++-- .../migrations/005_machine_configuration.sql | 16 +- .../migrations/006_machine_apps.sql | 64 +++---- .../migrations/007_runtime_retirement.sql | 2 +- .../migrations/008_machine_certificates.sql | 5 +- .../controlplane/migrations/009_onchain.sql | 20 +-- api/internal/controlplane/observed_state.go | 50 +++--- .../controlplane/observed_state_test.go | 64 +++---- .../controlplane/onchain_credentials.go | 22 +-- api/internal/controlplane/onchain_settings.go | 26 +-- api/internal/controlplane/onchain_test.go | 62 ++++--- api/internal/controlplane/registry_test.go | 2 +- api/internal/controlplane/server.go | 38 +++-- .../controlplane/tunnel/certificates.go | 6 +- .../controlplane/tunnel/certificates_test.go | 34 ---- .../tunnel/cloudflare_access_test.go | 6 +- .../tunnel/cloudflare_deletion_test.go | 2 +- .../controlplane/tunnel/endpoints_test.go | 6 +- api/internal/controlplane/tunnel/identity.go | 41 ----- api/internal/controlplane/tunnel/ingress.go | 13 +- .../controlplane/tunnel/ingress_cli_test.go | 47 +++--- api/internal/controlplane/tunnel/manager.go | 9 +- .../controlplane/tunnel/operations.go | 6 +- .../controlplane/tunnel/protection.go | 2 +- api/internal/controlplane/tunnel/reconcile.go | 31 ++-- api/internal/controlplane/tunnel/store.go | 59 +++---- .../controlplane/tunnel/tunnel_test.go | 34 ++-- api/internal/controlplane/tunnel/types.go | 3 - .../controlplane/tunnel_recovery_test.go | 93 ++++++----- api/internal/controlplane/tunnels.go | 4 +- api/internal/controlplane/tunnels_test.go | 60 +++---- deploy/onchain.example.json | 4 +- docs/app-registry.md | 14 +- docs/fleet-discovery.md | 14 +- docs/machine-tunnels.md | 22 +-- runtime/README.md | 4 + runtime/appbundle/bundle.go | 10 +- runtime/appbundle/bundle_test.go | 4 +- runtime/appreconciler/controller.go | 16 +- runtime/appreconciler/controller_test.go | 24 ++- runtime/appreconciler/hostnames_test.go | 2 +- runtime/appreconciler/input.go | 2 +- .../appreconciler/node_integration_test.go | 6 +- runtime/appreconciler/owner.go | 29 ++-- runtime/appreconciler/owner_test.go | 6 +- runtime/appreconciler/report.go | 8 +- runtime/appreconciler/report_test.go | 3 +- runtime/appreconciler/rolling.go | 2 +- runtime/appreconciler/rolling_test.go | 2 +- runtime/appreconciler/state.go | 1 - runtime/appreconciler/state_test.go | 3 +- runtime/bootstrap-livepeer.sh | 7 +- runtime/cmd/livepeer-runtime/main.go | 2 +- runtime/connector/integration.go | 14 +- runtime/connector/integration_test.go | 10 +- runtime/contract/contract.go | 1 - runtime/httpsource/component.go | 18 +- runtime/httpsource/source.go | 18 +- runtime/httpsource/source_test.go | 16 +- runtime/internal/testutil/assignment.go | 2 +- runtime/lib/credentials.sh | 50 +++--- runtime/management/relay.go | 4 +- runtime/management/sockets_test.go | 8 +- runtime/nodeproxy/proxy_test.go | 24 +-- runtime/orchestrator/integration.go | 8 +- runtime/orchestrator/integration_test.go | 4 +- runtime/orchestrator/observation.go | 2 +- runtime/tests/test_bootstrap.py | 12 +- runtime/tests/test_credentials.py | 35 ++-- runtime/transport/client.go | 14 +- runtime/transport/client_test.go | 6 +- runtime/transport/reports.go | 16 +- runtime/transport/reports_test.go | 14 +- schema/assignments.go | 5 +- schema/assignments_test.go | 2 +- ui/src/administration.tsx | 6 +- ui/src/catalog.tsx | 8 +- ui/src/machine-apps.tsx | 26 ++- ui/src/machine-status.tsx | 15 +- ui/src/main.tsx | 6 +- ui/tests/administration.spec.ts | 2 +- ui/tests/machine-apps.spec.ts | 18 +- ui/tests/machine-status.spec.ts | 23 ++- 121 files changed, 1114 insertions(+), 1469 deletions(-) delete mode 100644 api/internal/controlplane/tunnel/identity.go diff --git a/api/cmd/controlcenter/main_test.go b/api/cmd/controlcenter/main_test.go index e7e8d4c..8fbd78c 100644 --- a/api/cmd/controlcenter/main_test.go +++ b/api/cmd/controlcenter/main_test.go @@ -78,7 +78,7 @@ func TestOnchainCommandHelpDoesNotExposeSecrets(t *testing.T) { func TestOnchainInputRejectsUnknownPricingAndDuplicateFields(t *testing.T) { t.Setenv("PG_CONNSTR", "postgres://unused.invalid/no-network") for _, body := range []string{ - `{"version":1,"machines":{"lp-aaaaaaaaaaaaaaaa":{"version":1,"mode":"offchain","price":"1"}}}`, + `{"version":1,"machines":{"vkvkvkvkvkvkuaaaaaaaaaaaaa":{"version":1,"mode":"offchain","price":"1"}}}`, `{"version":1,"version":1,"machines":{}}`, `{"version":2,"machines":{}}`, } { diff --git a/api/internal/controlplane/administrator_database_test.go b/api/internal/controlplane/administrator_database_test.go index e9b9e59..8a0d24d 100644 --- a/api/internal/controlplane/administrator_database_test.go +++ b/api/internal/controlplane/administrator_database_test.go @@ -63,7 +63,7 @@ func TestAdministratorDatabasePrivileges(t *testing.T) { t.Fatal("schema access", role, usage, err) } var view, execute bool - if err := db.QueryRow(`SELECT has_table_privilege($1,'lpcc.machine_app_heads','SELECT,INSERT,UPDATE,DELETE'),has_function_privilege($1,'lpcc.remove_machine_apps(text,uuid,text)','EXECUTE')`, role).Scan(&view, &execute); err != nil || view || execute { + if err := db.QueryRow(`SELECT has_table_privilege($1,'lpcc.machine_app_heads','SELECT,INSERT,UPDATE,DELETE'),has_function_privilege($1,'lpcc.remove_machine_apps(text,text)','EXECUTE')`, role).Scan(&view, &execute); err != nil || view || execute { t.Fatal("assignment view/function access", role, view, execute, err) } for _, table := range []string{"administrator_grants", "admin_audit_events", "apps", "app_revisions", "app_revision_state", "enrollments", "credential_refreshes", "machine_reports", "machine_states", "access_credentials", "machine_app_versions", "machine_app_deliveries", "machine_app_completions", "machine_app_diagnostics", "onchain_revision", "onchain_state", "onchain_configs", "onchain_secrets", "onchain_grants"} { diff --git a/api/internal/controlplane/appreconciler_test.go b/api/internal/controlplane/appreconciler_test.go index e0c7189..993a8cc 100644 --- a/api/internal/controlplane/appreconciler_test.go +++ b/api/internal/controlplane/appreconciler_test.go @@ -18,7 +18,7 @@ func TestAppReconcilerReportOrderingAndDuplicateFreshness(t *testing.T) { if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - payload := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), Epoch: c["epoch"], CredentialVersion: 1, Component: "runner", Generation: 1, BundleFormat: contract.BundleFormat, Sequence: 1, Ready: true, Reason: "ready", Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}} + payload := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), NodeID: c["node_id"], CredentialVersion: 1, Component: "runner", Generation: 1, BundleFormat: contract.BundleFormat, Sequence: 1, Ready: true, Reason: "ready", Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}} path := "/v1/nodes/" + c["node_id"] + "/status" requireStatus(t, request(t, s, "POST", path, c["token"], payload), 200) var received time.Time @@ -51,7 +51,7 @@ func TestTerminalConnectorSurvivesOnlyPendingAppCleanup(t *testing.T) { initial := readyTunnel(t, s, c) s.params.AppStopSignals = true s.configs = s.newConfigurationManager() - requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/status", c["token"], currentReport(t, s, c["node_id"], machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: initial.Generation, BundleFormat: contract.BundleFormat, Reason: "ready"})), 200) + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/status", c["token"], currentReport(t, s, c["node_id"], machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runtime", Generation: initial.Generation, BundleFormat: contract.BundleFormat, Reason: "ready"})), 200) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } @@ -61,15 +61,15 @@ func TestTerminalConnectorSurvivesOnlyPendingAppCleanup(t *testing.T) { t.Fatal(err) } if compromise != "none" { - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": compromise, "compromised": true}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": compromise, "compromised": true}), 202) } - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"epoch": c["epoch"], "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"force": true}), 202) path := "/v1/nodes/" + c["node_id"] + "/tunnel/connector-token" if compromise != "none" { requireStatus(t, request(t, s, "POST", path, c["token"], map[string]any{}), 409) } driveTunnels(t, s) - retained, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + retained, _, err := s.loadTunnel(t.Context(), c["node_id"]) if compromise != "none" { if err != nil || !retained.CleanupComplete || len(f.resources) != 0 || count(t, s, `SELECT count(*) FROM lpcc.access_credentials WHERE revoked_at IS NULL`) != 0 { t.Fatal("known compromise did not override app cleanup hold", retained, err) @@ -96,7 +96,7 @@ func TestTerminalConnectorSurvivesOnlyPendingAppCleanup(t *testing.T) { } requireStatus(t, request(t, s, "POST", path, c["token"], map[string]any{}), 401) driveTunnels(t, s) - final, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + final, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil || !final.CleanupComplete || len(f.resources) != 0 { t.Fatal("provider cleanup failed after receipts", final, err) } @@ -112,7 +112,7 @@ func TestManagementSurvivesUnsupportedAppRendering(t *testing.T) { if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - supported := machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "ready"} + supported := machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "ready"} requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/status", c["token"], currentReport(t, s, c["node_id"], supported)), 200) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) @@ -149,23 +149,23 @@ func TestMaintenanceAdmissionFreezeEndsOnlyAtActualTarget(t *testing.T) { if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - runtime := machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "ready"} + runtime := machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "ready"} path := "/v1/nodes/" + c["node_id"] + "/status" requireStatus(t, request(t, s, "POST", path, c["token"], currentReport(t, s, c["node_id"], runtime)), 200) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - state, err := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"], c["epoch"]) + state, err := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"]) if err != nil { t.Fatal(err) } now := time.Now().UTC() - drain := machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runner", Generation: state.Generation, BundleFormat: contract.BundleFormat, Sequence: 1, Drained: true, Reason: "drain_pending", Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}, Evidence: &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(c["node_id"], c["epoch"], state.State), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)}} + drain := machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runner", Generation: state.Generation, BundleFormat: contract.BundleFormat, Sequence: 1, Drained: true, Reason: "drain_pending", Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}, Evidence: &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(c["node_id"], state.State), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)}} requireStatus(t, request(t, s, "POST", path, c["token"], currentReport(t, s, c["node_id"], drain)), 200) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - state, err = (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"], c["epoch"]) + state, err = (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"]) if err != nil { t.Fatal(err) } @@ -180,7 +180,7 @@ func TestMaintenanceAdmissionFreezeEndsOnlyAtActualTarget(t *testing.T) { if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - pending, _ := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"], c["epoch"]) + pending, _ := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"]) if !pending.DrainRequested { t.Fatal("unobserved K3s target reopened admission") } @@ -189,7 +189,7 @@ func TestMaintenanceAdmissionFreezeEndsOnlyAtActualTarget(t *testing.T) { if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - complete, _ := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"], c["epoch"]) + complete, _ := (machineconfig.Store{DB: s.db}).Load(t.Context(), c["node_id"]) if complete.DrainRequested || complete.ApplyingConfigDigest != "" { t.Fatal("verified actual target did not release admission", complete.State) } diff --git a/api/internal/controlplane/assignments.go b/api/internal/controlplane/assignments.go index f26f95f..2694c7a 100644 --- a/api/internal/controlplane/assignments.go +++ b/api/internal/controlplane/assignments.go @@ -36,7 +36,6 @@ func appConflict() error { } type assignmentInput struct { - Epoch string `json:"epoch"` Digest string `json:"digest"` Expected *int64 `json:"expected_generation"` Replicas *int `json:"replicas"` @@ -50,29 +49,26 @@ type assignmentInput struct { // Lock the live enrollment before state/history, shared with configuration // publication and credential changes. The policy lock is already held. -func lockAppMachine(ctx context.Context, tx *sql.Tx, node, epoch string) (string, error) { - var current string - err := tx.QueryRowContext(ctx, `SELECT enrollment_epoch::text FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(¤t) +func lockAppMachine(ctx context.Context, tx *sql.Tx, node string) (string, error) { + var present int + err := tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&present) if errors.Is(err, sql.ErrNoRows) { return "", problem(404, "machine_not_found", "Machine not found.") } if err != nil { return "", err } - if current != epoch { - return "", problem(409, "epoch_changed", "Machine enrollment changed.") - } - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_states(node_id,epoch,state) VALUES($1,$2,'{}') ON CONFLICT DO NOTHING`, node, epoch) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_states(node_id,state) VALUES($1,'{}') ON CONFLICT DO NOTHING`, node) if err != nil { return "", err } var lifecycle string - err = tx.QueryRowContext(ctx, `SELECT rollout->>'lifecycle' FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 FOR UPDATE`, node, epoch).Scan(&lifecycle) + err = tx.QueryRowContext(ctx, `SELECT rollout->>'lifecycle' FROM lpcc.machine_states WHERE node_id=$1 FOR UPDATE`, node).Scan(&lifecycle) return lifecycle, err } -func optionalHead(ctx context.Context, q machineapps.Querier, node, epoch, id string) (machineapps.Version, error) { - v, err := machineapps.Head(ctx, q, node, epoch, id) +func optionalHead(ctx context.Context, q machineapps.Querier, node, id string) (machineapps.Version, error) { + v, err := machineapps.Head(ctx, q, node, id) if errors.Is(err, sql.ErrNoRows) { return machineapps.Version{}, nil } @@ -103,21 +99,21 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, } node, id, method := r.PathValue("node_id"), r.PathValue("revision_id"), r.Method replace := method == "POST" - if !appID(in.Epoch) || !appID(id) || in.Expected == nil || *in.Expected < 0 || *in.Expected == math.MaxInt64 || (!replace && in.Target != nil) || (method == "DELETE" && (in.Digest != "" || in.Replicas != nil)) { - return nil, problem(400, "invalid_precondition", "Provide an enrollment epoch, revision UUID and expected_generation.") + if !appID(id) || in.Expected == nil || *in.Expected < 0 || *in.Expected == math.MaxInt64 || (!replace && in.Target != nil) || (method == "DELETE" && (in.Digest != "" || in.Replicas != nil)) { + return nil, problem(400, "invalid_precondition", "Provide a revision UUID and expected_generation.") } if replace && (in.Digest != "" || in.Replicas != nil || in.Target == nil || !appID(in.Target.RevisionID) || in.Target.RevisionID == id || in.Target.Expected == nil || *in.Target.Expected < 0 || *in.Target.Expected == math.MaxInt64) { return nil, problem(400, "invalid_replacement", "Provide a distinct target revision and its expected_generation.") } return func(ctx context.Context, tx *sql.Tx, u UserIdentity) (AdminChange, error) { - lifecycle, err := lockAppMachine(ctx, tx, node, in.Epoch) + lifecycle, err := lockAppMachine(ctx, tx, node) if err != nil { return AdminChange{}, err } if lifecycle != "active" { return AdminChange{}, problem(409, "machine_inactive", "Machine removal is in progress.") } - old, err := optionalHead(ctx, tx, node, in.Epoch, id) + old, err := optionalHead(ctx, tx, node, id) if err != nil { return AdminChange{}, err } @@ -133,7 +129,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, } if replace { if old.Replacement != nil { - done, e := machineapps.CleanupComplete(ctx, tx, node, in.Epoch, schema.AppStartAfter{RevisionID: old.Replacement.RevisionID, Generation: old.Replacement.Generation}) + done, e := machineapps.CleanupComplete(ctx, tx, node, schema.AppStartAfter{RevisionID: old.Replacement.RevisionID, Generation: old.Replacement.Generation}) if e != nil { return AdminChange{}, e } @@ -142,7 +138,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, } } if old.StartAfter != nil { - done, e := machineapps.CleanupComplete(ctx, tx, node, in.Epoch, *old.StartAfter) + done, e := machineapps.CleanupComplete(ctx, tx, node, *old.StartAfter) if e != nil { return AdminChange{}, e } @@ -152,7 +148,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, } targetID := in.Target.RevisionID affected = append(affected, targetID) - target, e := optionalHead(ctx, tx, node, in.Epoch, targetID) + target, e := optionalHead(ctx, tx, node, targetID) if e != nil { return AdminChange{}, e } @@ -201,8 +197,8 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, a.StartAllowed = true a.Replacement = &schema.AppReplacement{RevisionID: id, ActivationGeneration: old.ActivationGeneration, Generation: removal.Generation, Replicas: n} } - if e = machineapps.Append(ctx, tx, node, in.Epoch, u.ID, removal); e == nil { - e = machineapps.Append(ctx, tx, node, in.Epoch, u.ID, a) + if e = machineapps.Append(ctx, tx, node, u.ID, removal); e == nil { + e = machineapps.Append(ctx, tx, node, u.ID, a) } if e != nil { return AdminChange{}, e @@ -218,7 +214,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if old.Generation != *in.Expected { return AdminChange{}, appConflict() } - if err = machineapps.Append(ctx, tx, node, in.Epoch, u.ID, removal); err != nil { + if err = machineapps.Append(ctx, tx, node, u.ID, removal); err != nil { return AdminChange{}, err } changed = true @@ -239,7 +235,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, } base = machineapps.Version{} if *in.Expected > 0 { - base, e = machineapps.AtGeneration(ctx, tx, node, in.Epoch, id, *in.Expected) + base, e = machineapps.AtGeneration(ctx, tx, node, id, *in.Expected) if e != nil { return AdminChange{}, e } @@ -260,7 +256,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, a.ActivationGeneration = base.ActivationGeneration a.Replacement = base.Replacement if base.Replacement != nil && n != base.Replicas { - done, e := machineapps.CleanupComplete(ctx, tx, node, in.Epoch, schema.AppStartAfter{RevisionID: base.Replacement.RevisionID, Generation: base.Replacement.Generation}) + done, e := machineapps.CleanupComplete(ctx, tx, node, schema.AppStartAfter{RevisionID: base.Replacement.RevisionID, Generation: base.Replacement.Generation}) if e != nil { return AdminChange{}, e } @@ -287,17 +283,17 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if _, e = revisionForBinding(ctx, tx, current, ref, node); e != nil { return AdminChange{}, e } - if e = machineapps.Append(ctx, tx, node, in.Epoch, u.ID, a); e != nil { + if e = machineapps.Append(ctx, tx, node, u.ID, a); e != nil { return AdminChange{}, e } changed = true } } if changed { - if err = machineapps.Bump(ctx, tx, node, in.Epoch); err != nil { + if err = machineapps.Bump(ctx, tx, node); err != nil { return AdminChange{}, err } - set, e := machineapps.Snapshot(ctx, tx, node, in.Epoch) + set, e := machineapps.Snapshot(ctx, tx, node) if e != nil { return AdminChange{}, e } @@ -308,12 +304,12 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, sort.Strings(affected) versions := []machineapps.Version{} for _, key := range affected { - v, e := machineapps.Head(ctx, tx, node, in.Epoch, key) + v, e := machineapps.Head(ctx, tx, node, key) if e != nil { return AdminChange{}, e } if v.StartAfter != nil { - v.StartAllowed, e = machineapps.CleanupComplete(ctx, tx, node, in.Epoch, *v.StartAfter) + v.StartAllowed, e = machineapps.CleanupComplete(ctx, tx, node, *v.StartAfter) if e != nil { return AdminChange{}, e } @@ -337,16 +333,15 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if changed { status = 202 } - return AdminChange{Target: AdminTarget{Kind: "machine_app", ID: node + ":" + in.Epoch + ":" + id, Revision: auditRevision}, Changed: changed, Status: status, Body: map[string]any{"changed": changed, "epoch": in.Epoch, "assignments": versions}}, nil + return AdminChange{Target: AdminTarget{Kind: "machine_app", ID: node + ":" + node + ":" + id, Revision: auditRevision}, Changed: changed, Status: status, Body: map[string]any{"changed": changed, "node_id": node, "assignments": versions}}, nil }, nil } func (s *Server) listAssignments(w http.ResponseWriter, r *http.Request, _ UserIdentity) { ctx := r.Context() node := r.PathValue("node_id") - var epoch string var last *time.Time - err := s.db.QueryRowContext(ctx, `SELECT enrollment_epoch::text,last_config_fetch_at FROM lpcc.machines WHERE node_id=$1`, node).Scan(&epoch, &last) + err := s.db.QueryRowContext(ctx, `SELECT last_config_fetch_at FROM lpcc.machines WHERE node_id=$1`, node).Scan(&last) if errors.Is(err, sql.ErrNoRows) { err = problem(404, "machine_not_found", "Machine not found.") } @@ -365,7 +360,7 @@ func (s *Server) listAssignments(w http.ResponseWriter, r *http.Request, _ UserI return } // Read all current heads through a bounded database page, including completed history. - rows, err := s.db.QueryContext(ctx, `SELECT `+machineapps.VersionColumns+` FROM lpcc.machine_app_heads v `+machineapps.VersionJoins+` WHERE v.node_id=$1 AND v.epoch=$2 AND ($3='' OR v.revision_id::text>$3) ORDER BY v.revision_id LIMIT $4`, node, epoch, after, limit+1) + rows, err := s.db.QueryContext(ctx, `SELECT `+machineapps.VersionColumns+` FROM lpcc.machine_app_heads v `+machineapps.VersionJoins+` WHERE v.node_id=$1 AND ($2='' OR v.revision_id::text>$2) ORDER BY v.revision_id LIMIT $3`, node, after, limit+1) if err != nil { s.respondError(w, err) return @@ -377,7 +372,7 @@ func (s *Server) listAssignments(w http.ResponseWriter, r *http.Request, _ UserI } for i := range versions { if versions[i].StartAfter != nil { - versions[i].StartAllowed, err = machineapps.CleanupComplete(ctx, s.db, node, epoch, *versions[i].StartAfter) + versions[i].StartAllowed, err = machineapps.CleanupComplete(ctx, s.db, node, *versions[i].StartAfter) if err != nil { s.respondError(w, err) return @@ -391,12 +386,12 @@ func (s *Server) listAssignments(w http.ResponseWriter, r *http.Request, _ UserI } var gen, published int64 var failure *string - err = s.db.QueryRowContext(ctx, `SELECT COALESCE((SELECT apps_generation FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2),0),COALESCE((SELECT max(apps_generation) FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2),0),(SELECT apps_error FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2)`, node, epoch).Scan(&gen, &published, &failure) + err = s.db.QueryRowContext(ctx, `SELECT COALESCE((SELECT apps_generation FROM lpcc.machine_states WHERE node_id=$1),0),COALESCE((SELECT max(apps_generation) FROM lpcc.machine_app_deliveries WHERE node_id=$1),0),(SELECT apps_error FROM lpcc.machine_states WHERE node_id=$1)`, node).Scan(&gen, &published, &failure) if err != nil { s.respondError(w, err) return } - respond(w, 200, map[string]any{"epoch": epoch, "assignments": versions, "apps_generation": gen, "published_generation": published, "delivery_error": failure, "last_config_fetch_at": last, "next_after_revision_id": next}) + respond(w, 200, map[string]any{"assignments": versions, "apps_generation": gen, "published_generation": published, "delivery_error": failure, "last_config_fetch_at": last, "next_after_revision_id": next}) } func (s *Server) inspectAssignment(w http.ResponseWriter, r *http.Request, _ UserIdentity) { @@ -406,23 +401,7 @@ func (s *Server) inspectAssignment(w http.ResponseWriter, r *http.Request, _ Use s.respondError(w, problem(400, "invalid_revision_id", "Provide a revision UUID.")) return } - var epoch string - // Explicit retained epoch permits administrators to inspect deleted-enrollment history. - epoch = r.URL.Query().Get("epoch") - var err error - if epoch == "" { - err = s.db.QueryRowContext(ctx, `SELECT enrollment_epoch::text FROM lpcc.machines WHERE node_id=$1`, node).Scan(&epoch) - } else if !appID(epoch) { - err = problem(400, "invalid_epoch", "Provide an enrollment UUID.") - } - if errors.Is(err, sql.ErrNoRows) { - err = problem(404, "machine_not_found", "Machine not found.") - } - if err != nil { - s.respondError(w, err) - return - } - head, err := machineapps.Head(ctx, s.db, node, epoch, id) + head, err := machineapps.Head(ctx, s.db, node, id) if errors.Is(err, sql.ErrNoRows) { err = problem(404, "assignment_not_found", "Assignment not found.") } @@ -431,7 +410,7 @@ func (s *Server) inspectAssignment(w http.ResponseWriter, r *http.Request, _ Use return } if head.StartAfter != nil { - head.StartAllowed, err = machineapps.CleanupComplete(ctx, s.db, node, epoch, *head.StartAfter) + head.StartAllowed, err = machineapps.CleanupComplete(ctx, s.db, node, *head.StartAfter) if err != nil { s.respondError(w, err) return @@ -455,7 +434,7 @@ func (s *Server) inspectAssignment(w http.ResponseWriter, r *http.Request, _ Use return } } - rows, err := s.db.QueryContext(ctx, `SELECT `+machineapps.VersionColumns+` FROM lpcc.machine_app_versions v `+machineapps.VersionJoins+` WHERE v.node_id=$1 AND v.epoch=$2 AND v.revision_id=$3 AND v.generation<$4 ORDER BY v.generation DESC LIMIT $5`, node, epoch, id, before, limit+1) + rows, err := s.db.QueryContext(ctx, `SELECT `+machineapps.VersionColumns+` FROM lpcc.machine_app_versions v `+machineapps.VersionJoins+` WHERE v.node_id=$1 AND v.revision_id=$2 AND v.generation<$3 ORDER BY v.generation DESC LIMIT $4`, node, id, before, limit+1) if err != nil { s.respondError(w, err) return @@ -470,11 +449,11 @@ func (s *Server) inspectAssignment(w http.ResponseWriter, r *http.Request, _ Use history = history[:limit] next = &history[len(history)-1].Generation } - respond(w, 200, map[string]any{"epoch": epoch, "assignment": head, "revision": revision, "history": history, "next_before_generation": next}) + respond(w, 200, map[string]any{"assignment": head, "revision": revision, "history": history, "next_before_generation": next}) } type assignmentReport struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Generation int64 `json:"generation"` ActivationGeneration int64 `json:"activation_generation"` @@ -495,7 +474,7 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { return } id := r.PathValue("revision_id") - if !appID(id) || report.Epoch != m.Epoch || report.CredentialVersion != m.CredentialVersion || report.Generation < 1 || report.ActivationGeneration < 1 || !digestRefPattern(report.AppsDigest) || (report.Phase != "applied" && report.Phase != "failed" && report.Phase != "removed") { + if !appID(id) || report.NodeID != m.NodeID || report.CredentialVersion != m.CredentialVersion || report.Generation < 1 || report.ActivationGeneration < 1 || !digestRefPattern(report.AppsDigest) || (report.Phase != "applied" && report.Phase != "failed" && report.Phase != "removed") { s.respondError(w, problem(409, "invalid_app_status", "Status does not match an enrolled assignment.")) return } @@ -511,17 +490,17 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { return } defer tx.Rollback() - // Live publication locks the machine first; old terminal epochs lock only - // their retained enrollment and cannot block or mutate a new epoch's intents. + // Live publication locks the machine first; retired nodes lock only + // their retained enrollment and cannot block or mutate a replacement node's intents. var present int - err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 FOR UPDATE`, m.NodeID, m.Epoch).Scan(&present) + err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, m.NodeID).Scan(&present) if err != nil && !errors.Is(err, sql.ErrNoRows) { s.respondError(w, err) return } var version int64 var terminal bool - err = tx.QueryRowContext(ctx, `SELECT credential_version,retired_at IS NOT NULL FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2 FOR NO KEY UPDATE`, m.NodeID, m.Epoch).Scan(&version, &terminal) + err = tx.QueryRowContext(ctx, `SELECT credential_version,retired_at IS NOT NULL FROM lpcc.enrollments WHERE node_id=$1 FOR NO KEY UPDATE`, m.NodeID).Scan(&version, &terminal) if err != nil { s.respondError(w, err) return @@ -531,7 +510,7 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { return } var receiptDigest string - err = tx.QueryRowContext(ctx, `SELECT apps_digest FROM lpcc.machine_app_completions WHERE node_id=$1 AND epoch=$2 AND revision_id=$3 AND generation=$4 AND activation_generation=$5 AND phase=$6`, m.NodeID, m.Epoch, id, report.Generation, report.ActivationGeneration, report.Phase).Scan(&receiptDigest) + err = tx.QueryRowContext(ctx, `SELECT apps_digest FROM lpcc.machine_app_completions WHERE node_id=$1 AND revision_id=$2 AND generation=$3 AND activation_generation=$4 AND phase=$5`, m.NodeID, id, report.Generation, report.ActivationGeneration, report.Phase).Scan(&receiptDigest) recorded := err == nil if err != nil && !errors.Is(err, sql.ErrNoRows) { s.respondError(w, err) @@ -546,7 +525,7 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { return } var membership []byte - err = tx.QueryRowContext(ctx, `SELECT entries FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND apps_digest=$3 AND (NOT $4 OR terminal) LIMIT 1`, m.NodeID, m.Epoch, report.AppsDigest, m.Terminal && !recorded).Scan(&membership) + err = tx.QueryRowContext(ctx, `SELECT entries FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND apps_digest=$2 AND (NOT $3 OR terminal) LIMIT 1`, m.NodeID, report.AppsDigest, m.Terminal && !recorded).Scan(&membership) if errors.Is(err, sql.ErrNoRows) { err = problem(409, "unknown_delivery", "Status must refer to a published app configuration.") } @@ -575,7 +554,7 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { respond(w, 200, map[string]string{"status": "already_recorded"}) return } - head, err := machineapps.Head(ctx, tx, m.NodeID, m.Epoch, id) + head, err := machineapps.Head(ctx, tx, m.NodeID, id) if err != nil { s.respondError(w, err) return @@ -589,11 +568,11 @@ func (s *Server) assignmentStatus(w http.ResponseWriter, r *http.Request) { return } if report.Phase == "failed" { - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_diagnostics(node_id,epoch,revision_id,generation,reason) VALUES($1,$2,$3,$4,$5) ON CONFLICT(node_id,epoch,revision_id) DO UPDATE SET generation=EXCLUDED.generation,reason=EXCLUDED.reason,received_at=now() WHERE lpcc.machine_app_diagnostics.generation<=EXCLUDED.generation`, m.NodeID, m.Epoch, id, report.Generation, report.Reason) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_diagnostics(node_id,revision_id,generation,reason) VALUES($1,$2,$3,$4) ON CONFLICT(node_id,revision_id) DO UPDATE SET generation=EXCLUDED.generation,reason=EXCLUDED.reason,received_at=now() WHERE lpcc.machine_app_diagnostics.generation<=EXCLUDED.generation`, m.NodeID, id, report.Generation, report.Reason) } else { - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_completions(node_id,epoch,revision_id,generation,activation_generation,phase,apps_digest) VALUES($1,$2,$3,$4,$5,$6,$7)`, m.NodeID, m.Epoch, id, report.Generation, report.ActivationGeneration, report.Phase, report.AppsDigest) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_completions(node_id,revision_id,generation,activation_generation,phase,apps_digest) VALUES($1,$2,$3,$4,$5,$6)`, m.NodeID, id, report.Generation, report.ActivationGeneration, report.Phase, report.AppsDigest) if err == nil && report.Phase == "removed" && !m.Terminal { - err = machineapps.Bump(ctx, tx, m.NodeID, m.Epoch) + err = machineapps.Bump(ctx, tx, m.NodeID) } } if err == nil { diff --git a/api/internal/controlplane/assignments_test.go b/api/internal/controlplane/assignments_test.go index aeb56ca..69e14df 100644 --- a/api/internal/controlplane/assignments_test.go +++ b/api/internal/controlplane/assignments_test.go @@ -29,7 +29,7 @@ func appPath(c map[string]string, r CatalogRevision) string { } func putApp(t *testing.T, s *Server, c map[string]string, r CatalogRevision, g int64, n int) *httptest.ResponseRecorder { t.Helper() - return request(t, s, "PUT", appPath(c, r), "session-a", map[string]any{"epoch": c["epoch"], "digest": r.Digest, "expected_generation": g, "replicas": n}) + return request(t, s, "PUT", appPath(c, r), "session-a", map[string]any{"digest": r.Digest, "expected_generation": g, "replicas": n}) } func appBundle(t *testing.T, s *Server, c map[string]string) (schema.AppAssignmentSetV1, string, map[string]string) { t.Helper() @@ -55,7 +55,7 @@ func appReport(t *testing.T, s *Server, c map[string]string, a schema.AppAssignm if phase == "failed" { reason = "reconcile_failed" } - return request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/apps/"+a.RevisionID+"/status", c["token"], assignmentReport{Epoch: c["epoch"], CredentialVersion: 1, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: phase, Reason: reason}) + return request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/apps/"+a.RevisionID+"/status", c["token"], assignmentReport{NodeID: c["node_id"], CredentialVersion: 1, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: phase, Reason: reason}) } func findApp(t *testing.T, set schema.AppAssignmentSetV1, id string) schema.AppAssignment { t.Helper() @@ -101,12 +101,12 @@ func TestMachineAssignmentsDeliveryAndSequentialReplacement(t *testing.T) { } beta := publishAssignmentRevision(t, s, strings.Replace(registryFixture(t), `name = "whoami"`, `name = "beta"`, 1), "") requireStatus(t, putApp(t, s, c, beta, 0, 1), 202) - replace := map[string]any{"epoch": c["epoch"], "expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0, "replicas": 3}} + replace := map[string]any{"expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0, "replicas": 3}} requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", replace), 202) requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", replace), 200) - implicitRetry := map[string]any{"epoch": c["epoch"], "expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0}} + implicitRetry := map[string]any{"expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0}} requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", implicitRetry), 409) - currentReplacement := map[string]any{"epoch": c["epoch"], "expected_generation": 2, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 1}} + currentReplacement := map[string]any{"expected_generation": 2, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 1}} auditsBeforeNoop := count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events`) requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", currentReplacement), 200) if count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events`) != auditsBeforeNoop { @@ -138,7 +138,7 @@ func TestMachineAssignmentsDeliveryAndSequentialReplacement(t *testing.T) { requireStatus(t, appReport(t, s, c, source, blockedDigest, "removed"), 200) requireStatus(t, putApp(t, s, c, r, 3, 3), 202) requireStatus(t, putApp(t, s, c, r, 3, 3), 200) - head, err := machineapps.Head(t.Context(), s.db, c["node_id"], c["epoch"], r.RevisionID) + head, err := machineapps.Head(t.Context(), s.db, c["node_id"], r.RevisionID) if err != nil || head.Generation != 4 || head.ActivationGeneration != 3 { t.Fatal(head, err) } @@ -157,14 +157,14 @@ func TestMachineAssignmentsDeliveryAndSequentialReplacement(t *testing.T) { if err := json.Unmarshal(listing.Body.Bytes(), &page); err != nil || len(page.Assignments) != 1 || page.Next == nil { t.Fatal("assignment pagination", err, listing.Body.String()) } - requireStatus(t, request(t, s, "GET", appPath(c, r)+"?epoch=bad", "session-a", nil), 400) + requireStatus(t, request(t, s, "GET", appPath(c, r)+"?before_generation=bad", "session-a", nil), 400) } func TestAssignmentAuthorizationPolicyAndInvalidChanges(t *testing.T) { s := newTestServer(t) grant := adminA(t, s) c := enroll(t, s, ownerB, strings.Repeat("c", 64)) r := publishAssignmentRevision(t, s, registryFixture(t), "") - body := map[string]any{"epoch": c["epoch"], "digest": r.Digest, "expected_generation": 0} + body := map[string]any{"digest": r.Digest, "expected_generation": 0} for _, token := range []string{"", "invalid", c["token"]} { requireStatus(t, request(t, s, "PUT", appPath(c, r), token, body), 401) } @@ -179,7 +179,7 @@ func TestAssignmentAuthorizationPolicyAndInvalidChanges(t *testing.T) { requireStatus(t, putApp(t, s, c, r, 1, 2), 202) set, digest, _ := appBundle(t, s, c) a := findApp(t, set, r.RevisionID) - requireStatus(t, request(t, s, "DELETE", appPath(c, r), "session-a", map[string]any{"epoch": c["epoch"], "expected_generation": 2}), 202) + requireStatus(t, request(t, s, "DELETE", appPath(c, r), "session-a", map[string]any{"expected_generation": 2}), 202) set, digest, _ = appBundle(t, s, c) a = findApp(t, set, r.RevisionID) requireStatus(t, appReport(t, s, c, a, digest, "removed"), 200) @@ -234,7 +234,7 @@ func TestMachineRemovalWaitsForAppsAndRetainsTerminalCleanup(t *testing.T) { if mode == "owner-delete" { execSQL(t, s.db, `DELETE FROM auth.users WHERE id=$1`, ownerB) } else { - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"epoch": c["epoch"], "force": mode == "forced"}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"force": mode == "forced"}), 202) } if mode == "normal" { reportRuntime(t, s, c, "runner", true) @@ -253,7 +253,7 @@ func TestMachineRemovalWaitsForAppsAndRetainsTerminalCleanup(t *testing.T) { // Cleanup outlasts both the Node deadline and the runner report TTL. execSQL(t, s.db, `UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{drain_started_at}',to_jsonb($1::text))`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano)) execSQL(t, s.db, `UPDATE lpcc.machine_reports SET received_at=now()-interval '1 hour'`) - head, err := machineapps.Head(t.Context(), s.db, c["node_id"], c["epoch"], r.RevisionID) + head, err := machineapps.Head(t.Context(), s.db, c["node_id"], r.RevisionID) if err != nil || head.Revision != nil || head.AppName != "whoami" || head.RevisionNumber != 1 { t.Fatal("compact removal lost administrative identity", head, err) } @@ -324,7 +324,7 @@ func TestAssignmentSizeAdmissionStillAllowsRemoval(t *testing.T) { t.Fatal("oversized intent persisted") } appBundle(t, s, c) - requireStatus(t, request(t, s, "DELETE", appPath(c, first), "session-a", map[string]any{"epoch": c["epoch"], "expected_generation": 1}), 202) + requireStatus(t, request(t, s, "DELETE", appPath(c, first), "session-a", map[string]any{"expected_generation": 1}), 202) set, _, _ := appBundle(t, s, c) if findApp(t, set, first.RevisionID).Desired != "absent" { t.Fatal("removal failed at boundary") @@ -338,18 +338,18 @@ func TestAssignmentTerminalCleanupCannotAffectReenrollment(t *testing.T) { r := publishAssignmentRevision(t, s, registryFixture(t), "") requireStatus(t, putApp(t, s, old, r, 0, 1), 202) appBundle(t, s, old) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+old["node_id"], "session-a", map[string]any{"epoch": old["epoch"], "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+old["node_id"], "session-a", map[string]any{"force": true}), 202) terminal, oldDigest, _ := appBundle(t, s, old) removal := terminal.Entries[0] fresh := enroll(t, s, ownerA, fingerprint) - if old["epoch"] == fresh["epoch"] { - t.Fatal("epoch reused") + if old["node_id"] == fresh["node_id"] { + t.Fatal("node reused") } requireStatus(t, putApp(t, s, fresh, r, 0, 1), 202) appBundle(t, s, fresh) requireStatus(t, appReport(t, s, old, removal, oldDigest, "removed"), 200) requireStatus(t, appReport(t, s, old, removal, oldDigest, "removed"), 200) - head, err := machineapps.Head(t.Context(), s.db, fresh["node_id"], fresh["epoch"], r.RevisionID) + head, err := machineapps.Head(t.Context(), s.db, fresh["node_id"], r.RevisionID) if err != nil || head.CompletedAt != nil || head.Generation != 1 { t.Fatal("old cleanup modified new assignment", head, err) } @@ -362,7 +362,7 @@ func TestAssignmentsPreserveTunnelReadiness(t *testing.T) { r := publishAssignmentRevision(t, s, registryFixture(t), "") requireStatus(t, putApp(t, s, c, r, 0, 2), 202) _, _, files := appBundle(t, s, c) - after, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + after, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil || !after.Ready || after.Generation != ready.Generation || after.SourceGeneration != ready.SourceGeneration { t.Fatal("app assignment invalidated tunnel", after, err) } @@ -382,22 +382,22 @@ func TestAssignmentBlockedTargetEditsAndCancellation(t *testing.T) { r := publishAssignmentRevision(t, s, registryFixture(t), "") next := publishAssignmentRevision(t, s, strings.Replace(registryFixture(t), `app_version = "1"`, `app_version = "2"`, 1), r.RevisionID) requireStatus(t, putApp(t, s, c, r, 0, 1), 202) - replace := map[string]any{"epoch": c["epoch"], "expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0}} + replace := map[string]any{"expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0}} requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", replace), 202) - requireStatus(t, request(t, s, "PUT", appPath(c, next), "session-a", map[string]any{"epoch": c["epoch"], "digest": next.Digest, "expected_generation": 0}), 409) + requireStatus(t, request(t, s, "PUT", appPath(c, next), "session-a", map[string]any{"digest": next.Digest, "expected_generation": 0}), 409) requireStatus(t, putApp(t, s, c, next, 1, 3), 202) - impossibleRetry := map[string]any{"epoch": c["epoch"], "expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 1, "replicas": 3}} + impossibleRetry := map[string]any{"expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 1, "replicas": 3}} requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", impossibleRetry), 409) - currentNoop := map[string]any{"epoch": c["epoch"], "expected_generation": 2, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 2}} + currentNoop := map[string]any{"expected_generation": 2, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 2}} requireStatus(t, request(t, s, "POST", appPath(c, r)+"/replace", "session-a", currentNoop), 200) set, digest, _ := appBundle(t, s, c) target := findApp(t, set, next.RevisionID) if target.StartAllowed || target.StartAfter == nil || target.Generation != 2 || target.ActivationGeneration != 1 { t.Fatal("replica edit cleared prerequisite") } - chain := map[string]any{"epoch": c["epoch"], "expected_generation": 2, "target": map[string]any{"revision_id": r.RevisionID, "digest": r.Digest, "expected_generation": 2}} + chain := map[string]any{"expected_generation": 2, "target": map[string]any{"revision_id": r.RevisionID, "digest": r.Digest, "expected_generation": 2}} requireStatus(t, request(t, s, "POST", appPath(c, next)+"/replace", "session-a", chain), 409) - requireStatus(t, request(t, s, "DELETE", appPath(c, next), "session-a", map[string]any{"epoch": c["epoch"], "expected_generation": 2}), 202) + requireStatus(t, request(t, s, "DELETE", appPath(c, next), "session-a", map[string]any{"expected_generation": 2}), 202) set, digest, _ = appBundle(t, s, c) requireStatus(t, appReport(t, s, c, findApp(t, set, r.RevisionID), digest, "removed"), 200) requireStatus(t, appReport(t, s, c, findApp(t, set, next.RevisionID), digest, "removed"), 200) @@ -413,7 +413,7 @@ func TestAssignmentOmittedReplicasUseExpectedIntent(t *testing.T) { c := enroll(t, s, ownerA, fmt.Sprintf("%064x", 41)) r := publishAssignmentRevision(t, s, registryFixture(t), "") implicit := func(expected int64) *httptest.ResponseRecorder { - return request(t, s, "PUT", appPath(c, r), "session-a", map[string]any{"epoch": c["epoch"], "digest": r.Digest, "expected_generation": expected}) + return request(t, s, "PUT", appPath(c, r), "session-a", map[string]any{"digest": r.Digest, "expected_generation": expected}) } requireStatus(t, putApp(t, s, c, r, 0, 3), 202) requireStatus(t, implicit(0), 409) // Creation requested the definition default, two. @@ -423,7 +423,7 @@ func TestAssignmentOmittedReplicasUseExpectedIntent(t *testing.T) { requireStatus(t, implicit(1), 409) // A stale omission retains the expected version's three. requireStatus(t, putApp(t, s, c, r, 1, 4), 200) requireStatus(t, implicit(2), 200) - head, err := machineapps.Head(t.Context(), s.db, c["node_id"], c["epoch"], r.RevisionID) + head, err := machineapps.Head(t.Context(), s.db, c["node_id"], r.RevisionID) if err != nil || head.Generation != 2 || head.Replicas != 4 || head.ActivationGeneration != 1 { t.Fatal(head, err) } @@ -442,7 +442,7 @@ func TestAssignmentCompletionRetriesSurviveRetirementAndDeliveryChanges(t *testi requireStatus(t, putApp(t, s, c, beta, 0, 1), 202) _, secondDigest, _ := appBundle(t, s, c) requireStatus(t, appReport(t, s, c, applied, secondDigest, "applied"), 200) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"epoch": c["epoch"], "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"force": true}), 202) terminal, terminalDigest, _ := appBundle(t, s, c) for _, digest := range []string{firstDigest, secondDigest} { requireStatus(t, appReport(t, s, c, applied, digest, "applied"), 200) @@ -473,16 +473,16 @@ func TestAssignmentReportValidationAndProviderBackoff(t *testing.T) { reasons[2] = "" } for _, reason := range reasons { - report := assignmentReport{Epoch: c["epoch"], CredentialVersion: 1, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: phase, Reason: reason} + report := assignmentReport{NodeID: c["node_id"], CredentialVersion: 1, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: phase, Reason: reason} path := "/v1/nodes/" + c["node_id"] + "/apps/" + r.RevisionID + "/status" requireStatus(t, request(t, s, "POST", path, c["token"], report), 400) } } - wrongVersion := assignmentReport{Epoch: c["epoch"], CredentialVersion: 2, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: "applied"} + wrongVersion := assignmentReport{NodeID: c["node_id"], CredentialVersion: 2, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, AppsDigest: digest, Phase: "applied"} requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/apps/"+r.RevisionID+"/status", c["token"], wrongVersion), 409) requireStatus(t, appReport(t, s, c, a, digest, "failed"), 200) requireStatus(t, appReport(t, s, c, a, digest, "applied"), 200) - requireStatus(t, request(t, s, "DELETE", appPath(c, r), "session-a", map[string]any{"epoch": c["epoch"], "expected_generation": 1}), 202) + requireStatus(t, request(t, s, "DELETE", appPath(c, r), "session-a", map[string]any{"expected_generation": 1}), 202) set, digest, _ = appBundle(t, s, c) // A provider write holds state before checking its enrollment foreign key. // The receipt must not take a conflicting enrollment key lock while waiting. @@ -503,7 +503,7 @@ func TestAssignmentReportValidationAndProviderBackoff(t *testing.T) { } time.Sleep(10 * time.Millisecond) } - if _, err := provider.Exec(`INSERT INTO lpcc.access_credentials(node_id,epoch,version,provider_id,key_id,ciphertext,expires_at) VALUES($1,$2,1,'fixture','fixture',decode('00','hex'),now()+interval '1 hour')`, c["node_id"], c["epoch"]); err != nil { + if _, err := provider.Exec(`INSERT INTO lpcc.access_credentials(node_id,version,provider_id,key_id,ciphertext,expires_at) VALUES($1,1,'fixture','fixture',decode('00','hex'),now()+interval '1 hour')`, c["node_id"]); err != nil { t.Fatal("receipt blocked credential foreign-key check", err) } if err := provider.Commit(); err != nil { @@ -541,7 +541,7 @@ func TestReplacementSelectsCleanupPolicyAndPreservesLineage(t *testing.T) { old := publishAssignmentRevision(t, s, registryFixture(t), "") requireStatus(t, putApp(t, s, c, old, 0, counts[0]), 202) next := publishAssignmentRevision(t, s, strings.Replace(registryFixture(t), `app_version = "1"`, `app_version = "2"`, 1), old.RevisionID) - body := map[string]any{"epoch": c["epoch"], "expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0, "replicas": counts[1]}} + body := map[string]any{"expected_generation": 1, "target": map[string]any{"revision_id": next.RevisionID, "digest": next.Digest, "expected_generation": 0, "replicas": counts[1]}} requireStatus(t, request(t, s, "POST", appPath(c, old)+"/replace", "session-a", body), 202) audits := count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events`) requireStatus(t, request(t, s, "POST", appPath(c, old)+"/replace", "session-a", body), 200) diff --git a/api/internal/controlplane/certificates_test.go b/api/internal/controlplane/certificates_test.go index e525403..e62f6bf 100644 --- a/api/internal/controlplane/certificates_test.go +++ b/api/internal/controlplane/certificates_test.go @@ -46,7 +46,7 @@ func (f *simulatedCloudflare) DeleteCertificate(_ context.Context, id string) er return nil } -func TestReenrollmentReplacesSuffixWithoutCrossEnrollmentCertificateDeletion(t *testing.T) { +func TestReenrollmentNamespacesIsolateCertificateCleanup(t *testing.T) { s, f := tunnelTestServer(t) fingerprint := strings.Repeat("a", 64) first := enroll(t, s, ownerA, fingerprint) @@ -58,11 +58,11 @@ func TestReenrollmentReplacesSuffixWithoutCrossEnrollmentCertificateDeletion(t * driveTunnels(t, s) second := enroll(t, s, ownerA, fingerprint) after := readyTunnel(t, s, second) - if before.EndpointSuffix == after.EndpointSuffix || before.ServiceURL == after.ServiceURL || first["epoch"] == second["epoch"] { + if before.ServiceURL == after.ServiceURL || first["node_id"] == second["node_id"] { t.Fatal("re-enrollment reused endpoint identity") } - if before.ProxyURLTemplate != after.ProxyURLTemplate { - t.Fatal("stable proxy namespace changed") + if before.ProxyURLTemplate == after.ProxyURLTemplate { + t.Fatal("replacement reused the retired proxy namespace") } if len(f.certificatePacks) != 1 || after.CertificatePackID == oldPack.ID { t.Fatal("replacement certificate not isolated") @@ -86,7 +86,7 @@ func TestDomainCertificatePrecedesDrainAndReleasesAbandonedCandidates(t *testing s.params.CloudflareBaseDomain = "replacement.example.invalid" configureTestTunnels(t, s) driveTunnels(t, s) - pending, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + pending, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil || pending.DrainRequested || pending.Target != "" || pending.ServiceURL != initial.ServiceURL || pending.ProxyURLTemplate != initial.ProxyURLTemplate { t.Fatal("certificate issuance changed endpoints or started a drain", pending, err) } @@ -98,14 +98,14 @@ func TestDomainCertificatePrecedesDrainAndReleasesAbandonedCandidates(t *testing pack.Status = "active" f.certificatePacks[pack.ID] = pack driveTunnels(t, s) - draining, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + draining, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil || !draining.DrainRequested || draining.Target == "" { t.Fatal("usable certificate did not release endpoint staging", draining, err) } s.params.CloudflareBaseDomain = "another.example.invalid" configureTestTunnels(t, s) driveTunnels(t, s) - canceled, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + canceled, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil || canceled.DrainRequested || canceled.Target != "" || canceled.HeldOrchestrator != "" || canceled.ServiceURL != initial.ServiceURL { t.Fatal("new pending certificate delayed obsolete drain cancellation", canceled, err) } diff --git a/api/internal/controlplane/controlplane_test.go b/api/internal/controlplane/controlplane_test.go index 78108cf..72542eb 100644 --- a/api/internal/controlplane/controlplane_test.go +++ b/api/internal/controlplane/controlplane_test.go @@ -5,6 +5,7 @@ import ( "bytes" "compress/gzip" "database/sql" + "encoding/base32" "encoding/json" "errors" "io" @@ -167,7 +168,7 @@ func currentReport(t *testing.T, s *Server, node string, report machineconfig.Re report.ReportVersion = 1 report.ObservedAt = time.Now().UTC() var previous uint64 - err := s.db.QueryRow(`SELECT COALESCE((report->>'sequence')::numeric,0) FROM lpcc.machine_reports WHERE node_id=$1 AND epoch::text=$2 AND component=$3`, node, report.Epoch, report.Component).Scan(&previous) + err := s.db.QueryRow(`SELECT COALESCE((report->>'sequence')::numeric,0) FROM lpcc.machine_reports WHERE node_id=$1 AND component=$2`, node, report.Component).Scan(&previous) if err != nil && !errors.Is(err, sql.ErrNoRows) { t.Fatal(err) } @@ -183,7 +184,7 @@ func credentials(t *testing.T, data []byte) map[string]string { } result := map[string]string{} var resultValue string - for _, key := range []string{"node_id", "epoch", "token", "config_url"} { + for _, key := range []string{"node_id", "node_id", "token", "config_url"} { if err := json.Unmarshal(raw[key], &resultValue); err != nil { t.Fatal(err) } @@ -233,6 +234,9 @@ func TestEnrollmentAndConfigFlow(t *testing.T) { t.Fatal(w.Code) } archiveFiles(t, w.Body.Bytes()) + if id, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(first["node_id"])); err != nil || len(id) != 16 { + t.Fatal("node ID must encode 128 random bits as unpadded base32", err) + } for session, count := range map[string]int{"session-a": 2, "session-b": 1} { w := request(t, s, "GET", "/api/machines", session, nil) if w.Code != 200 { diff --git a/api/internal/controlplane/discovery.go b/api/internal/controlplane/discovery.go index aebc092..974e3fd 100644 --- a/api/internal/controlplane/discovery.go +++ b/api/internal/controlplane/discovery.go @@ -87,7 +87,7 @@ func (s discoveryStore) Sources(ctx context.Context) ([]fleet.Source, error) { } result := make([]fleet.Source, 0, len(sources)) for _, source := range sources { - result = append(result, fleet.Source{ID: source.ID, NodeID: source.NodeID, Epoch: source.Epoch, URL: source.URL, + result = append(result, fleet.Source{NodeID: source.NodeID, URL: source.URL, ServiceURL: source.ServiceURL, ProxyURLTemplate: source.ProxyURLTemplate, AuthMode: fleet.AuthCloudflare, Lifecycle: source.Lifecycle, Ready: source.Ready, Blocked: source.Blocked, Generation: source.Generation, VerifiedGeneration: source.VerifiedGeneration, CredentialRef: source.CredentialRef, CredentialVersion: source.CredentialVersion}) @@ -102,6 +102,6 @@ func (s discoveryStore) Resolve(ctx context.Context, ref string) (fleet.Credenti return fleet.Credential{ClientID: credential.ClientID, ClientSecret: credential.ClientSecret}, nil } func (s discoveryStore) Acknowledge(ctx context.Context, source fleet.Source) error { - return s.server.tunnels.AcknowledgeDiscovery(ctx, tunnel.DiscoverySource{ID: source.ID, NodeID: source.NodeID, Epoch: source.Epoch, + return s.server.tunnels.AcknowledgeDiscovery(ctx, tunnel.DiscoverySource{NodeID: source.NodeID, URL: source.URL, Generation: source.Generation, CredentialRef: source.CredentialRef, CredentialVersion: source.CredentialVersion}) } diff --git a/api/internal/controlplane/discovery/auth.go b/api/internal/controlplane/discovery/auth.go index 50b8889..6feeb55 100644 --- a/api/internal/controlplane/discovery/auth.go +++ b/api/internal/controlplane/discovery/auth.go @@ -1,6 +1,7 @@ package discovery import ( + "bytes" "errors" "io" "net" @@ -20,39 +21,29 @@ import ( func (Credential) String() string { return "[redacted Access credential]" } func (Credential) GoString() string { return "[redacted Access credential]" } +// Each immutable authorization owns its collection confirmation and diagnostics. +// Confirmation permits retirement of an older credential; it does not version inventory. type authorization struct { - source Source - credential Credential - available bool + source Source + credential Credential + available bool + confirmed, acknowledged bool + attempt attempt } - type attempt struct { - source Source completed time.Time - before time.Time - revision uint64 outcome string status int } - type transport struct { - base http.RoundTripper - selection atomic.Pointer[authorizationSnapshot] - nextSelection atomic.Uint64 - before func(string) time.Time - mu sync.Mutex - attempts map[string]attempt -} - -type authorizationSnapshot struct { - revision uint64 - sources map[string]authorization + base http.RoundTripper + selection atomic.Pointer[authorizationSnapshot] + mu sync.Mutex } +type authorizationSnapshot struct{ sources map[string]*authorization } -func (t *transport) install(sources map[string]authorization) uint64 { - revision := t.nextSelection.Add(1) - t.selection.Store(&authorizationSnapshot{revision: revision, sources: sources}) - return revision +func (t *transport) install(sources map[string]*authorization) { + t.selection.Store(&authorizationSnapshot{sources: sources}) } // Complete, canonical endpoints are the authorization keys, not host suffixes or @@ -113,23 +104,10 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { if !ok { return nil, errors.New("discovery source is not configured") } - var before time.Time - if t.before != nil { - before = t.before(u.String()) - } finish := func(status int, outcome string) { - current := t.selection.Load() - if current == nil || !sameVersion(current.sources[u.String()].source, auth.source) { - return - } t.mu.Lock() - defer t.mu.Unlock() - if t.attempts == nil { - t.attempts = map[string]attempt{} - } - // The Collector joins each batch, including body close, before the - // next batch starts; attempts for one URL cannot finish out of order. - t.attempts[u.String()] = attempt{source: auth.source, completed: time.Now().UTC(), before: before, revision: selection.revision, status: status, outcome: outcome} + auth.attempt = attempt{completed: time.Now().UTC(), status: status, outcome: outcome} + t.mu.Unlock() } clone := req.Clone(req.Context()) if clone.Header == nil { @@ -179,21 +157,31 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { } else if resp.StatusCode != 200 { outcome = "http_error" } - resp.Body = &responseBody{ReadCloser: resp.Body, done: func() { finish(resp.StatusCode, outcome) }} + finish(resp.StatusCode, outcome) + // Confirm the exact credential against Node's bounded, decoded wire contract. + // The Collector still owns its snapshots and failure policy. Re-reading these + // bounded bytes there avoids correlating transport attempts with cache timestamps. + if resp.StatusCode == http.StatusOK { + data, readErr := shared.Read(resp.Body) + resp.Body.Close() + if readErr != nil { + return nil, errors.New("invalid discovery response") + } + resp.Body = io.NopCloser(bytes.NewReader(data)) + entries, decodeErr := shared.Decode[runner](data, time.Now()) + valid := decodeErr == nil + for _, entry := range entries { + valid = valid && publicAddress(auth.source, entry.Address) + } + if valid { + t.mu.Lock() + auth.confirmed = true + t.mu.Unlock() + } + } return resp, nil } -// Collector closes the body before recording decode success. Acknowledgement -// compares the successful snapshot marker before/after this exact request; -// wall-clock ordering is deliberately not used as evidence of collection. -type responseBody struct { - io.ReadCloser - once sync.Once - done func() -} - -func (b *responseBody) Close() error { err := b.ReadCloser.Close(); b.once.Do(b.done); return err } - func (t *transport) CloseIdleConnections() { if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok { closer.CloseIdleConnections() diff --git a/api/internal/controlplane/discovery/auth_test.go b/api/internal/controlplane/discovery/auth_test.go index 59ead12..35a6476 100644 --- a/api/internal/controlplane/discovery/auth_test.go +++ b/api/internal/controlplane/discovery/auth_test.go @@ -33,7 +33,7 @@ func TestDiscoveryTransportScopeAndRequestClone(t *testing.T) { } return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("[]"))}, nil })} - selection := map[string]authorization{source.URL: {source: source, available: true, credential: credential}} + selection := map[string]*authorization{source.URL: {source: source, available: true, credential: credential}} transport.install(selection) req, _ := http.NewRequest("GET", source.URL, nil) req.Header["cf-access-client-secret"] = []string{"injected"} diff --git a/api/internal/controlplane/discovery/manager.go b/api/internal/controlplane/discovery/manager.go index 1ce0615..964e668 100644 --- a/api/internal/controlplane/discovery/manager.go +++ b/api/internal/controlplane/discovery/manager.go @@ -32,11 +32,8 @@ type Manager struct { configured []Source reconciledAt time.Time reconcileFailed bool - acknowledged map[string]bool refreshes, failures uint64 refreshDuration time.Duration - pendingRefresh map[string]uint64 - provenance map[string]snapshotProvenance } func New(config Config, deps Dependencies) (*Manager, error) { @@ -60,7 +57,7 @@ func New(config Config, deps Dependencies) (*Manager, error) { } t := &transport{base: base} f := &Manager{transport: t, backend: deps.Store, logger: logger, interval: config.RefreshInterval, - selectionInterval: config.ReconcileInterval, instanceID: uuid.New().String(), acknowledged: map[string]bool{}, pendingRefresh: map[string]uint64{}} + selectionInterval: config.ReconcileInterval, instanceID: uuid.New().String()} if own, err := url.Parse(config.OwnURL); err == nil && own.Host != "" { own.Path = "/discovery" own.RawPath = "" @@ -80,32 +77,12 @@ func New(config Config, deps Dependencies) (*Manager, error) { f.failures++ } }} - t.before = f.observation return f, nil } // Run owns the polling worker. Run once, then Close/join before discarding it. func (f *Manager) Run(ctx context.Context) { f.collector.Run(ctx, f.interval) } func (f *Manager) Close() { f.collector.Close() } -func (f *Manager) observation(endpoint string) time.Time { - f.mu.Lock() - defer f.mu.Unlock() - f.transport.mu.Lock() - defer f.transport.mu.Unlock() - for _, snapshot := range f.collector.Snapshots() { - if snapshot.URL == endpoint { - // Preserve the previous decode's provenance before a new attempt - // replaces its transport marker, even if nobody has read status. - for _, source := range f.selected { - if source.URL == endpoint { - f.snapshotCurrent(source, snapshot, f.transport.attempts[endpoint]) - } - } - return snapshot.QueriedAt - } - } - return time.Time{} -} // A raw runner preserves extension fields and the original numeric/timestamp // tokens. Node's shared codec alone validates and merges inventory records. @@ -166,7 +143,7 @@ func (r runner) DiscoveryIdentity() (string, string, string) { type publishedRunner struct { runner - sourceID string + nodeID string queriedAt time.Time } @@ -190,7 +167,7 @@ func (f *Manager) publicInventory(snapshots []shared.Snapshot[runner]) []shared. published := shared.Entry[publishedRunner]{Address: entry.Address, Runners: []publishedRunner{}} for _, candidate := range entry.Runners { if publicRunnerURL(source, candidate.URL) { - published.Runners = append(published.Runners, publishedRunner{candidate, source.ID, snapshot.QueriedAt}) + published.Runners = append(published.Runners, publishedRunner{candidate, source.NodeID, snapshot.QueriedAt}) } } entries = append(entries, published) diff --git a/api/internal/controlplane/discovery/manager_test.go b/api/internal/controlplane/discovery/manager_test.go index 55a5775..a3e3c3b 100644 --- a/api/internal/controlplane/discovery/manager_test.go +++ b/api/internal/controlplane/discovery/manager_test.go @@ -58,7 +58,7 @@ const discoveryTestRecord = `{"url":"https://orch.example/apps/a/session","app": const discoveryTestInventory = `[{"nodes":[{"url":"https://never-follow.example","queried_at":"2000-01-01T00:00:00Z"}]},{"address":"https://orch.example","runners":[` + discoveryTestRecord + `]}]` func testSource(id, endpoint string) Source { - return Source{ID: id, NodeID: id, Epoch: "epoch-" + id, URL: endpoint + "/discovery", ServiceURL: "https://orch.example", ProxyURLTemplate: "https://{proxy}.apps.example", AuthMode: AuthCloudflare, Lifecycle: "active", Ready: true, Generation: 1, VerifiedGeneration: 1, CredentialRef: "ref-" + id, CredentialVersion: 1} + return Source{NodeID: id, URL: endpoint + "/discovery", ServiceURL: "https://orch.example", ProxyURLTemplate: "https://{proxy}.apps.example", AuthMode: AuthCloudflare, Lifecycle: "active", Ready: true, Generation: 1, VerifiedGeneration: 1, CredentialRef: "ref-" + id, CredentialVersion: 1} } func testFleet(t *testing.T, b *simulatedDiscoveryBackend, servers ...*httptest.Server) (*Manager, *bytes.Buffer) { t.Helper() @@ -140,7 +140,7 @@ func TestFleetIdentityAndPartialPublication(t *testing.T) { } } -func TestFleetAcknowledgementAfterClockRollback(t *testing.T) { +func TestFleetAcknowledgementRequiresDecodedReplacementCredential(t *testing.T) { source := testSource("one", "https://source.example") b := &simulatedDiscoveryBackend{sources: []Source{source}, credentials: map[string]Credential{source.CredentialRef: {"old-client", "old-secret"}}} f, _ := testFleet(t, b) @@ -163,15 +163,10 @@ func TestFleetAcknowledgementAfterClockRollback(t *testing.T) { b.sources[0].CredentialRef = "new-ref" b.credentials["new-ref"] = Credential{"new-client", "new-secret"} reconcileFleet(t, f) + f.collector.Refresh(t.Context(), false) if len(b.acknowledgements) != 1 || f.Status().Sources[0].State != "retained" || f.collector.Snapshots()[0].QueriedAt != original { t.Fatal("HTTP 200 login HTML acknowledged v2 or changed retained v1 observation") } - // Model a backward clock step without changing the host's system clock. - f.transport.mu.Lock() - a := f.transport.attempts[source.URL] - a.completed = original.Add(-time.Hour) - f.transport.attempts[source.URL] = a - f.transport.mu.Unlock() f.acknowledge(t.Context()) for _, ack := range b.acknowledgements { if ack.CredentialVersion == 2 { @@ -195,88 +190,51 @@ func TestFleetAcknowledgementAfterClockRollback(t *testing.T) { } } -func TestFleetRotationRefreshDuringWorkerRequest(t *testing.T) { +func TestFleetRotationDuringPollDoesNotAcknowledgeOldCredential(t *testing.T) { source := testSource("one", "https://source.example") b := &simulatedDiscoveryBackend{sources: []Source{source}, credentials: map[string]Credential{source.CredentialRef: {"old-client", "old-secret"}}} f, _ := testFleet(t, b) - f.interval = time.Hour started, release := make(chan struct{}), make(chan struct{}) - var unblock sync.Once - newRequest := make(chan struct{}, 1) var calls atomic.Int32 var allowNew atomic.Bool f.transport.base = discoveryRoundTripFunc(func(r *http.Request) (*http.Response, error) { if calls.Add(1) == 1 { close(started) <-release - if r.Header.Get("CF-Access-Client-Id") != "old-client" || r.Header.Get("CF-Access-Client-Secret") != "old-secret" { - t.Error("in-flight credential pair was mutated") - } } - if r.Header.Get("CF-Access-Client-Secret") == "new-secret" { - if r.Header.Get("CF-Access-Client-Id") != "new-client" { - t.Error("mixed replacement credential pair") - } - select { - case newRequest <- struct{}{}: - default: - } - if !allowNew.Load() { - return &http.Response{StatusCode: 403, Body: io.NopCloser(strings.NewReader("denied"))}, nil - } + status, body := 200, discoveryTestInventory + if r.Header.Get("CF-Access-Client-Secret") == "new-secret" && !allowNew.Load() { + status, body = 403, "denied" } - return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(discoveryTestInventory))}, nil + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body))}, nil }) reconcileFleet(t, f) - ctx, cancel := context.WithCancel(t.Context()) done := make(chan struct{}) - go func() { f.Run(ctx); close(done) }() - defer func() { unblock.Do(func() { close(release) }); cancel(); <-done }() + go func() { f.collector.Refresh(t.Context(), false); close(done) }() <-started - b.mu.Lock() - b.sources[0].Generation = 2 - b.sources[0].VerifiedGeneration = 2 - b.sources[0].CredentialVersion = 2 - b.sources[0].CredentialRef = "new-ref" - b.credentials["new-ref"] = Credential{"new-client", "new-secret"} - b.mu.Unlock() - reconciled := make(chan error, 1) - go func() { reconciled <- f.Reconcile(t.Context()) }() - deadline := time.After(time.Second) - for { - if selection := f.transport.selection.Load(); selection != nil && selection.sources[source.URL].source.Generation == 2 { - break - } - select { - case <-deadline: - t.Fatal("replacement selection not installed") - case <-time.After(time.Millisecond): - } - } - unblock.Do(func() { close(release) }) - if err := <-reconciled; err != nil { - t.Fatal(err) - } - select { - case <-newRequest: - case <-time.After(time.Second): - t.Fatal("replacement credential waits for periodic poll") - } + b.sources[0].Generation, b.sources[0].VerifiedGeneration, b.sources[0].CredentialVersion = 2, 2, 2 + b.sources[0].CredentialRef = "replacement" + b.credentials["replacement"] = Credential{"new-client", "new-secret"} + reconcileFleet(t, f) + close(release) + <-done + reconcileFleet(t, f) + f.collector.Refresh(t.Context(), false) + reconcileFleet(t, f) if len(b.acknowledgements) != 0 || f.Status().Sources[0].State != "retained" { - t.Fatal("old in-flight success or v2 authorization failure acknowledged v2") + t.Fatal("old response or denied replacement acknowledged a credential") } allowNew.Store(true) f.collector.Refresh(t.Context(), false) reconcileFleet(t, f) if len(b.acknowledgements) != 1 || b.acknowledgements[0].CredentialVersion != 2 { - t.Fatal("replacement attempt was not acknowledged") + t.Fatal("decoded replacement was not acknowledged") } - b.mu.Lock() - delete(b.credentials, "new-ref") - b.mu.Unlock() + delete(b.credentials, "replacement") reconcileFleet(t, f) + f.collector.Refresh(t.Context(), false) if f.Status().Sources[0].CredentialAvailable || f.Status().Sources[0].State != "retained" { - t.Fatal("missing credential did not fail closed with retention") + t.Fatal("missing credential did not fail closed") } } @@ -461,22 +419,27 @@ func TestFleetSelectionLifecycleAndStoreFailure(t *testing.T) { t.Fatal("draining source lost withdrawal polling") } b.mu.Lock() - b.sources[0].Epoch = "new-epoch" + b.sources[0].NodeID = "new-node" + b.sources[0].URL = "https://replacement.example/discovery" + f.transport.base = discoveryRoundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(discoveryTestInventory))}, nil + }) b.sources[0].Generation, b.sources[0].VerifiedGeneration = 1, 1 b.sources[0].Lifecycle = "active" b.sources[0].Ready = true b.mu.Unlock() reconcileFleet(t, f) if len(f.collector.Snapshots()) != 0 || f.Status().Sources[0].Acknowledged { - t.Fatal("epoch-only replacement reused predecessor cache or acknowledgement") + t.Fatal("node-only replacement reused predecessor cache or acknowledgement") } f.collector.Refresh(t.Context(), false) reconcileFleet(t, f) - if len(b.acknowledgements) != 2 || b.acknowledgements[1].Epoch != "new-epoch" { - t.Fatal("epoch-only replacement did not receive its own acknowledgement") + if len(b.acknowledgements) != 2 || b.acknowledgements[1].NodeID != "new-node" { + t.Fatal("node-only replacement did not receive its own acknowledgement") } b.mu.Lock() - b.sources[0].Epoch = "unverified-epoch" + b.sources[0].NodeID = "unverified-node" + b.sources[0].URL = "https://unverified.example/discovery" b.sources[0].Generation, b.sources[0].VerifiedGeneration = 2, 1 b.sources[0].Ready = false b.mu.Unlock() @@ -584,8 +547,8 @@ func TestFleetReplacementFencesInFlightResult(t *testing.T) { go func() { f.collector.Refresh(t.Context(), false); close(done) }() <-started b.mu.Lock() - b.sources[0].ID = "replacement" - b.sources[0].Epoch = "replacement-epoch" + b.sources[0].NodeID = "replacement-node" + b.sources[0].URL = "https://replacement.example/discovery" b.mu.Unlock() reconcileFleet(t, f) close(release) diff --git a/api/internal/controlplane/discovery/membership.go b/api/internal/controlplane/discovery/membership.go index 0556980..e3253e9 100644 --- a/api/internal/controlplane/discovery/membership.go +++ b/api/internal/controlplane/discovery/membership.go @@ -6,56 +6,29 @@ import ( shared "github.com/livepeer/node/discovery/shared" ) -type snapshotProvenance struct { - Key string - At time.Time -} - -// Membership describes publication as of a successful source snapshot. It does -// not attest application reachability, and contains no protected source URL. +// Membership describes app publication as of a successful source snapshot. type Membership struct { - State string `json:"state"` - ProvenanceCurrent bool `json:"provenance_current"` - QueriedAt *time.Time `json:"queried_at,omitempty"` - ObservedAt *time.Time `json:"observed_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` + State string `json:"state"` + QueriedAt *time.Time `json:"queried_at,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` } type MembershipQuery struct{ InstanceID, Endpoint, App, Version string } -// Caller holds the Manager lock and has captured attempts before snapshots. -func (f *Manager) snapshotCurrent(source Source, snapshot shared.Snapshot[runner], attempt attempt) bool { - if f.provenance == nil { - f.provenance = map[string]snapshotProvenance{} - } - prior := f.provenance[source.ID] - current := prior.Key == ackKey(source) && prior.At.Equal(snapshot.QueriedAt) - if !current && attempt.status == 200 && sameVersion(attempt.source, source) && !snapshot.QueriedAt.IsZero() && !snapshot.QueriedAt.Equal(attempt.before) { - f.provenance[source.ID] = snapshotProvenance{ackKey(source), snapshot.QueriedAt} - current = true - } - return current -} - -func (f *Manager) Membership(node, epoch, endpoint, app, version string) Membership { - return f.Memberships(node, epoch, []MembershipQuery{{Endpoint: endpoint, App: app, Version: version}})[""] +func (f *Manager) Membership(node, endpoint, app, version string) Membership { + return f.Memberships(node, []MembershipQuery{{Endpoint: endpoint, App: app, Version: version}})[""] } // Members of one bounded instance report share a single Collector snapshot read. -func (f *Manager) Memberships(node, epoch string, queries []MembershipQuery) map[string]Membership { +func (f *Manager) Memberships(node string, queries []MembershipQuery) map[string]Membership { f.mu.Lock() defer f.mu.Unlock() - f.transport.mu.Lock() - attempts := make(map[string]attempt, len(f.transport.attempts)) - for endpoint, value := range f.transport.attempts { - attempts[endpoint] = value - } snapshots := f.collector.Snapshots() - f.transport.mu.Unlock() published := f.publicInventory(snapshots) result := make(map[string]Membership, len(queries)) for _, q := range queries { - current := f.membership(node, epoch, q.Endpoint, q.App, q.Version, snapshots, published, attempts) + current := f.membership(node, q.Endpoint, q.App, q.Version, snapshots, published) if prior, ok := result[q.InstanceID]; ok { if prior.State != "present" { current = prior @@ -73,31 +46,23 @@ func (f *Manager) Memberships(node, epoch string, queries []MembershipQuery) map return result } -func (f *Manager) membership(node, epoch, endpoint, app, version string, snapshots []shared.Snapshot[runner], published []shared.Entry[publishedRunner], attempts map[string]attempt) Membership { +func (f *Manager) membership(node, endpoint, app, version string, snapshots []shared.Snapshot[runner], published []shared.Entry[publishedRunner]) Membership { result := Membership{State: "excluded"} for _, source := range f.selected { - if source.NodeID != node || source.Epoch != epoch { + if source.NodeID != node { continue } result.State = "uninitialized" - attempt := attempts[source.URL] for _, snapshot := range snapshots { if snapshot.URL != source.URL { continue } - current := f.snapshotCurrent(source, snapshot, attempt) - for _, configured := range f.configured { - if configured.ID == source.ID && !sameVersion(configured, source) { - current = false - } - } - result.ProvenanceCurrent = current at, expiry := snapshot.QueriedAt, snapshot.QueriedAt.Add(2*f.interval) result.QueriedAt, result.ExpiresAt = &at, &expiry result.State = "absent" for _, entry := range published { for _, candidate := range entry.Runners { - if candidate.sourceID != source.ID || !candidate.queriedAt.Equal(snapshot.QueriedAt) || candidate.URL != endpoint || candidate.App != app || candidate.Version != version { + if candidate.nodeID != source.NodeID || !candidate.queriedAt.Equal(snapshot.QueriedAt) || candidate.URL != endpoint || candidate.App != app || candidate.Version != version { continue } stamp, err := time.Parse(time.RFC3339Nano, candidate.ObservedAt) @@ -111,9 +76,7 @@ func (f *Manager) membership(node, epoch, endpoint, app, version string, snapsho } } } - if !current { - result.State = "unverified_provenance" - } else if f.reconcileFailed || f.reconciledAt.IsZero() || time.Since(f.reconciledAt) > 2*f.selectionInterval || !time.Now().Before(expiry) { + if f.reconcileFailed || f.reconciledAt.IsZero() || time.Since(f.reconciledAt) > 2*f.selectionInterval || !time.Now().Before(expiry) { result.State = "stale" } return result diff --git a/api/internal/controlplane/discovery/membership_test.go b/api/internal/controlplane/discovery/membership_test.go index c722f0c..b847892 100644 --- a/api/internal/controlplane/discovery/membership_test.go +++ b/api/internal/controlplane/discovery/membership_test.go @@ -1,7 +1,6 @@ package discovery import ( - "context" "encoding/json" "io" "net/http" @@ -36,7 +35,7 @@ func TestSharedBackendMembershipRequiresEveryApp(t *testing.T) { } body.Store(string(raw)) f.collector.Refresh(t.Context(), false) - got := f.Memberships(source.NodeID, source.Epoch, queries)["shared"] + got := f.Memberships(source.NodeID, queries)["shared"] want := "absent" if len(present) == 2 { want = "present" @@ -50,7 +49,7 @@ func TestSharedBackendMembershipRequiresEveryApp(t *testing.T) { } } -func TestMembershipBindsSuccessfulSnapshotToSourceVersion(t *testing.T) { +func TestMembershipFreshnessEmptyAndRecovery(t *testing.T) { source := testSource("one", "https://source.example") b := &simulatedDiscoveryBackend{sources: []Source{source}, credentials: map[string]Credential{source.CredentialRef: {"old-client", "secret-sentinel"}}} f, _ := testFleet(t, b) @@ -63,27 +62,27 @@ func TestMembershipBindsSuccessfulSnapshotToSourceVersion(t *testing.T) { validBody := body.Load() body.Store("initial collection failed") f.collector.Refresh(t.Context(), false) - missing := f.Membership(source.NodeID, source.Epoch, "https://orch.example/apps/a/session", "test", "v1") - if missing.State != "uninitialized" || missing.QueriedAt != nil || missing.ExpiresAt != nil || missing.ObservedAt != nil || missing.ProvenanceCurrent || f.Status().Sources[0].State != "uninitialized" { + missing := f.Membership(source.NodeID, "https://orch.example/apps/a/session", "test", "v1") + if missing.State != "uninitialized" || missing.QueriedAt != nil || missing.ExpiresAt != nil || missing.ObservedAt != nil || f.Status().Sources[0].State != "uninitialized" { t.Fatal("initial failure fabricated retained inventory", missing) } body.Store(validBody) f.collector.Refresh(t.Context(), false) lookup := func() Membership { - return f.Membership(source.NodeID, source.Epoch, "https://orch.example/apps/a/session", "test", "v1") + return f.Membership(source.NodeID, "https://orch.example/apps/a/session", "test", "v1") } - batch := f.Memberships(source.NodeID, source.Epoch, []MembershipQuery{{InstanceID: "one", Endpoint: "https://orch.example/apps/a/session", App: "test", Version: "v1"}, {InstanceID: "two", Endpoint: "https://orch.example/apps/a/session", App: "test", Version: "v2"}}) + batch := f.Memberships(source.NodeID, []MembershipQuery{{InstanceID: "one", Endpoint: "https://orch.example/apps/a/session", App: "test", Version: "v1"}, {InstanceID: "two", Endpoint: "https://orch.example/apps/a/session", App: "test", Version: "v2"}}) if batch["one"].State != "present" || batch["two"].State != "absent" { t.Fatal("batch mixed instance evidence", batch) } first := lookup() - if first.State != "present" || !first.ProvenanceCurrent { + if first.State != "present" { t.Fatal("did not confirm exact publication", first) } - if other := f.Membership(source.NodeID, "another-epoch", "https://orch.example/apps/a/session", "test", "v1"); other.State != "excluded" { + if other := f.Membership("another-node", "https://orch.example/apps/a/session", "test", "v1"); other.State != "excluded" { t.Fatal("cross-enrollment membership", other) } - if wrong := f.Membership(source.NodeID, source.Epoch, "https://orch.example/apps/a/session", "test", "v2"); wrong.State != "absent" { + if wrong := f.Membership(source.NodeID, "https://orch.example/apps/a/session", "test", "v2"); wrong.State != "absent" { t.Fatal("version mismatch claimed discovery", wrong) } b.sources[0].Generation = 2 @@ -93,14 +92,15 @@ func TestMembershipBindsSuccessfulSnapshotToSourceVersion(t *testing.T) { b.credentials["new-ref"] = Credential{"new-client", "new-secret"} body.Store("not discovery") reconcileFleet(t, f) + f.collector.Refresh(t.Context(), false) retained := lookup() - if retained.State != "unverified_provenance" || retained.ProvenanceCurrent || !retained.QueriedAt.Equal(*first.QueriedAt) { + if retained.State != "present" || !retained.QueriedAt.Equal(*first.QueriedAt) { t.Fatal("relabeled retained membership after rotation", retained) } body.Store("[]") f.collector.Refresh(t.Context(), false) empty := lookup() - if empty.State != "absent" || !empty.ProvenanceCurrent || empty.QueriedAt.Equal(*first.QueriedAt) { + if empty.State != "absent" || empty.QueriedAt.Equal(*first.QueriedAt) { t.Fatal("valid empty snapshot was not authoritative", empty) } raw, _ := json.Marshal(empty) @@ -114,12 +114,12 @@ func TestMembershipBindsSuccessfulSnapshotToSourceVersion(t *testing.T) { f.collector.Refresh(t.Context(), false) evicted := lookup() status := f.Status().Sources[0] - if evicted.State != "uninitialized" || evicted.QueriedAt != nil || evicted.ExpiresAt != nil || evicted.ObservedAt != nil || evicted.ProvenanceCurrent || status.State != "evicted" || status.LastSuccess == nil { + if evicted.State != "uninitialized" || evicted.QueriedAt != nil || evicted.ExpiresAt != nil || evicted.ObservedAt != nil || status.State != "evicted" || status.LastSuccess == nil { t.Fatal("eviction fabricated retained inventory or lost source history", evicted, status) } body.Store(validBody) f.collector.Refresh(t.Context(), false) - if recovered := lookup(); recovered.State != "present" || !recovered.ProvenanceCurrent { + if recovered := lookup(); recovered.State != "present" { t.Fatal("evicted source did not recover", recovered) } } @@ -144,51 +144,10 @@ func TestMembershipMatchesPublicDuplicateWinner(t *testing.T) { if strings.Contains(w.Body.String(), `"v1"`) || !strings.Contains(w.Body.String(), `"v2"`) { t.Fatal("unexpected public winner", w.Body.String()) } - if got := f.Membership(source.NodeID, source.Epoch, endpoint, "test", "v1"); got.State != "absent" { + if got := f.Membership(source.NodeID, endpoint, "test", "v1"); got.State != "absent" { t.Fatal("shadowed version claimed publication", got) } - if got := f.Membership(source.NodeID, source.Epoch, endpoint, "test", "v2"); got.State != "present" || !got.ObservedAt.Equal(now) || !got.ExpiresAt.After(now) { + if got := f.Membership(source.NodeID, endpoint, "test", "v2"); got.State != "present" || !got.ObservedAt.Equal(now) || !got.ExpiresAt.After(now) { t.Fatal("winning record lost freshness", got) } } - -func TestMembershipProvenanceDoesNotRequireReadBeforeFailedRefresh(t *testing.T) { - for _, failure := range []string{"timeout", "http_error", "invalid_200"} { - t.Run(failure, func(t *testing.T) { - source := testSource("one", "https://source.example") - b := &simulatedDiscoveryBackend{sources: []Source{source}, credentials: map[string]Credential{source.CredentialRef: {"client", "secret"}}} - f, _ := testFleet(t, b) - body := `[{"address":"https://orch.example","runners":[{"url":"https://orch.example/apps/a/session","app":"test","version":"v1","observed_at":"` + time.Now().UTC().Format(time.RFC3339Nano) + `"}]}]` - status := 200 - var failureErr error - f.transport.base = discoveryRoundTripFunc(func(*http.Request) (*http.Response, error) { - if failureErr != nil { - return nil, failureErr - } - return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body))}, nil - }) - reconcileFleet(t, f) - f.collector.Refresh(t.Context(), false) - at := f.collector.Snapshots()[0].QueriedAt - if failure == "timeout" { - failureErr = context.DeadlineExceeded - } else if failure == "http_error" { - status = 503 - } else { - body = "invalid inventory" - } - f.collector.Refresh(t.Context(), false) - got := f.Membership(source.NodeID, source.Epoch, "https://orch.example/apps/a/session", "test", "v1") - if got.State != "present" || !got.ProvenanceCurrent || !got.QueriedAt.Equal(at) { - t.Fatal("failed refresh erased known source provenance before first status read", got) - } - b.sources[0].Generation, b.sources[0].VerifiedGeneration, b.sources[0].CredentialVersion = 2, 2, 2 - b.sources[0].CredentialRef = "replacement" - b.credentials["replacement"] = Credential{"new-client", "new-secret"} - reconcileFleet(t, f) - if got := f.Membership(source.NodeID, source.Epoch, "https://orch.example/apps/a/session", "test", "v1"); got.State != "unverified_provenance" || got.ProvenanceCurrent { - t.Fatal("rotation borrowed predecessor provenance", got) - } - }) - } -} diff --git a/api/internal/controlplane/discovery/sources.go b/api/internal/controlplane/discovery/sources.go index 4e57816..f95b780 100644 --- a/api/internal/controlplane/discovery/sources.go +++ b/api/internal/controlplane/discovery/sources.go @@ -7,7 +7,6 @@ import ( "net/url" "regexp" "sort" - "strconv" "strings" "time" @@ -16,10 +15,6 @@ import ( var proxyIDPattern = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$`) -func sameVersion(a, b Source) bool { - return a.ID == b.ID && a.Epoch == b.Epoch && a.Generation == b.Generation && a.CredentialVersion == b.CredentialVersion && a.CredentialRef == b.CredentialRef && a.URL == b.URL -} - func (f *Manager) Reconcile(ctx context.Context) error { f.reconcileMu.Lock() defer f.reconcileMu.Unlock() @@ -28,22 +23,22 @@ func (f *Manager) Reconcile(ctx context.Context) error { f.reconciliationFailed() return errors.New("discovery source reconciliation failed") } - sort.Slice(sources, func(i, j int) bool { return sources[i].ID < sources[j].ID }) + sort.Slice(sources, func(i, j int) bool { return sources[i].NodeID < sources[j].NodeID }) f.mu.Lock() old := map[string]Source{} for _, source := range f.selected { - old[source.ID] = source + old[source.NodeID] = source } f.mu.Unlock() next := []Source{} seenIDs, seenURLs := map[string]bool{}, map[string]bool{} for _, source := range sources { - if source.ID == "" || seenIDs[source.ID] { + if source.NodeID == "" || seenIDs[source.NodeID] { f.reconciliationFailed() return errors.New("ambiguous discovery source identity") } - seenIDs[source.ID] = true - if previous, ok := old[source.ID]; ok && previous.Epoch == source.Epoch && source.Generation < previous.Generation { + seenIDs[source.NodeID] = true + if previous, ok := old[source.NodeID]; ok && source.Generation < previous.Generation { f.reconciliationFailed() return errors.New("stale discovery source generation") } @@ -54,8 +49,8 @@ func (f *Manager) Reconcile(ctx context.Context) error { // must not disable polling/recovery, including after an API restart. approved := source.Generation > 0 && source.VerifiedGeneration == source.Generation if !source.Ready && !approved { - previous, ok := old[source.ID] - if !ok || previous.Epoch != source.Epoch || previous.Generation != source.VerifiedGeneration { + previous, ok := old[source.NodeID] + if !ok || previous.Generation != source.VerifiedGeneration { continue } previous.Lifecycle = source.Lifecycle @@ -78,9 +73,10 @@ func (f *Manager) Reconcile(ctx context.Context) error { seenURLs[source.URL] = true next = append(next, source) } - authorizations := map[string]authorization{} + authorizations := map[string]*authorization{} + prior := f.transport.selection.Load() for _, source := range next { - auth := authorization{source: source, available: source.AuthMode == AuthNone} + auth := &authorization{source: source, available: source.AuthMode == AuthNone} if source.AuthMode == AuthCloudflare { credential, e := f.backend.Resolve(ctx, source.CredentialRef) if e == nil && validCredential(credential) { @@ -88,6 +84,13 @@ func (f *Manager) Reconcile(ctx context.Context) error { auth.available = true } } + // Reuse confirmation only for the same immutable source authorization. + if prior != nil { + old := prior.sources[source.URL] + if old != nil && old.source.NodeID == source.NodeID && old.source.Generation == source.Generation && old.source.CredentialRef == source.CredentialRef && old.source.CredentialVersion == source.CredentialVersion && old.source.ServiceURL == source.ServiceURL && old.source.AuthMode == source.AuthMode && old.credential == auth.credential && old.available == auth.available { + auth = old + } + } authorizations[source.URL] = auth } if ctx.Err() != nil { @@ -95,34 +98,7 @@ func (f *Manager) Reconcile(ctx context.Context) error { return ctx.Err() } f.mu.Lock() - previousAuth := f.transport.selection.Load() - changedCredentials := []string{} - survivors := []*url.URL{} - for _, source := range f.selected { - // SetSources keys on URL. Explicitly remove a reused URL when its - // enrollment identity changes, fencing an obsolete in-flight result. - auth, ok := authorizations[source.URL] - if ok && auth.source.ID == source.ID && auth.source.Epoch == source.Epoch { - u, _ := url.Parse(source.URL) - survivors = append(survivors, u) - if previousAuth != nil { - prior := previousAuth.sources[source.URL] - if !sameVersion(prior.source, auth.source) || prior.source.AuthMode != auth.source.AuthMode || prior.available != auth.available || prior.credential != auth.credential { - changedCredentials = append(changedCredentials, source.URL) - } - } - } - } - f.collector.SetSources(survivors) - revision := f.transport.install(authorizations) - for _, endpoint := range changedCredentials { - f.pendingRefresh[endpoint] = revision - } - for endpoint := range f.pendingRefresh { - if !seenURLs[endpoint] { - delete(f.pendingRefresh, endpoint) - } - } + f.transport.install(authorizations) urls := make([]*url.URL, 0, len(next)) for _, source := range next { u, _ := url.Parse(source.URL) @@ -134,107 +110,38 @@ func (f *Manager) Reconcile(ctx context.Context) error { } f.selected = next f.configured = sources - for id := range f.provenance { - if !seenIDs[id] { - delete(f.provenance, id) - } - } f.reconciledAt = time.Now().UTC() f.reconcileFailed = false - f.transport.mu.Lock() - for endpoint := range f.transport.attempts { - if !seenURLs[endpoint] { - delete(f.transport.attempts, endpoint) - } - } - f.transport.mu.Unlock() - ackKeys := map[string]bool{} - for _, source := range next { - ackKeys[ackKey(source)] = true - } - for key := range f.acknowledged { - if !ackKeys[key] { - delete(f.acknowledged, key) - } - } f.mu.Unlock() - if len(f.pendingRefresh) > 0 { - f.collector.Refresh(ctx, false) - // Refresh may have joined a predecessor batch. A bounded follow-up - // starts with the installed selection; no second poller/cache is added. - f.clearAttemptedRefreshes() - if len(f.pendingRefresh) > 0 && ctx.Err() == nil { - f.collector.Refresh(ctx, false) - f.clearAttemptedRefreshes() - } - } f.acknowledge(ctx) return nil } -// Pending configuration refreshes survive a canceled reconciliation wait. Any -// completed attempt with this or a later immutable selection fulfills the wakeup; -// a failed collection then follows the Collector's ordinary retry/failure policy. -func (f *Manager) clearAttemptedRefreshes() { - f.transport.mu.Lock() - defer f.transport.mu.Unlock() - for endpoint, revision := range f.pendingRefresh { - if f.transport.attempts[endpoint].revision >= revision { - delete(f.pendingRefresh, endpoint) - } - } -} - func (f *Manager) reconciliationFailed() { f.mu.Lock(); f.reconcileFailed = true; f.mu.Unlock() } +// Acknowledgement asserts that this source authorization decoded successfully. +// The backend rechecks the current credential and deployment generation atomically. func (f *Manager) acknowledge(ctx context.Context) { f.mu.Lock() + selection := f.transport.selection.Load() sources := append([]Source(nil), f.selected...) - attempts := map[string]attempt{} - f.transport.mu.Lock() - for endpoint, attempt := range f.transport.attempts { - attempts[endpoint] = attempt - } - // Capture attempts before snapshots under the same lock. A later attempt - // must not be compared with an older already-copied observation marker. - snapshots := f.collector.Snapshots() - f.transport.mu.Unlock() f.mu.Unlock() + if selection == nil { + return + } for _, source := range sources { - if source.AuthMode != AuthCloudflare || source.Lifecycle != "active" { - continue - } - f.mu.Lock() - acked := f.acknowledged[ackKey(source)] - f.mu.Unlock() - if acked { - continue - } - attempt, ok := attempts[source.URL] - if !ok || attempt.status != 200 || !sameVersion(attempt.source, source) { - continue - } - for _, snapshot := range snapshots { - if snapshot.URL != source.URL || snapshot.QueriedAt.IsZero() || snapshot.QueriedAt.Equal(attempt.before) { - continue - } - valid := true - for _, entry := range snapshot.Entries { - valid = valid && publicAddress(source, entry.Address) - } - if valid && f.backend.Acknowledge(ctx, source) == nil { - f.mu.Lock() - f.acknowledged[ackKey(source)] = true - f.mu.Unlock() - } + auth := selection.sources[source.URL] + f.transport.mu.Lock() + ready := auth.confirmed && !auth.acknowledged + f.transport.mu.Unlock() + if ready && source.AuthMode == AuthCloudflare && source.Lifecycle == "active" && f.backend.Acknowledge(ctx, source) == nil { + f.transport.mu.Lock() + auth.acknowledged = true + f.transport.mu.Unlock() } } } -func ackKey(source Source) string { - return source.ID + "\x00" + source.Epoch + "\x00" + source.URL + "\x00" + source.CredentialRef + "\x00" + strconv.FormatInt(source.Generation, 10) + "/" + strconv.FormatInt(source.CredentialVersion, 10) -} - // Public routing comes from the same managed state as source selection. Do not // rewrite upstream URLs or publish a private/wrong-machine registration target. func publicEntry(source Source, entry shared.Entry[runner]) bool { diff --git a/api/internal/controlplane/discovery/status.go b/api/internal/controlplane/discovery/status.go index 43f74d6..16a95cc 100644 --- a/api/internal/controlplane/discovery/status.go +++ b/api/internal/controlplane/discovery/status.go @@ -22,9 +22,7 @@ type Status struct { } type SourceStatus struct { - ID string `json:"id"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` Generation int64 `json:"generation"` SelectedGeneration int64 `json:"selected_generation,omitempty"` Lifecycle string `json:"lifecycle"` @@ -67,7 +65,7 @@ func (f *Manager) Status() Status { } selected := make([]SourceStatus, len(f.selected)) for i, source := range f.selected { - selected[i] = SourceStatus{ID: source.ID, Selected: true, SelectedGeneration: source.Generation} + selected[i] = SourceStatus{NodeID: source.NodeID, Selected: true, SelectedGeneration: source.Generation} } collectDiscoveryMetrics(f.collector.CollectMetrics, func(name string, value float64, labels map[string]string) { i, err := strconv.Atoi(labels["source_index"]) @@ -104,21 +102,24 @@ func (f *Manager) Status() Status { if auth := f.transport.selection.Load(); auth != nil { s.CredentialAvailable = auth.sources[source.URL].available } - if attempt, ok := f.transport.attempts[source.URL]; ok && sameVersion(attempt.source, source) { - stamp := attempt.completed - s.LastAttempt = &stamp - s.TransportOutcome = attempt.outcome - s.HTTPStatus = attempt.status + if auth := f.transport.selection.Load(); auth != nil && auth.sources[source.URL] != nil { + a := auth.sources[source.URL] + if !a.attempt.completed.IsZero() { + stamp := a.attempt.completed + s.LastAttempt = &stamp + s.TransportOutcome = a.attempt.outcome + s.HTTPStatus = a.attempt.status + } + s.Acknowledged = a.acknowledged } - s.Acknowledged = f.acknowledged[ackKey(source)] - byID[source.ID] = s + byID[source.NodeID] = s } for _, snapshot := range f.collector.Snapshots() { for _, source := range f.selected { if source.URL != snapshot.URL { continue } - s := byID[source.ID] + s := byID[source.NodeID] for _, entry := range snapshot.Entries { if !publicEntry(source, entry) { s.PublicationBlocked = true @@ -136,13 +137,13 @@ func (f *Manager) Status() Status { } } } - byID[source.ID] = s + byID[source.NodeID] = s } } for _, source := range f.configured { - s, ok := byID[source.ID] + s, ok := byID[source.NodeID] if !ok { - s = SourceStatus{ID: source.ID, State: "excluded", Stale: true} + s = SourceStatus{NodeID: source.NodeID, State: "excluded", Stale: true} } s.SelectionReason = "selected" if !ok { @@ -154,8 +155,6 @@ func (f *Manager) Status() Status { s.SelectionReason = "blocked" } } - s.NodeID = source.NodeID - s.Epoch = source.Epoch s.Generation = source.Generation s.Lifecycle = source.Lifecycle status.Sources = append(status.Sources, s) diff --git a/api/internal/controlplane/discovery/types.go b/api/internal/controlplane/discovery/types.go index 1ec605f..0bfc127 100644 --- a/api/internal/controlplane/discovery/types.go +++ b/api/internal/controlplane/discovery/types.go @@ -53,9 +53,7 @@ type Credential struct { } type Source struct { - ID string `json:"id"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` URL string `json:"url"` ServiceURL string `json:"service_url"` ProxyURLTemplate string `json:"proxy_url_template"` diff --git a/api/internal/controlplane/discovery_database_test.go b/api/internal/controlplane/discovery_database_test.go index bc08a97..a5d3251 100644 --- a/api/internal/controlplane/discovery_database_test.go +++ b/api/internal/controlplane/discovery_database_test.go @@ -34,7 +34,7 @@ func TestFleetEncryptedStoreAPIAndRotation(t *testing.T) { readyTunnel(t, s, a) readyTunnel(t, s, b) adminA(t, s) - s.params.DiscoveryParams = DiscoveryParams{DiscoveryEnabled: true, DiscoveryRefreshInterval: 5 * time.Minute, DiscoveryMaxFailedRefreshes: 6} + s.params.DiscoveryParams = DiscoveryParams{DiscoveryEnabled: true, DiscoveryRefreshInterval: time.Second, DiscoveryMaxFailedRefreshes: 6} if err := s.ConfigureDiscovery(); err != nil { t.Fatal(err) } @@ -127,30 +127,39 @@ func TestFleetEncryptedStoreAPIAndRotation(t *testing.T) { } } managerBeforeRotation := s.tunnels - rotate := request(t, s, "POST", "/api/admin/machines/"+a["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": a["epoch"], "kind": "access"}) + rotate := request(t, s, "POST", "/api/admin/machines/"+a["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": "access"}) requireStatus(t, rotate, 202) driveTunnels(t, s) reconcileDiscovery(t, s) var acknowledged bool - if err := s.db.QueryRow(`SELECT acknowledged_at IS NOT NULL FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=2`, a["node_id"], a["epoch"]).Scan(&acknowledged); err != nil || !acknowledged { - t.Fatal("new version not acknowledged by actual collection", err) + for deadline := time.Now().Add(3 * time.Second); !acknowledged; { + reconcileDiscovery(t, s) + if err := s.db.QueryRow(`SELECT acknowledged_at IS NOT NULL FROM lpcc.access_credentials WHERE node_id=$1 AND version=2`, a["node_id"]).Scan(&acknowledged); err != nil { + t.Fatal(err) + } + if !acknowledged && time.Now().After(deadline) { + t.Fatal("replacement credential was not acknowledged after periodic collection") + } + if !acknowledged { + time.Sleep(10 * time.Millisecond) + } } driveTunnels(t, s) if s.tunnels != managerBeforeRotation { t.Fatal("ordinary reconciliation replaced manager with active discovery readers") } var active int - if err := s.db.QueryRow(`SELECT count(*) FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, a["node_id"], a["epoch"]).Scan(&active); err != nil || active != 1 { + if err := s.db.QueryRow(`SELECT count(*) FROM lpcc.access_credentials WHERE node_id=$1 AND revoked_at IS NULL`, a["node_id"]).Scan(&active); err != nil || active != 1 { t.Fatal("acknowledgement did not release predecessor token", err, active) } - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+a["node_id"], "session-a", map[string]any{"epoch": a["epoch"], "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+a["node_id"], "session-a", map[string]any{"force": true}), 202) reconcileDiscovery(t, s) if strings.Count(request(t, s, "GET", "/discovery", "", nil).Body.String(), `"app":"test"`) != 1 { t.Fatal("machine removal did not withdraw only that source") } // Missing routing identity must withdraw a previously approved source, // including before the tunnel worker runs again. - execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=state-'endpoint_suffix' WHERE node_id=$1`, b["node_id"]) + execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=state-'service_url' WHERE node_id=$1`, b["node_id"]) reconcileDiscovery(t, s) if strings.Contains(request(t, s, "GET", "/discovery", "", nil).Body.String(), `"app":"test"`) { t.Fatal("source without routing identity remained advertised") @@ -173,7 +182,7 @@ func TestFleetConfigurationAndPublicDisabledRoute(t *testing.T) { } requireStatus(t, request(t, s, "GET", "/discovery", "", nil), 503) requireStatus(t, request(t, s, "GET", "/healthz", "", nil), 200) - p.DiscoveryParams = DiscoveryParams{DiscoveryEnabled: true, DiscoveryRefreshInterval: 5 * time.Minute, DiscoveryMaxFailedRefreshes: 6} + p.DiscoveryParams = DiscoveryParams{DiscoveryEnabled: true, DiscoveryRefreshInterval: time.Second, DiscoveryMaxFailedRefreshes: 6} s.params = p if s.ConfigureDiscovery() == nil { t.Fatal("discovery started without ingress approval") diff --git a/api/internal/controlplane/machine_admin.go b/api/internal/controlplane/machine_admin.go index 6f1b10f..80add9b 100644 --- a/api/internal/controlplane/machine_admin.go +++ b/api/internal/controlplane/machine_admin.go @@ -14,23 +14,22 @@ import ( func (s *Server) prepareMachineRemoval(r *http.Request, _ UserIdentity) (AdminApply, error) { var in struct { - Epoch string `json:"epoch"` - Force bool `json:"force"` + Force bool `json:"force"` } if err := machineInput(r, &in); err != nil { return nil, err } node := r.PathValue("node_id") return func(ctx context.Context, tx *sql.Tx, _ UserIdentity) (AdminChange, error) { - result, err := s.configs.Remove(ctx, tx, node, in.Epoch, in.Force) + result, err := s.configs.Remove(ctx, tx, node, in.Force) if err != nil { return AdminChange{}, configurationProblem(err) } - target := AdminTarget{Kind: "machine", ID: node, Revision: in.Epoch} + target := AdminTarget{Kind: "machine", ID: node, Revision: node} if result.AlreadyRemoved { return AdminChange{Target: target, Status: 204}, nil } - body := map[string]any{"lifecycle": result.Lifecycle, "epoch": result.Epoch} + body := map[string]any{"lifecycle": result.Lifecycle, "node_id": result.NodeID} if result.Generation != 0 { target.Revision += ":" + strconv.FormatInt(result.Generation, 10) body["generation"] = result.Generation @@ -41,19 +40,18 @@ func (s *Server) prepareMachineRemoval(r *http.Request, _ UserIdentity) (AdminAp func (s *Server) prepareDrainRetry(r *http.Request, _ UserIdentity) (AdminApply, error) { var in struct { - Epoch string `json:"epoch"` - Generation int64 `json:"generation"` + Generation int64 `json:"generation"` } if err := machineInput(r, &in); err != nil { return nil, err } node := r.PathValue("node_id") return func(ctx context.Context, tx *sql.Tx, _ UserIdentity) (AdminChange, error) { - result, err := s.configs.RetryDrain(ctx, tx, node, in.Epoch, in.Generation) + result, err := s.configs.RetryDrain(ctx, tx, node, in.Generation) if err != nil { return AdminChange{}, configurationProblem(err) } - return AdminChange{Target: AdminTarget{Kind: "machine", ID: node, Revision: in.Epoch + ":" + strconv.FormatInt(result.Generation, 10)}, Changed: result.Changed, Status: 202, Body: map[string]any{"generation": result.Generation, "lifecycle": result.Lifecycle}}, nil + return AdminChange{Target: AdminTarget{Kind: "machine", ID: node, Revision: node + ":" + strconv.FormatInt(result.Generation, 10)}, Changed: result.Changed, Status: 202, Body: map[string]any{"generation": result.Generation, "lifecycle": result.Lifecycle}}, nil }, nil } @@ -61,8 +59,6 @@ func configurationProblem(err error) error { switch { case errors.Is(err, machineconfig.ErrNotFound): return problem(404, "machine_not_found", "Machine not found.") - case errors.Is(err, machineconfig.ErrEnrollmentChanged): - return problem(409, "epoch_changed", "Machine enrollment changed.") case errors.Is(err, machineconfig.ErrDrainChanged): return problem(409, "drain_changed", "Drain intent changed.") case errors.Is(err, machineconfig.ErrDrainNotExpired): @@ -74,7 +70,6 @@ func configurationProblem(err error) error { func (s *Server) prepareTunnelRotation(r *http.Request, _ UserIdentity) (AdminApply, error) { var in struct { - Epoch string `json:"epoch"` Kind string `json:"kind"` Compromised bool `json:"compromised"` } @@ -90,7 +85,7 @@ func (s *Server) prepareTunnelRotation(r *http.Request, _ UserIdentity) (AdminAp var revision int64 var state tunnel.RoutingState var lifecycle string - e := tx.QueryRowContext(ctx, `SELECT state,revision,rollout->>'lifecycle' FROM lpcc.machine_states WHERE node_id=$1 AND epoch::text=$2 FOR UPDATE`, node, in.Epoch).Scan(&b, &revision, &lifecycle) + e := tx.QueryRowContext(ctx, `SELECT state,revision,rollout->>'lifecycle' FROM lpcc.machine_states WHERE node_id=$1 FOR UPDATE`, node).Scan(&b, &revision, &lifecycle) if errors.Is(e, sql.ErrNoRows) { return AdminChange{}, problem(404, "tunnel_not_found", "Tunnel not found.") } @@ -106,9 +101,6 @@ func (s *Server) prepareTunnelRotation(r *http.Request, _ UserIdentity) (AdminAp if lifecycle != "active" { return AdminChange{}, problem(409, "tunnel_inactive", "Tunnel is not active.") } - if state.EndpointSuffix == "" { - return AdminChange{}, problem(409, "invalid_tunnel_state", "Tunnel routing state is incomplete.") - } previous := string(b) if in.Kind == "connector" { state.RotateTunnel = true @@ -121,8 +113,8 @@ func (s *Server) prepareTunnelRotation(r *http.Request, _ UserIdentity) (AdminAp b, _ = json.Marshal(state) changed := previous != string(b) if changed { - e = tx.QueryRowContext(ctx, `UPDATE lpcc.machine_states SET state=$3,revision=revision+1,next_attempt_at=now() WHERE node_id=$1 AND epoch=$2 RETURNING revision`, node, in.Epoch, string(b)).Scan(&revision) + e = tx.QueryRowContext(ctx, `UPDATE lpcc.machine_states SET state=$2,revision=revision+1,next_attempt_at=now() WHERE node_id=$1 RETURNING revision`, node, string(b)).Scan(&revision) } - return AdminChange{Target: AdminTarget{Kind: "tunnel", ID: node, Revision: in.Epoch + ":" + strconv.FormatInt(revision, 10)}, Changed: changed, Status: 202, Body: map[string]string{"status": "rotation_queued"}}, e + return AdminChange{Target: AdminTarget{Kind: "tunnel", ID: node, Revision: node + ":" + strconv.FormatInt(revision, 10)}, Changed: changed, Status: 202, Body: map[string]string{"status": "rotation_queued"}}, e }, nil } diff --git a/api/internal/controlplane/machine_credentials.go b/api/internal/controlplane/machine_credentials.go index fb0847d..00787ce 100644 --- a/api/internal/controlplane/machine_credentials.go +++ b/api/internal/controlplane/machine_credentials.go @@ -22,37 +22,27 @@ import ( func (s *Server) enrollmentToken(m Machine) string { mac := hmac.New(sha256.New, []byte(s.params.MachineTokenSecret)) - mac.Write([]byte("machine:v2:" + m.OwnerID + ":" + m.NodeID + ":" + m.Epoch + ":" + strconv.FormatInt(m.CredentialVersion, 10))) + mac.Write([]byte("machine:v2:" + m.OwnerID + ":" + m.NodeID + ":" + strconv.FormatInt(m.CredentialVersion, 10))) return hex.EncodeToString(mac.Sum(nil)) } func (s *Server) authenticateMachine(ctx context.Context, node, token string, retired bool) (Machine, error) { if !fingerprintPattern.MatchString(token) { return Machine{}, problem(401, "invalid_machine_credential", "Invalid machine credential.") } - rows, e := s.db.QueryContext(ctx, `SELECT node_id,epoch::text,owner_id::text,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at IS NOT NULL FROM lpcc.enrollments WHERE node_id=$1`, node) - if e != nil { - return Machine{}, e - } - defer rows.Close() - found := false - for rows.Next() { - var m Machine - if e := rows.Scan(&m.NodeID, &m.Epoch, &m.OwnerID, &m.Fingerprint, &m.Hostname, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal); e != nil { - return m, e - } - found = true - if hmac.Equal([]byte(token), []byte(s.enrollmentToken(m))) && (!m.Terminal || retired) { - return m, nil - } + var m Machine + e := s.db.QueryRowContext(ctx, `SELECT node_id,owner_id::text,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at IS NOT NULL FROM lpcc.enrollments WHERE node_id=$1`, node).Scan(&m.NodeID, &m.OwnerID, &m.Fingerprint, &m.Hostname, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal) + if errors.Is(e, sql.ErrNoRows) { + return m, problem(404, "machine_not_found", "Machine not found.") } - if e := rows.Err(); e != nil { - return Machine{}, e + if e != nil { + return m, e } - if !found { - return Machine{}, problem(404, "machine_not_found", "Machine not found.") + if !hmac.Equal([]byte(token), []byte(s.enrollmentToken(m))) || m.Terminal && !retired { + return m, problem(401, "invalid_machine_credential", "Invalid machine credential.") } - return Machine{}, problem(401, "invalid_machine_credential", "Invalid machine credential.") + return m, nil } + func machineInput(r *http.Request, v any) error { return boundedMachineInput(r, v, 16384) } @@ -100,7 +90,7 @@ func (s *Server) refreshCredentials(w http.ResponseWriter, r *http.Request) { } defer tx.Rollback() var m Machine - e = tx.QueryRowContext(r.Context(), `SELECT node_id,enrollment_epoch::text,owner_id::text,fingerprint,hostname,install_dir,k3s_version,credential_version FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, r.PathValue("node_id")).Scan(&m.NodeID, &m.Epoch, &m.OwnerID, &m.Fingerprint, &m.Hostname, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion) + e = tx.QueryRowContext(r.Context(), `SELECT node_id,owner_id::text,fingerprint,hostname,install_dir,k3s_version,credential_version FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, r.PathValue("node_id")).Scan(&m.NodeID, &m.OwnerID, &m.Fingerprint, &m.Hostname, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion) if errors.Is(e, sql.ErrNoRows) { fail(w, 404, "machine not found") return @@ -114,7 +104,7 @@ func (s *Server) refreshCredentials(w http.ResponseWriter, r *http.Request) { return } var expected, result int64 - e = tx.QueryRowContext(r.Context(), `SELECT expected_version,resulting_version FROM lpcc.credential_refreshes WHERE node_id=$1 AND epoch=$2 AND operation_id=$3`, m.NodeID, m.Epoch, op.String()).Scan(&expected, &result) + e = tx.QueryRowContext(r.Context(), `SELECT expected_version,resulting_version FROM lpcc.credential_refreshes WHERE node_id=$1 AND operation_id=$2`, m.NodeID, op.String()).Scan(&expected, &result) if e == nil { if expected != in.ExpectedVersion || result != m.CredentialVersion { fail(w, 409, "refresh operation is conflicting or superseded") @@ -126,19 +116,19 @@ func (s *Server) refreshCredentials(w http.ResponseWriter, r *http.Request) { return } m.CredentialVersion++ - if _, e = tx.ExecContext(r.Context(), `INSERT INTO lpcc.credential_refreshes(node_id,epoch,operation_id,expected_version,resulting_version) VALUES($1,$2,$3,$4,$5)`, m.NodeID, m.Epoch, op.String(), in.ExpectedVersion, m.CredentialVersion); e != nil { + if _, e = tx.ExecContext(r.Context(), `INSERT INTO lpcc.credential_refreshes(node_id,operation_id,expected_version,resulting_version) VALUES($1,$2,$3,$4)`, m.NodeID, op.String(), in.ExpectedVersion, m.CredentialVersion); e != nil { s.databaseError(w, e) return } - if _, e = tx.ExecContext(r.Context(), `UPDATE lpcc.machines SET credential_version=$3,tunnel_eligible=true WHERE node_id=$1 AND enrollment_epoch=$2`, m.NodeID, m.Epoch, m.CredentialVersion); e != nil { + if _, e = tx.ExecContext(r.Context(), `UPDATE lpcc.machines SET credential_version=$2,tunnel_eligible=true WHERE node_id=$1`, m.NodeID, m.CredentialVersion); e != nil { s.databaseError(w, e) return } - if _, e = tx.ExecContext(r.Context(), `UPDATE lpcc.enrollments SET credential_version=$3 WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch, m.CredentialVersion); e != nil { + if _, e = tx.ExecContext(r.Context(), `UPDATE lpcc.enrollments SET credential_version=$2 WHERE node_id=$1`, m.NodeID, m.CredentialVersion); e != nil { s.databaseError(w, e) return } - if e = s.configs.FenceCredentialRefresh(r.Context(), tx, m.NodeID, m.Epoch); e != nil { + if e = s.configs.FenceCredentialRefresh(r.Context(), tx, m.NodeID); e != nil { s.databaseError(w, e) return } @@ -164,7 +154,7 @@ func (s *Server) connectorToken(w http.ResponseWriter, r *http.Request) { fail(w, 403, "connector delivery is not enabled for this enrollment") return } - state, _, e := s.loadTunnel(r.Context(), m.NodeID, m.Epoch) + state, _, e := s.loadTunnel(r.Context(), m.NodeID) if e != nil { s.respondError(w, e) return @@ -200,19 +190,19 @@ func (s *Server) connectorToken(w http.ResponseWriter, r *http.Request) { s.respondError(w, e) return } - latest, _, e := s.loadTunnel(r.Context(), m.NodeID, m.Epoch) + latest, _, e := s.loadTunnel(r.Context(), m.NodeID) stillRetained, retainErr := s.retainedConnector(r.Context(), m) if e != nil || retainErr != nil || (m.Terminal && (!stillRetained || latest.CompromisedAccess)) || (!stillRetained && latest.Lifecycle != "active") || latest.TunnelID != state.TunnelID || latest.CredentialGeneration != state.CredentialGeneration || latest.RotateTunnel || latest.Compromised || latest.Quarantined || latest.ConnectorRevoked { fail(w, 409, "tunnel changed during credential retrieval") return } - respond(w, 200, map[string]any{"token": token, "epoch": m.Epoch, "tunnel_id": state.TunnelID, "generation": state.Generation, "credential_generation": state.CredentialGeneration, "provider_version": state.ProviderVersion}) + respond(w, 200, map[string]any{"token": token, "node_id": m.NodeID, "tunnel_id": state.TunnelID, "generation": state.Generation, "credential_generation": state.CredentialGeneration, "provider_version": state.ProviderVersion}) } func (s *Server) retainedConnector(ctx context.Context, m Machine) (bool, error) { if !m.Terminal { return false, nil } - return machineapps.Pending(ctx, s.db, m.NodeID, m.Epoch) + return machineapps.Pending(ctx, s.db, m.NodeID) } func (s *Server) machineStatus(w http.ResponseWriter, r *http.Request) { m, e := s.authenticateMachine(r.Context(), r.PathValue("node_id"), bearer(r), true) @@ -225,7 +215,7 @@ func (s *Server) machineStatus(w http.ResponseWriter, r *http.Request) { s.respondError(w, e) return } - if report.Epoch != m.Epoch || report.CredentialVersion != m.CredentialVersion || report.Generation < 1 || (report.Component != "runtime" && report.Component != "connector" && report.Component != "runner" && report.Component != "app-reconciler") { + if report.NodeID != m.NodeID || report.CredentialVersion != m.CredentialVersion || report.Generation < 1 || (report.Component != "runtime" && report.Component != "connector" && report.Component != "runner" && report.Component != "app-reconciler") { fail(w, 409, "status does not match enrollment") return } @@ -262,7 +252,7 @@ func (s *Server) removalAck(w http.ResponseWriter, r *http.Request) { return } var in struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` Digest string `json:"digest"` ConnectorAbsent bool `json:"connector_absent"` } @@ -270,11 +260,11 @@ func (s *Server) removalAck(w http.ResponseWriter, r *http.Request) { s.respondError(w, e) return } - if !m.Terminal || in.Epoch != m.Epoch || !in.ConnectorAbsent || !fingerprintPattern.MatchString(in.Digest) { + if !m.Terminal || in.NodeID != m.NodeID || !in.ConnectorAbsent || !fingerprintPattern.MatchString(in.Digest) { fail(w, 409, "invalid removal acknowledgement") return } - pending, e := machineapps.Pending(r.Context(), s.db, m.NodeID, m.Epoch) + pending, e := machineapps.Pending(r.Context(), s.db, m.NodeID) if e != nil { s.respondError(w, e) return @@ -283,7 +273,7 @@ func (s *Server) removalAck(w http.ResponseWriter, r *http.Request) { fail(w, 409, "app cleanup is incomplete") return } - result, e := s.db.ExecContext(r.Context(), `UPDATE lpcc.enrollments SET removal_ack_at=COALESCE(removal_ack_at,now()) WHERE node_id=$1 AND epoch=$2 AND retired_at IS NOT NULL AND terminal_sha256=$3`, m.NodeID, m.Epoch, in.Digest) + result, e := s.db.ExecContext(r.Context(), `UPDATE lpcc.enrollments SET removal_ack_at=COALESCE(removal_ack_at,now()) WHERE node_id=$1 AND retired_at IS NOT NULL AND terminal_sha256=$2`, m.NodeID, in.Digest) if e != nil { s.databaseError(w, e) return diff --git a/api/internal/controlplane/machineapps/store.go b/api/internal/controlplane/machineapps/store.go index 98904d6..e12b37f 100644 --- a/api/internal/controlplane/machineapps/store.go +++ b/api/internal/controlplane/machineapps/store.go @@ -53,45 +53,45 @@ func ReadVersions(rows *sql.Rows) ([]Version, error) { const VersionColumns = `v.intent,v.actor_id,v.created_at,c.received_at,CASE WHEN c.received_at IS NULL THEN COALESCE(d.reason,'') ELSE '' END,COALESCE(c.received_at,d.received_at),r.app_name,r.revision` const VersionJoins = ` JOIN lpcc.app_revisions r ON r.revision_id=v.revision_id - LEFT JOIN lpcc.machine_app_completions c ON c.node_id=v.node_id AND c.epoch=v.epoch AND c.revision_id=v.revision_id AND c.generation=v.generation - LEFT JOIN lpcc.machine_app_diagnostics d ON d.node_id=v.node_id AND d.epoch=v.epoch AND d.revision_id=v.revision_id AND d.generation=v.generation ` + LEFT JOIN lpcc.machine_app_completions c ON c.node_id=v.node_id AND c.revision_id=v.revision_id AND c.generation=v.generation + LEFT JOIN lpcc.machine_app_diagnostics d ON d.node_id=v.node_id AND d.revision_id=v.revision_id AND d.generation=v.generation ` -func Head(ctx context.Context, q Querier, node, epoch, id string) (Version, error) { - return ReadVersion(q.QueryRowContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_heads v `+VersionJoins+` WHERE v.node_id=$1 AND v.epoch=$2 AND v.revision_id=$3`, node, epoch, id)) +func Head(ctx context.Context, q Querier, node, id string) (Version, error) { + return ReadVersion(q.QueryRowContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_heads v `+VersionJoins+` WHERE v.node_id=$1 AND v.revision_id=$2`, node, id)) } -func AtGeneration(ctx context.Context, q Querier, node, epoch, id string, generation int64) (Version, error) { - return ReadVersion(q.QueryRowContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_versions v `+VersionJoins+` WHERE v.node_id=$1 AND v.epoch=$2 AND v.revision_id=$3 AND v.generation=$4`, node, epoch, id, generation)) +func AtGeneration(ctx context.Context, q Querier, node, id string, generation int64) (Version, error) { + return ReadVersion(q.QueryRowContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_versions v `+VersionJoins+` WHERE v.node_id=$1 AND v.revision_id=$2 AND v.generation=$3`, node, id, generation)) } -func Heads(ctx context.Context, q Querier, node, epoch string) ([]Version, error) { - rows, err := q.QueryContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_heads v `+VersionJoins+` WHERE v.node_id=$1 AND v.epoch=$2 ORDER BY v.revision_id`, node, epoch) +func Heads(ctx context.Context, q Querier, node string) ([]Version, error) { + rows, err := q.QueryContext(ctx, `SELECT `+VersionColumns+` FROM lpcc.machine_app_heads v `+VersionJoins+` WHERE v.node_id=$1 ORDER BY v.revision_id`, node) if err != nil { return nil, err } return ReadVersions(rows) } -func CleanupComplete(ctx context.Context, q Querier, node, epoch string, p schema.AppStartAfter) (bool, error) { +func CleanupComplete(ctx context.Context, q Querier, node string, p schema.AppStartAfter) (bool, error) { var yes bool - err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_completions WHERE node_id=$1 AND epoch=$2 AND revision_id=$3 AND generation=$4 AND phase='removed')`, node, epoch, p.RevisionID, p.Generation).Scan(&yes) + err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_completions WHERE node_id=$1 AND revision_id=$2 AND generation=$3 AND phase='removed')`, node, p.RevisionID, p.Generation).Scan(&yes) return yes, err } -func Snapshot(ctx context.Context, q Querier, node, epoch string) (*schema.AppAssignmentSetV1, error) { +func Snapshot(ctx context.Context, q Querier, node string) (*schema.AppAssignmentSetV1, error) { var gen int64 - err := q.QueryRowContext(ctx, `SELECT apps_generation FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2`, node, epoch).Scan(&gen) + err := q.QueryRowContext(ctx, `SELECT apps_generation FROM lpcc.machine_states WHERE node_id=$1`, node).Scan(&gen) if errors.Is(err, sql.ErrNoRows) || err == nil && gen == 0 { return nil, nil } if err != nil { return nil, err } - versions, err := Heads(ctx, q, node, epoch) + versions, err := Heads(ctx, q, node) if err != nil { return nil, err } - set := &schema.AppAssignmentSetV1{SchemaVersion: 1, NodeID: node, Epoch: epoch, Generation: gen, Entries: []schema.AppAssignment{}} + set := &schema.AppAssignmentSetV1{SchemaVersion: 1, NodeID: node, Generation: gen, Entries: []schema.AppAssignment{}} for _, v := range versions { // Keep completed removals in history, outside future desired snapshots. // A terminal artifact already published is never rewritten. @@ -100,7 +100,7 @@ func Snapshot(ctx context.Context, q Querier, node, epoch string) (*schema.AppAs } a := v.AppAssignment if a.StartAfter != nil { - a.StartAllowed, err = CleanupComplete(ctx, q, node, epoch, *a.StartAfter) + a.StartAllowed, err = CleanupComplete(ctx, q, node, *a.StartAfter) if err != nil { return nil, err } @@ -110,23 +110,23 @@ func Snapshot(ctx context.Context, q Querier, node, epoch string) (*schema.AppAs return set, nil } -func Append(ctx context.Context, tx *sql.Tx, node, epoch, actor string, a schema.AppAssignment) error { +func Append(ctx context.Context, tx *sql.Tx, node, actor string, a schema.AppAssignment) error { raw, err := json.Marshal(a) if err != nil { return err } - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_versions(node_id,epoch,revision_id,generation,intent,actor_id) VALUES($1,$2,$3,$4,$5,$6)`, node, epoch, a.RevisionID, a.Generation, string(raw), actor) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_versions(node_id,revision_id,generation,intent,actor_id) VALUES($1,$2,$3,$4,$5)`, node, a.RevisionID, a.Generation, string(raw), actor) return err } -func Bump(ctx context.Context, tx *sql.Tx, node, epoch string) error { - _, err := tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_generation=apps_generation+1,revision=revision+1,apps_error=NULL WHERE node_id=$1 AND epoch=$2`, node, epoch) +func Bump(ctx context.Context, tx *sql.Tx, node string) error { + _, err := tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_generation=apps_generation+1,revision=revision+1,apps_error=NULL WHERE node_id=$1`, node) return err } -func Pending(ctx context.Context, q Querier, node, epoch string) (bool, error) { +func Pending(ctx context.Context, q Querier, node string) (bool, error) { var yes bool - err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_heads v WHERE v.node_id=$1 AND v.epoch=$2 AND (v.intent->>'desired'='present' OR NOT EXISTS(SELECT FROM lpcc.machine_app_completions c WHERE c.node_id=v.node_id AND c.epoch=v.epoch AND c.revision_id=v.revision_id AND c.generation=v.generation AND c.phase='removed')))`, node, epoch).Scan(&yes) + err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_heads v WHERE v.node_id=$1 AND (v.intent->>'desired'='present' OR NOT EXISTS(SELECT FROM lpcc.machine_app_completions c WHERE c.node_id=v.node_id AND c.revision_id=v.revision_id AND c.generation=v.generation AND c.phase='removed')))`, node).Scan(&yes) return yes, err } @@ -146,6 +146,6 @@ func RecordDelivery(ctx context.Context, tx *sql.Tx, set *schema.AppAssignmentSe if err != nil { return err } - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_deliveries(node_id,epoch,apps_digest,bundle_sha256,apps_generation,entries,terminal) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING`, set.NodeID, set.Epoch, schema.Digest(raw), bundle, set.Generation, string(membership), terminal) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_app_deliveries(node_id,apps_digest,bundle_sha256,apps_generation,entries,terminal) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING`, set.NodeID, schema.Digest(raw), bundle, set.Generation, string(membership), terminal) return err } diff --git a/api/internal/controlplane/machineconfig.go b/api/internal/controlplane/machineconfig.go index 109c339..dad659b 100644 --- a/api/internal/controlplane/machineconfig.go +++ b/api/internal/controlplane/machineconfig.go @@ -16,6 +16,9 @@ func (s *Server) newConfigurationManager() *machineconfig.Manager { p := s.params return machineconfig.New(machineconfig.Config{APIURL: p.PublicAPIURL, DrainTimeout: p.TunnelDrainTimeout, StatusTTL: p.TunnelStatusTTL, RuntimeImage: p.RuntimeImage, NodeImage: p.RuntimeNodeImage, NodeDrainTimeout: &p.RuntimeNodeDrainTimeout, StopSignals: p.AppStopSignals, Connector: machineconfig.ConnectorConfig{Image: p.RuntimeConnectorImage, NodeAddresses: p.TunnelNodeAddresses}}, machineconfig.Dependencies{DB: s.db, Logger: s.logger, Onchain: func(ctx context.Context, m machineconfig.Machine) (onchain.Config, error) { + if m.Fingerprint != "" { + return loadInstallationOnchain(ctx, s.db, "$1", m.Fingerprint) + } return loadOnchain(ctx, s.db, m.NodeID) }, Exposure: func(raw json.RawMessage) (*machineconfig.Exposure, error) { @@ -28,5 +31,5 @@ func (s *Server) newConfigurationManager() *machineconfig.Manager { } func configurationMachine(m Machine) machineconfig.Machine { - return machineconfig.Machine{NodeID: m.NodeID, Epoch: m.Epoch, InstallDir: m.InstallDir, K3sVersion: m.K3sVersion, CredentialVersion: m.CredentialVersion, Terminal: m.Terminal} + return machineconfig.Machine{NodeID: m.NodeID, Fingerprint: m.Fingerprint, InstallDir: m.InstallDir, K3sVersion: m.K3sVersion, CredentialVersion: m.CredentialVersion, Terminal: m.Terminal} } diff --git a/api/internal/controlplane/machineconfig/apps.go b/api/internal/controlplane/machineconfig/apps.go index 0c8ed6b..964726f 100644 --- a/api/internal/controlplane/machineconfig/apps.go +++ b/api/internal/controlplane/machineconfig/apps.go @@ -11,8 +11,8 @@ import ( "github.com/livepeer/control-center/runtime/transport" ) -func DrainTarget(node, epoch string, state State) string { - return artifact.Digest([]byte(fmt.Sprintf("%s/%s/%d/%s/%s", node, epoch, state.Generation, state.PendingConfigDigest, state.Target))) +func DrainTarget(node string, state State) string { + return artifact.Digest([]byte(fmt.Sprintf("%s/%s/%d/%s/%s", node, node, state.Generation, state.PendingConfigDigest, state.Target))) } func (s *Manager) connectorSettings(m Machine, record *Record) { if m.Terminal { @@ -52,12 +52,12 @@ func (s *Manager) prepareApps(ctx context.Context, m *Desired, lookupErr error) query := `SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1` args := []any{m.NodeID} if m.Terminal { - query = `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2` - args = append(args, m.Epoch) + query = `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1` + args = append(args, m.NodeID) } if s.store.DB.QueryRowContext(ctx, query, args...).Scan(&prior) == nil { if files, e := artifact.Read(prior); e == nil { - if metadata, e := transport.ReadMetadata(files["runtime.json"]); e == nil && metadata.NodeID == m.NodeID && metadata.Epoch == m.Epoch { + if metadata, e := transport.ReadMetadata(files["runtime.json"]); e == nil && metadata.NodeID == m.NodeID { if old, e := appbundle.Read(files, metadata); e == nil { p = old } diff --git a/api/internal/controlplane/machineconfig/apps_test.go b/api/internal/controlplane/machineconfig/apps_test.go index dd78cf5..6b889d5 100644 --- a/api/internal/controlplane/machineconfig/apps_test.go +++ b/api/internal/controlplane/machineconfig/apps_test.go @@ -12,7 +12,7 @@ import ( ) func TestIndependentManagementAndFullWorkloadDigest(t *testing.T) { - m := Desired{Machine: Machine{NodeID: "lp-" + strings.Repeat("a", 16), Epoch: "22222222-2222-4222-8222-222222222222", CredentialVersion: 1, InstallDir: "/opt/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} + m := Desired{Machine: Machine{NodeID: strings.Repeat("a", 26), CredentialVersion: 1, InstallDir: "/opt/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} missing := m missing.RuntimeImage = "" if _, _, err := Build(missing); err == nil { @@ -73,9 +73,9 @@ func TestIndependentManagementAndFullWorkloadDigest(t *testing.T) { } func TestDrainProofDoesNotGainFreshnessFromDeliveryRetry(t *testing.T) { now := time.Now().UTC() - m := Machine{NodeID: "node", Epoch: "epoch"} + m := Machine{NodeID: "node"} state := State{Generation: 7, DrainRequested: true, DrainStartedAt: now.Add(-time.Hour), PendingConfigDigest: "target"} - r := Report{Generation: 7, Drained: true, Evidence: &contract.Evidence{Kind: "no_owner", Target: DrainTarget(m.NodeID, m.Epoch, state), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)}} + r := Report{Generation: 7, Drained: true, Evidence: &contract.Evidence{Kind: "no_owner", Target: DrainTarget(m.NodeID, state), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)}} if !validDrainEvidence(m, state, r, now) { t.Fatal("late confirmed completion rejected") } diff --git a/api/internal/controlplane/machineconfig/bundle_test.go b/api/internal/controlplane/machineconfig/bundle_test.go index 1f0b043..cd09c8d 100644 --- a/api/internal/controlplane/machineconfig/bundle_test.go +++ b/api/internal/controlplane/machineconfig/bundle_test.go @@ -13,7 +13,7 @@ import ( ) func TestConfigurationBundle(t *testing.T) { - m := Desired{Machine: Machine{NodeID: "lp-" + strings.Repeat("a", 16), Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64)} + m := Desired{Machine: Machine{NodeID: strings.Repeat("a", 26), CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64)} first, digest, err := Build(m) if err != nil { t.Fatal(err) diff --git a/api/internal/controlplane/machineconfig/commands.go b/api/internal/controlplane/machineconfig/commands.go index 21a16f0..3138597 100644 --- a/api/internal/controlplane/machineconfig/commands.go +++ b/api/internal/controlplane/machineconfig/commands.go @@ -9,26 +9,25 @@ import ( ) var ( - ErrNotFound = errors.New("machine not found") - ErrEnrollmentChanged = errors.New("machine enrollment changed") - ErrDrainChanged = errors.New("drain intent changed") - ErrDrainNotExpired = errors.New("drain deadline has not expired") + ErrNotFound = errors.New("machine not found") + ErrDrainChanged = errors.New("drain intent changed") + ErrDrainNotExpired = errors.New("drain deadline has not expired") ) type Change struct { - Epoch, Lifecycle string + NodeID, Lifecycle string Generation int64 Changed, AlreadyRemoved bool } // Remove participates in the caller's authorization and audit transaction. -func (s *Manager) Remove(ctx context.Context, tx *sql.Tx, node, epoch string, force bool) (Change, error) { - var current string - result := Change{Epoch: epoch, Lifecycle: "removed"} - err := tx.QueryRowContext(ctx, `SELECT enrollment_epoch::text FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(¤t) +func (s *Manager) Remove(ctx context.Context, tx *sql.Tx, node string, force bool) (Change, error) { + var present int + result := Change{NodeID: node, Lifecycle: "removed"} + err := tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&present) if errors.Is(err, sql.ErrNoRows) { var retired bool - err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.enrollments WHERE node_id=$1 AND epoch::text=$2 AND retired_at IS NOT NULL)`, node, epoch).Scan(&retired) + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.enrollments WHERE node_id=$1 AND retired_at IS NOT NULL)`, node).Scan(&retired) if err != nil { return result, err } @@ -41,17 +40,14 @@ func (s *Manager) Remove(ctx context.Context, tx *sql.Tx, node, epoch string, fo if err != nil { return result, err } - if current != epoch { - return result, ErrEnrollmentChanged - } if force { - _, err = tx.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2`, node, epoch) + _, err = tx.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1`, node) result.Changed = true return result, err } var raw []byte state := InitialState(false) - err = tx.QueryRowContext(ctx, `SELECT rollout FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 FOR UPDATE`, node, epoch).Scan(&raw) + err = tx.QueryRowContext(ctx, `SELECT rollout FROM lpcc.machine_states WHERE node_id=$1 FOR UPDATE`, node).Scan(&raw) if err == nil { err = json.Unmarshal(raw, &state) } else if errors.Is(err, sql.ErrNoRows) { @@ -70,28 +66,28 @@ func (s *Manager) Remove(ctx context.Context, tx *sql.Tx, node, epoch string, fo state.PendingConfigDigest = "" state.RolloutReason = "drain_pending" raw, _ = json.Marshal(state) - _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_states(node_id,epoch,state,rollout) VALUES($1,$2,'{}',$3) ON CONFLICT(node_id,epoch) DO UPDATE SET rollout=EXCLUDED.rollout,revision=lpcc.machine_states.revision+1,next_attempt_at=now()`, node, epoch, string(raw)) + _, err = tx.ExecContext(ctx, `INSERT INTO lpcc.machine_states(node_id,state,rollout) VALUES($1,'{}',$2) ON CONFLICT(node_id) DO UPDATE SET rollout=EXCLUDED.rollout,revision=lpcc.machine_states.revision+1,next_attempt_at=now()`, node, string(raw)) } if err == nil { - _, err = tx.ExecContext(ctx, `SELECT lpcc.remove_machine_apps($1,$2,'system:machine-removal')`, node, epoch) + _, err = tx.ExecContext(ctx, `SELECT lpcc.remove_machine_apps($1,'system:machine-removal')`, node) } result.Lifecycle = "draining" result.Generation = state.Generation return result, err } -func (s *Manager) RetryDrain(ctx context.Context, tx *sql.Tx, node, epoch string, generation int64) (Change, error) { - result := Change{Epoch: epoch} +func (s *Manager) RetryDrain(ctx context.Context, tx *sql.Tx, node string, generation int64) (Change, error) { + result := Change{NodeID: node} var present int - err := tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch::text=$2 FOR UPDATE`, node, epoch).Scan(&present) + err := tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&present) if errors.Is(err, sql.ErrNoRows) { - return result, ErrEnrollmentChanged + return result, ErrNotFound } if err != nil { return result, err } var raw []byte - if err = tx.QueryRowContext(ctx, `SELECT rollout FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 FOR UPDATE`, node, epoch).Scan(&raw); err != nil { + if err = tx.QueryRowContext(ctx, `SELECT rollout FROM lpcc.machine_states WHERE node_id=$1 FOR UPDATE`, node).Scan(&raw); err != nil { return result, err } var state State @@ -108,7 +104,7 @@ func (s *Manager) RetryDrain(ctx context.Context, tx *sql.Tx, node, epoch string state.DrainStartedAt = time.Now().UTC() state.RolloutReason = "drain_pending" raw, _ = json.Marshal(state) - _, err = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET rollout=$3,revision=revision+1,next_attempt_at=now() WHERE node_id=$1 AND epoch=$2`, node, epoch, string(raw)) + _, err = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET rollout=$2,revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, node, string(raw)) result.Changed = true result.Lifecycle = state.Lifecycle result.Generation = state.Generation @@ -117,7 +113,7 @@ func (s *Manager) RetryDrain(ctx context.Context, tx *sql.Tx, node, epoch string // FenceCredentialRefresh runs in the credential transaction, after updating the // enrollment. A waiting state writer must recheck the changed shared revision. -func (s *Manager) FenceCredentialRefresh(ctx context.Context, tx *sql.Tx, node, epoch string) error { - _, err := tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1 AND epoch=$2`, node, epoch) +func (s *Manager) FenceCredentialRefresh(ctx context.Context, tx *sql.Tx, node string) error { + _, err := tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, node) return err } diff --git a/api/internal/controlplane/machineconfig/manager.go b/api/internal/controlplane/machineconfig/manager.go index c4f0eb2..e0b1ab8 100644 --- a/api/internal/controlplane/machineconfig/manager.go +++ b/api/internal/controlplane/machineconfig/manager.go @@ -78,14 +78,14 @@ func (s *Manager) drainTimeout() time.Duration { } func (s *Manager) Reconcile(ctx context.Context) error { - rows, err := s.store.DB.QueryContext(ctx, `SELECT node_id,epoch::text,install_dir,k3s_version,credential_version,retired_at IS NOT NULL FROM lpcc.enrollments ORDER BY node_id,epoch`) + rows, err := s.store.DB.QueryContext(ctx, `SELECT node_id,install_dir,k3s_version,credential_version,retired_at IS NOT NULL FROM lpcc.enrollments ORDER BY node_id`) if err != nil { return err } var machines []Machine for rows.Next() { var m Machine - if err = rows.Scan(&m.NodeID, &m.Epoch, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal); err != nil { + if err = rows.Scan(&m.NodeID, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal); err != nil { rows.Close() return err } @@ -105,7 +105,7 @@ func (s *Manager) Reconcile(ctx context.Context) error { } func (s *Manager) reconcile(ctx context.Context, m Machine) error { - record, err := s.store.Load(ctx, m.NodeID, m.Epoch) + record, err := s.store.Load(ctx, m.NodeID) var lease *Lease defer func() { if lease != nil { @@ -158,7 +158,7 @@ func (s *Manager) reconcile(ctx context.Context, m Machine) error { } if removed { m.Terminal = true - lease.Record, e = s.store.Load(ctx, m.NodeID, m.Epoch) + lease.Record, e = s.store.Load(ctx, m.NodeID) if e != nil { return e } @@ -178,7 +178,7 @@ func (s *Manager) reconcile(ctx context.Context, m Machine) error { // An enrolled machine with no assignments still needs an authoritative empty intent. // Reserve its first generation before delivery, so the first edit advances beyond it. var revision int64 - err = s.store.DB.QueryRowContext(ctx, `UPDATE lpcc.machine_states SET apps_generation=1,revision=revision+1 WHERE node_id=$1 AND epoch=$2 AND revision=$3 AND apps_generation=0 AND EXISTS(SELECT FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2 AND credential_version=$4) RETURNING revision`, m.NodeID, m.Epoch, record.Revision, m.CredentialVersion).Scan(&revision) + err = s.store.DB.QueryRowContext(ctx, `UPDATE lpcc.machine_states SET apps_generation=1,revision=revision+1 WHERE node_id=$1 AND revision=$2 AND apps_generation=0 AND EXISTS(SELECT FROM lpcc.enrollments WHERE node_id=$1 AND credential_version=$3) RETURNING revision`, m.NodeID, record.Revision, m.CredentialVersion).Scan(&revision) if err == nil { record.Revision = revision } else if !errors.Is(err, sql.ErrNoRows) { @@ -187,16 +187,16 @@ func (s *Manager) reconcile(ctx context.Context, m Machine) error { desired := s.Desired(m, record.State, exposure) if m.Terminal { var prior []byte - if s.store.DB.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&prior) == nil { + if s.store.DB.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1`, m.NodeID).Scan(&prior) == nil { desired.RetainedFiles, _ = artifact.Read(prior) } } - desired.Apps, err = machineapps.Snapshot(ctx, s.store.DB, m.NodeID, m.Epoch) + desired.Apps, err = machineapps.Snapshot(ctx, s.store.DB, m.NodeID) s.prepareApps(ctx, &desired, err) data, digest, err := s.deps.Build(desired) if err != nil { s.deps.Logger.Error("keeping previous configuration", "node_id", m.NodeID, "reason", "generation_failed") - _, _ = s.store.DB.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_error='generation_failed' WHERE node_id=$1 AND epoch=$2 AND revision=$3`, m.NodeID, m.Epoch, record.Revision) + _, _ = s.store.DB.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_error='generation_failed' WHERE node_id=$1 AND revision=$2`, m.NodeID, record.Revision) return nil } return s.publish(ctx, m, record.Revision, data, digest, desired.Apps, desired.AppsError) @@ -268,9 +268,9 @@ func (s *Manager) publish(ctx context.Context, m Machine, revision int64, data [ defer tx.Rollback() var present int if m.Terminal { - err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2 AND credential_version=$3 AND retired_at IS NOT NULL FOR UPDATE`, m.NodeID, m.Epoch, m.CredentialVersion).Scan(&present) + err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.enrollments WHERE node_id=$1 AND credential_version=$2 AND retired_at IS NOT NULL FOR UPDATE`, m.NodeID, m.CredentialVersion).Scan(&present) } else { - err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$3 FOR UPDATE`, m.NodeID, m.Epoch, m.CredentialVersion).Scan(&present) + err = tx.QueryRowContext(ctx, `SELECT 1 FROM lpcc.machines WHERE node_id=$1 AND credential_version=$2 FOR UPDATE`, m.NodeID, m.CredentialVersion).Scan(&present) } if errors.Is(err, sql.ErrNoRows) { return nil @@ -285,7 +285,7 @@ func (s *Manager) publish(ctx context.Context, m Machine, revision int64, data [ } } var current int64 - err = tx.QueryRowContext(ctx, `SELECT revision FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 FOR SHARE`, m.NodeID, m.Epoch).Scan(¤t) + err = tx.QueryRowContext(ctx, `SELECT revision FROM lpcc.machine_states WHERE node_id=$1 FOR SHARE`, m.NodeID).Scan(¤t) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } @@ -293,7 +293,7 @@ func (s *Manager) publish(ctx context.Context, m Machine, revision int64, data [ return nil } if m.Terminal { - result, e := tx.ExecContext(ctx, `UPDATE lpcc.enrollments SET terminal_bundle=$3,terminal_sha256=$4 WHERE node_id=$1 AND epoch=$2 AND terminal_bundle IS NULL`, m.NodeID, m.Epoch, data, digest) + result, e := tx.ExecContext(ctx, `UPDATE lpcc.enrollments SET terminal_bundle=$2,terminal_sha256=$3 WHERE node_id=$1 AND terminal_bundle IS NULL`, m.NodeID, data, digest) if e != nil { return e } @@ -307,7 +307,7 @@ func (s *Manager) publish(ctx context.Context, m Machine, revision int64, data [ if err = machineapps.RecordDelivery(ctx, tx, apps, digest, m.Terminal); err != nil { return err } - if _, err = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_error=NULLIF($3,'') WHERE node_id=$1 AND epoch=$2 AND apps_error IS DISTINCT FROM NULLIF($3,'')`, m.NodeID, m.Epoch, appsError); err != nil { + if _, err = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET apps_error=NULLIF($2,'') WHERE node_id=$1 AND apps_error IS DISTINCT FROM NULLIF($2,'')`, m.NodeID, appsError); err != nil { return err } return tx.Commit() diff --git a/api/internal/controlplane/machineconfig/observations.go b/api/internal/controlplane/machineconfig/observations.go index 874e9d0..b6e0ab6 100644 --- a/api/internal/controlplane/machineconfig/observations.go +++ b/api/internal/controlplane/machineconfig/observations.go @@ -30,7 +30,7 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) } if p.Mode == "onchain" { var known bool - err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.onchain_grants WHERE grant_id::text=$1 AND node_id=$2 AND epoch=$3 AND onchain_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, m.Epoch, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) + err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.onchain_grants WHERE grant_id::text=$1 AND node_id=$2 AND onchain_generation=$3 AND config_digest=$4 AND pod_uid=$5 AND revoked_at IS NULL)`, p.GrantID, m.NodeID, p.Generation, r.ConfigDigest, p.PodUID).Scan(&known) if err != nil { return err } @@ -50,7 +50,7 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) stages := []*contract.StageIdentity{r.Downloaded} if r.Downloaded != nil && r.Downloaded.AppsDigest != "" { var known bool - err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND apps_digest=$3 AND bundle_sha256=$4)`, m.NodeID, m.Epoch, r.Downloaded.AppsDigest, strings.TrimPrefix(r.Downloaded.ArtifactDigest, "sha256:")).Scan(&known) + err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND apps_digest=$2 AND bundle_sha256=$3)`, m.NodeID, r.Downloaded.AppsDigest, strings.TrimPrefix(r.Downloaded.ArtifactDigest, "sha256:")).Scan(&known) if err != nil { return err } @@ -62,8 +62,8 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) a := r.Apps if m.Terminal && r.Component == "runner" { var bound bool - err := s.store.DB.QueryRowContext(ctx, `SELECT NOT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND terminal) - OR EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND terminal AND apps_generation=$3 AND apps_digest=$4)`, m.NodeID, m.Epoch, a.DesiredGeneration, a.DesiredDigest).Scan(&bound) + err := s.store.DB.QueryRowContext(ctx, `SELECT NOT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND terminal) + OR EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND terminal AND apps_generation=$2 AND apps_digest=$3)`, m.NodeID, a.DesiredGeneration, a.DesiredDigest).Scan(&bound) if err != nil { return err } @@ -106,8 +106,8 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) } b, _ := json.Marshal(members) var valid bool - err := s.store.DB.QueryRowContext(ctx, `SELECT NOT EXISTS(SELECT FROM jsonb_to_recordset($3::jsonb) AS i(revision_id text,generation bigint,activation_generation bigint) - WHERE NOT EXISTS(SELECT FROM lpcc.machine_app_deliveries d WHERE d.node_id=$1 AND d.epoch=$2 AND d.entries @> jsonb_build_array(jsonb_build_object('revision_id',i.revision_id,'generation',i.generation,'activation_generation',i.activation_generation))))`, m.NodeID, m.Epoch, string(b)).Scan(&valid) + err := s.store.DB.QueryRowContext(ctx, `SELECT NOT EXISTS(SELECT FROM jsonb_to_recordset($2::jsonb) AS i(revision_id text,generation bigint,activation_generation bigint) + WHERE NOT EXISTS(SELECT FROM lpcc.machine_app_deliveries d WHERE d.node_id=$1 AND d.entries @> jsonb_build_array(jsonb_build_object('revision_id',i.revision_id,'generation',i.generation,'activation_generation',i.activation_generation))))`, m.NodeID, string(b)).Scan(&valid) if err != nil { return err } @@ -129,7 +129,7 @@ func (s *Manager) validateObservations(ctx context.Context, m Machine, r Report) continue } var known bool - err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND apps_digest=$3 AND ($4::bigint=0 OR apps_generation=$4))`, m.NodeID, m.Epoch, stage.AppsDigest, stage.Generation).Scan(&known) + err := s.store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND apps_digest=$2 AND ($3::bigint=0 OR apps_generation=$3))`, m.NodeID, stage.AppsDigest, stage.Generation).Scan(&known) if err != nil { return err } diff --git a/api/internal/controlplane/machineconfig/onchain_test.go b/api/internal/controlplane/machineconfig/onchain_test.go index 90afa75..ea43b07 100644 --- a/api/internal/controlplane/machineconfig/onchain_test.go +++ b/api/internal/controlplane/machineconfig/onchain_test.go @@ -19,7 +19,7 @@ import ( func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) { c := onchain.Config{Version: 1, Generation: 1, CredentialRevision: 1, Mode: "onchain", Network: "custom", ChainID: 1, Controller: "0x" + strings.Repeat("1", 40), Recipient: "0x" + strings.Repeat("2", 40), RPCSecret: "rpc-v1", RedeemerURL: "https://redeemer.example", RPCGrants: []string{"10.0.0.2:443"}, RedeemerGrants: []string{"10.0.0.3:443"}, WeiPerUSD: "100", TicketFaceValue: "100", TicketWinProb: "1", MaxPendingTickets: 100, MaxTicketsPerRecipient: 10} - m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} + m := Desired{Machine: Machine{NodeID: "aaaaaaaaaaaaaaaaaaaaaaaaaa", CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: c, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), NodeImage: "registry.invalid/node@sha256:" + strings.Repeat("b", 64)} b, d, e := Build(m) if e != nil { t.Fatal(e) @@ -82,7 +82,7 @@ func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) t.Fatal("management refresh did not schedule Node drain and replacement") } refreshed = m - refreshed.Epoch = "22222222-2222-4222-8222-222222222222" + refreshed.NodeID = "22222222-2222-4222-8222-222222222222" if Digest(refreshed) == original { t.Fatal("re-enrollment reused a previous lifetime's Node workload") } diff --git a/api/internal/controlplane/machineconfig/reports.go b/api/internal/controlplane/machineconfig/reports.go index f9ef348..8b0e4b7 100644 --- a/api/internal/controlplane/machineconfig/reports.go +++ b/api/internal/controlplane/machineconfig/reports.go @@ -20,7 +20,7 @@ var ErrReportOrder = errors.New("report ordering state must be restored") // rejects observations ahead of the persisted machine rollout. It returns // whether the observation can advance an outstanding drain. func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (bool, error) { - record, err := s.store.Load(ctx, m.NodeID, m.Epoch) + record, err := s.store.Load(ctx, m.NodeID) if err != nil && !errors.Is(err, sql.ErrNoRows) { return false, err } @@ -64,16 +64,16 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b } } raw, _ := json.Marshal(report) - result, err := s.store.DB.ExecContext(ctx, `INSERT INTO lpcc.machine_reports(node_id,epoch,component,generation,credential_version,report) - SELECT $1,$2,$3,$4,$5,$6 WHERE EXISTS(SELECT FROM lpcc.enrollments e WHERE e.node_id=$1 AND e.epoch=$2 AND e.credential_version=$5 - AND ((NOT $7 AND e.retired_at IS NULL) OR ($7 AND e.retired_at IS NOT NULL AND e.terminal_sha256 IS NOT NULL))) - ON CONFLICT(node_id,epoch,component) DO UPDATE SET generation=EXCLUDED.generation,credential_version=EXCLUDED.credential_version,report=EXCLUDED.report,received_at=now() + result, err := s.store.DB.ExecContext(ctx, `INSERT INTO lpcc.machine_reports(node_id,component,generation,credential_version,report) + SELECT $1,$2,$3,$4,$5 WHERE EXISTS(SELECT FROM lpcc.enrollments e WHERE e.node_id=$1 AND e.credential_version=$4 + AND ((NOT $6 AND e.retired_at IS NULL) OR ($6 AND e.retired_at IS NOT NULL AND e.terminal_sha256 IS NOT NULL))) + ON CONFLICT(node_id,component) DO UPDATE SET generation=EXCLUDED.generation,credential_version=EXCLUDED.credential_version,report=EXCLUDED.report,received_at=now() WHERE lpcc.machine_reports.generation<=EXCLUDED.generation AND lpcc.machine_reports.credential_version<=EXCLUDED.credential_version - AND ($3<>'runner' OR + AND ($2<>'runner' OR (COALESCE((lpcc.machine_reports.report#>>'{apps,desired_generation}')::bigint,0)<=COALESCE((EXCLUDED.report#>>'{apps,desired_generation}')::bigint,0) AND (COALESCE((lpcc.machine_reports.report#>>'{apps,desired_generation}')::bigint,0)<>COALESCE((EXCLUDED.report#>>'{apps,desired_generation}')::bigint,0) OR COALESCE(lpcc.machine_reports.report#>>'{apps,desired_digest}','')=COALESCE(EXCLUDED.report#>>'{apps,desired_digest}','')))) - AND (lpcc.machine_reports.credential_version>'sequence')::numeric,0)>'sequence')::numeric,0))`, m.NodeID, m.Epoch, report.Component, report.Generation, m.CredentialVersion, string(raw), m.Terminal) + AND (lpcc.machine_reports.credential_version>'sequence')::numeric,0)>'sequence')::numeric,0))`, m.NodeID, report.Component, report.Generation, m.CredentialVersion, string(raw), m.Terminal) if err != nil { return false, err } @@ -101,7 +101,7 @@ func (s *Manager) RecordReport(ctx context.Context, m Machine, report Report) (b func validDrainEvidence(m Machine, state State, report Report, now time.Time) bool { e := report.Evidence - if e == nil || !report.Drained || !state.DrainRequested || report.Generation != state.Generation || e.Target != DrainTarget(m.NodeID, m.Epoch, state) || e.WithdrawalID == "" || len(e.WithdrawalID) > 64 || e.Kind != "no_owner" { + if e == nil || !report.Drained || !state.DrainRequested || report.Generation != state.Generation || e.Target != DrainTarget(m.NodeID, state) || e.WithdrawalID == "" || len(e.WithdrawalID) > 64 || e.Kind != "no_owner" { return false } if e.ObservedAt.Before(state.DrainStartedAt) || e.ObservedAt.After(now.Add(5*time.Second)) || !now.Before(e.ExpiresAt) || !e.ExpiresAt.After(e.ObservedAt) || e.ExpiresAt.Sub(e.ObservedAt) > time.Minute { diff --git a/api/internal/controlplane/machineconfig/rollout.go b/api/internal/controlplane/machineconfig/rollout.go index 98a6fca..fb33e69 100644 --- a/api/internal/controlplane/machineconfig/rollout.go +++ b/api/internal/controlplane/machineconfig/rollout.go @@ -192,7 +192,7 @@ func (s *Manager) removalComplete(ctx context.Context, m Machine, state *State) // A timely Node drain remains complete while slower app cleanup runs. state.DrainedGeneration = state.Generation } - pending, err := machineapps.Pending(ctx, s.store.DB, m.NodeID, m.Epoch) + pending, err := machineapps.Pending(ctx, s.store.DB, m.NodeID) if err != nil || pending { state.RolloutReason = "app_cleanup_pending" return false, err @@ -206,7 +206,7 @@ func (s *Manager) finishRemoval(ctx context.Context, l *Lease) (bool, error) { if err != nil || !done { return false, err } - result, err := s.store.DB.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 AND credential_version=$5 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND lease_id=$3 AND revision=$4 AND lease_until>now())`, l.Machine.NodeID, l.Machine.Epoch, l.ID, l.Revision, l.Machine.CredentialVersion) + result, err := s.store.DB.ExecContext(ctx, `DELETE FROM lpcc.machines WHERE node_id=$1 AND credential_version=$4 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND lease_id=$2 AND revision=$3 AND lease_until>now())`, l.Machine.NodeID, l.ID, l.Revision, l.Machine.CredentialVersion) if err != nil { return false, err } diff --git a/api/internal/controlplane/machineconfig/runtime.go b/api/internal/controlplane/machineconfig/runtime.go index 0c65734..6b337c4 100644 --- a/api/internal/controlplane/machineconfig/runtime.go +++ b/api/internal/controlplane/machineconfig/runtime.go @@ -27,7 +27,7 @@ func templateValues(m Desired) *strings.Replacer { if strings.HasPrefix(m.ControlAPIURL, "http://") { mode = "development-http" } - return strings.NewReplacer("@RUNTIME_IMAGE@", m.RuntimeImage, "@CONTROL_TRANSPORT@", mode, "@NODE_ID@", m.NodeID, "@ENROLLMENT_EPOCH@", m.Epoch, "@MANAGEMENT_CREDENTIAL_VERSION@", fmt.Sprint(m.CredentialVersion), "@INSTALL_DIR@", m.InstallDir, "@K3S_VERSION@", m.K3sVersion, "@SERVICE_URL@", service, "@PROXY_URL_TEMPLATE@", proxy) + return strings.NewReplacer("@RUNTIME_IMAGE@", m.RuntimeImage, "@CONTROL_TRANSPORT@", mode, "@NODE_ID@", m.NodeID, "@MANAGEMENT_CREDENTIAL_VERSION@", fmt.Sprint(m.CredentialVersion), "@INSTALL_DIR@", m.InstallDir, "@K3S_VERSION@", m.K3sVersion, "@SERVICE_URL@", service, "@PROXY_URL_TEMPLATE@", proxy) } func orchestratorConfiguration(m Desired) string { if m.State.HeldOrchestrator != "" { @@ -95,7 +95,7 @@ func renderMachineTemplate(raw string, m Desired) string { type Runtime = contract.Metadata func DesiredRuntime(m Desired) Runtime { - d := Runtime{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Generation: 1, Terminal: m.Terminal, ConfigDigest: Digest(m), ServiceURL: PrivateOrchestrator, APIURL: m.ControlAPIURL} + d := Runtime{NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, Generation: 1, Terminal: m.Terminal, ConfigDigest: Digest(m), ServiceURL: PrivateOrchestrator, APIURL: m.ControlAPIURL} d.Onchain = effectiveOnchain(m) if d.Onchain.Version == 0 { d.Onchain = onchain.Offchain() @@ -113,7 +113,7 @@ func DesiredRuntime(m Desired) Runtime { d.RequestedAppsGeneration = m.RequestedAppsGeneration d.DrainStartedAt = m.State.DrainStartedAt if d.DrainRequested { - d.DrainTarget = DrainTarget(m.NodeID, m.Epoch, m.State) + d.DrainTarget = DrainTarget(m.NodeID, m.State) if m.DrainTimeout > 0 { d.DrainDeadline = m.State.DrainStartedAt.Add(m.DrainTimeout) } diff --git a/api/internal/controlplane/machineconfig/store.go b/api/internal/controlplane/machineconfig/store.go index b78ab87..e5544c8 100644 --- a/api/internal/controlplane/machineconfig/store.go +++ b/api/internal/controlplane/machineconfig/store.go @@ -22,10 +22,10 @@ type Record struct { type Store struct{ DB *sql.DB } -func (s Store) Load(ctx context.Context, node, epoch string) (Record, error) { +func (s Store) Load(ctx context.Context, node string) (Record, error) { var r Record var raw []byte - err := s.DB.QueryRowContext(ctx, `SELECT s.rollout,s.state,s.revision,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.machine_states s JOIN lpcc.enrollments e USING(node_id,epoch) WHERE s.node_id=$1 AND s.epoch=$2`, node, epoch).Scan(&raw, &r.Routing, &r.Revision, &r.CredentialVersion, &r.Terminal) + err := s.DB.QueryRowContext(ctx, `SELECT s.rollout,s.state,s.revision,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.machine_states s JOIN lpcc.enrollments e USING(node_id) WHERE s.node_id=$1`, node).Scan(&raw, &r.Routing, &r.Revision, &r.CredentialVersion, &r.Terminal) if err == nil { err = json.Unmarshal(raw, &r.State) } @@ -45,16 +45,16 @@ func (s Store) Claim(ctx context.Context, m Machine, initial json.RawMessage, du initial = json.RawMessage(`{}`) } state, _ := json.Marshal(InitialState(m.Terminal)) - insert := `INSERT INTO lpcc.machine_states(node_id,epoch,state,rollout) SELECT $1,$2,$3,$4 FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 FOR KEY SHARE ON CONFLICT DO NOTHING` + insert := `INSERT INTO lpcc.machine_states(node_id,state,rollout) SELECT $1,$2,$3 FROM lpcc.machines WHERE node_id=$1 FOR KEY SHARE ON CONFLICT DO NOTHING` if m.Terminal { - insert = `INSERT INTO lpcc.machine_states(node_id,epoch,state,rollout) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING` + insert = `INSERT INTO lpcc.machine_states(node_id,state,rollout) VALUES($1,$2,$3) ON CONFLICT DO NOTHING` } - if _, err := s.DB.ExecContext(ctx, insert, m.NodeID, m.Epoch, initial, string(state)); err != nil { + if _, err := s.DB.ExecContext(ctx, insert, m.NodeID, initial, string(state)); err != nil { return nil, err } l := &Lease{Machine: m, ID: uuid.New().String(), store: s} var raw []byte - err := s.DB.QueryRowContext(ctx, `UPDATE lpcc.machine_states SET lease_id=$3,lease_until=now()+interval '90 seconds' WHERE node_id=$1 AND epoch=$2 AND (NOT $4 OR next_attempt_at<=now()) AND (lease_until IS NULL OR lease_untilnow() AND (NOT $7 OR rollout->>'lifecycle'='active') AND EXISTS(SELECT FROM lpcc.enrollments e WHERE e.node_id=$1 AND e.epoch=$2 AND e.credential_version=$8) RETURNING revision` - args := []any{l.Machine.NodeID, l.Machine.Epoch, l.ID, routing, l.Revision, string(raw), active, l.Machine.CredentialVersion} + query := `UPDATE lpcc.machine_states SET state=$3,rollout=$5,revision=revision+1,lease_until=now()+interval '90 seconds' WHERE node_id=$1 AND lease_id=$2 AND revision=$4 AND lease_until>now() AND (NOT $6 OR rollout->>'lifecycle'='active') AND EXISTS(SELECT FROM lpcc.enrollments e WHERE e.node_id=$1 AND e.credential_version=$7) RETURNING revision` + args := []any{l.Machine.NodeID, l.ID, routing, l.Revision, string(raw), active, l.Machine.CredentialVersion} var row *sql.Row if tx == nil { row = l.store.DB.QueryRowContext(ctx, query, args...) @@ -106,7 +106,7 @@ func (l *Lease) Save(ctx context.Context) error { func (l *Lease) Release(ctx context.Context) { cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) defer cancel() - _, _ = l.store.DB.ExecContext(cleanup, `UPDATE lpcc.machine_states SET lease_id=NULL,lease_until=NULL WHERE node_id=$1 AND epoch=$2 AND lease_id=$3`, l.Machine.NodeID, l.Machine.Epoch, l.ID) + _, _ = l.store.DB.ExecContext(cleanup, `UPDATE lpcc.machine_states SET lease_id=NULL,lease_until=NULL WHERE node_id=$1 AND lease_id=$2`, l.Machine.NodeID, l.ID) } func (l *Lease) Finish(ctx context.Context, failed bool) { @@ -114,14 +114,14 @@ func (l *Lease) Finish(ctx context.Context, failed bool) { if failed { delay = 5 } - _, _ = l.store.DB.ExecContext(ctx, `UPDATE lpcc.machine_states SET lease_id=NULL,lease_until=NULL,failures=CASE WHEN $4 THEN LEAST(failures+1,8) ELSE 0 END,next_attempt_at=now()+make_interval(secs=>LEAST(300,$5*power(2,CASE WHEN $4 THEN LEAST(failures,6) ELSE 0 END))+random()) WHERE node_id=$1 AND epoch=$2 AND lease_id=$3`, l.Machine.NodeID, l.Machine.Epoch, l.ID, failed, delay) + _, _ = l.store.DB.ExecContext(ctx, `UPDATE lpcc.machine_states SET lease_id=NULL,lease_until=NULL,failures=CASE WHEN $3 THEN LEAST(failures+1,8) ELSE 0 END,next_attempt_at=now()+make_interval(secs=>LEAST(300,$4*power(2,CASE WHEN $3 THEN LEAST(failures,6) ELSE 0 END))+random()) WHERE node_id=$1 AND lease_id=$2`, l.Machine.NodeID, l.ID, failed, delay) } func (s Store) Report(ctx context.Context, m Machine, component string) (Report, time.Time, error) { var r Report var raw []byte var at time.Time - err := s.DB.QueryRowContext(ctx, `SELECT report,received_at FROM lpcc.machine_reports WHERE node_id=$1 AND epoch=$2 AND component=$3 AND credential_version=$4`, m.NodeID, m.Epoch, component, m.CredentialVersion).Scan(&raw, &at) + err := s.DB.QueryRowContext(ctx, `SELECT report,received_at FROM lpcc.machine_reports WHERE node_id=$1 AND component=$2 AND credential_version=$3`, m.NodeID, component, m.CredentialVersion).Scan(&raw, &at) if err == nil { err = json.Unmarshal(raw, &r) at = ObservationTime(r, at) diff --git a/api/internal/controlplane/machineconfig/system_test.go b/api/internal/controlplane/machineconfig/system_test.go index 3c32dac..7ffc6b1 100644 --- a/api/internal/controlplane/machineconfig/system_test.go +++ b/api/internal/controlplane/machineconfig/system_test.go @@ -13,7 +13,7 @@ import ( ) func TestSystemPeersRetainTerminalCleanupAndScopedCredentials(t *testing.T) { - m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "22222222-2222-4222-8222-222222222222", CredentialVersion: 1, InstallDir: "/opt/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), Connector: ConnectorConfig{Image: "registry.invalid/connector@sha256:" + strings.Repeat("b", 64)}, State: State{Lifecycle: "active"}, Exposure: &Exposure{TunnelID: "tunnel", ServiceURL: "https://machine.example", IngressDigest: "ingress", CredentialGeneration: 4, ProviderVersion: 8}} + m := Desired{Machine: Machine{NodeID: "vkvkvkvkvkvkuaaaaaaaaaaaaa", CredentialVersion: 1, InstallDir: "/opt/livepeer", K3sVersion: "v1.37.2+k3s1"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), Connector: ConnectorConfig{Image: "registry.invalid/connector@sha256:" + strings.Repeat("b", 64)}, State: State{Lifecycle: "active"}, Exposure: &Exposure{TunnelID: "tunnel", ServiceURL: "https://machine.example", IngressDigest: "ingress", CredentialGeneration: 4, ProviderVersion: 8}} build := func(m Desired) map[string][]byte { data, _, err := Build(m) if err != nil { @@ -109,7 +109,7 @@ func TestSystemPeersRetainTerminalCleanupAndScopedCredentials(t *testing.T) { func TestProxyRoutingFollowsHeldNodeConfiguration(t *testing.T) { { - m := Desired{Machine: Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", InstallDir: "/opt/livepeer"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), Connector: ConnectorConfig{Image: "registry.invalid/connector@sha256:" + strings.Repeat("b", 64)}, State: State{Lifecycle: "active"}} + m := Desired{Machine: Machine{NodeID: "vkvkvkvkvkvkuaaaaaaaaaaaaa", InstallDir: "/opt/livepeer"}, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64), Connector: ConnectorConfig{Image: "registry.invalid/connector@sha256:" + strings.Repeat("b", 64)}, State: State{Lifecycle: "active"}} build := func() map[string][]byte { t.Helper() bundle, _, err := Build(m) @@ -124,23 +124,23 @@ func TestProxyRoutingFollowsHeldNodeConfiguration(t *testing.T) { } prefix, nodeFile, proxyFile := "system/", "node/orchestrator.yaml", "connector/tunnel.yaml" private := build() - m.Exposure = &Exposure{TunnelID: "tunnel", ServiceURL: "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.a.invalid", ProxyURLTemplate: "https://{proxy}.lp-aaaaaaaaaaaaaaaa.a.invalid", IngressDigest: "ingress"} + m.Exposure = &Exposure{TunnelID: "tunnel", ServiceURL: "https://api-aaaaaaa.vkvkvkvkvkvkuaaaaaaaaaaaaa.a.invalid", ProxyURLTemplate: "https://{proxy}.vkvkvkvkvkvkuaaaaaaaaaaaaa.a.invalid", IngressDigest: "ingress"} a := build() if !strings.Contains(string(a[prefix+nodeFile]), `APIOriginURL = "`+PrivateOrchestrator+`"`) { t.Fatal("public Node routing omitted the private API origin") } m.State.HeldOrchestrator = string(a[prefix+nodeFile]) - m.Exposure.ServiceURL = "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.b.invalid" - m.Exposure.ProxyURLTemplate = "https://{proxy}.lp-aaaaaaaaaaaaaaaa.b.invalid" + m.Exposure.ServiceURL = "https://api-aaaaaaa.vkvkvkvkvkvkuaaaaaaaaaaaaa.b.invalid" + m.Exposure.ProxyURLTemplate = "https://{proxy}.vkvkvkvkvkvkuaaaaaaaaaaaaa.b.invalid" for _, held := range []string{m.State.HeldOrchestrator, string(private[prefix+nodeFile])} { m.State.HeldOrchestrator = held files := build() manifest := string(files[prefix+proxyFile]) _, manifest, _ = strings.Cut(manifest, "- name: node-proxy\n") - if strings.Contains(manifest, "lp-aaaaaaaaaaaaaaaa.b.invalid") || !strings.Contains(manifest, "--service-url") { + if strings.Contains(manifest, "vkvkvkvkvkvkuaaaaaaaaaaaaa.b.invalid") || !strings.Contains(manifest, "--service-url") { t.Fatal("guard advanced beyond held Node configuration", manifest) } - if strings.Contains(held, "lp-aaaaaaaaaaaaaaaa.a.invalid") && !strings.Contains(manifest, "https://{proxy}.lp-aaaaaaaaaaaaaaaa.a.invalid") { + if strings.Contains(held, "vkvkvkvkvkvkuaaaaaaaaaaaaa.a.invalid") && !strings.Contains(manifest, "https://{proxy}.vkvkvkvkvkvkuaaaaaaaaaaaaa.a.invalid") { t.Fatal("guard lost held public proxy template") } } diff --git a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml index 478061a..ca225f2 100644 --- a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml +++ b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml @@ -87,7 +87,6 @@ spec: template: metadata: annotations: - livepeer.io/enrollment-epoch: '@ENROLLMENT_EPOCH@' livepeer.io/credential-version: '@MANAGEMENT_CREDENTIAL_VERSION@' livepeer.io/config-sha256: '@ORCHESTRATOR_DIGEST@' labels: diff --git a/api/internal/controlplane/machineconfig/types.go b/api/internal/controlplane/machineconfig/types.go index 43c1d3e..cbc3a79 100644 --- a/api/internal/controlplane/machineconfig/types.go +++ b/api/internal/controlplane/machineconfig/types.go @@ -13,9 +13,9 @@ import ( const PrivateOrchestrator = contract.PrivateOrchestrator type Machine struct { - NodeID, Epoch, InstallDir, K3sVersion string - CredentialVersion int64 - Terminal bool + NodeID, Fingerprint, InstallDir, K3sVersion string + CredentialVersion int64 + Terminal bool } // State is the enrollment's workload rollout, independent of any provider. @@ -93,7 +93,7 @@ type Report struct { ReportVersion int `json:"report_version,omitempty"` ObservedAt time.Time `json:"observed_at,omitempty"` Downloaded *contract.StageIdentity `json:"downloaded,omitempty"` - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Component string `json:"component"` Generation int64 `json:"generation"` diff --git a/api/internal/controlplane/machineconfig_database_test.go b/api/internal/controlplane/machineconfig_database_test.go index cb5e1b3..f90d2f6 100644 --- a/api/internal/controlplane/machineconfig_database_test.go +++ b/api/internal/controlplane/machineconfig_database_test.go @@ -96,7 +96,7 @@ func TestCredentialRefreshSerializesWithBlockedStateWrite(t *testing.T) { if status := <-refreshed; status != 200 { t.Fatal("refresh failed", status) } - current, err := store.Load(t.Context(), m.NodeID, m.Epoch) + current, err := store.Load(t.Context(), m.NodeID) if err != nil { t.Fatal(err) } @@ -123,14 +123,14 @@ func TestPrivateMachineRolloutAndRemoval(t *testing.T) { if err = s.reconcile(t.Context()); err != nil { t.Fatal(err) } - state, _, err := s.loadTunnel(t.Context(), m.NodeID, m.Epoch) + state, _, err := s.loadTunnel(t.Context(), m.NodeID) if err != nil || !state.DrainRequested || state.HeldOrchestrator != previous { t.Fatal("private replacement was not drain gated", state, err) } if s.tunnels.Enabled() || state.TunnelID != "" { t.Fatal("private rollout acquired provider resources") } - stale := currentReport(t, s, m.NodeID, machineconfig.Report{Epoch: m.Epoch, CredentialVersion: 1, Component: "runner", Generation: state.Generation - 1, BundleFormat: contract.BundleFormat, Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}, HTTPS: true}) + stale := currentReport(t, s, m.NodeID, machineconfig.Report{NodeID: m.NodeID, CredentialVersion: 1, Component: "runner", Generation: state.Generation - 1, BundleFormat: contract.BundleFormat, Apps: &contract.AppStatus{Instances: []contract.InstanceStatus{}}, HTTPS: true}) for len(s.reconcileWake) > 0 { <-s.reconcileWake } @@ -157,7 +157,7 @@ func TestPrivateMachineRolloutAndRemoval(t *testing.T) { t.Fatal("matching drain did not release replacement") } adminA(t, s) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{"epoch": m.Epoch}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{}), 202) if err = s.reconcile(t.Context()); err != nil { t.Fatal(err) } @@ -192,7 +192,7 @@ func TestMachineRolloutWithdrawsTunnelReadiness(t *testing.T) { if err != nil || len(sources) != 1 || sources[0].Ready || sources[0].Reason != "rollout_pending" { t.Fatal("prior generation advertised during workload replacement", sources, err) } - state, _, err := s.loadTunnel(t.Context(), m.NodeID, m.Epoch) + state, _, err := s.loadTunnel(t.Context(), m.NodeID) if err != nil || state.Ready || state.Reason != "rollout_pending" { t.Fatal("prior generation reported ready", state, err) } @@ -259,7 +259,7 @@ func TestRemovalKeepsAppliedWorkload(t *testing.T) { c := enroll(t, s, ownerA, strings.Repeat("a", 64)) m, prior := priorMachineConfiguration(t, s, c, nil) adminA(t, s) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{"epoch": m.Epoch}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{}), 202) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } @@ -460,7 +460,7 @@ func TestRotationRejectsConfigOnlyRow(t *testing.T) { } adminA(t, s) for _, kind := range []string{"connector", "access"} { - w := request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": kind, "compromised": true}) + w := request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": kind, "compromised": true}) requireStatus(t, w, 404) } if count(t, s, `SELECT count(*) FROM lpcc.admin_audit_events WHERE action='tunnel.rotate' AND outcome='success'`) != 0 { @@ -474,14 +474,14 @@ func TestRetirementReasonSurvivesOldDrainReason(t *testing.T) { readyTunnel(t, s, c) adminA(t, s) path := "/api/admin/machines/" + c["node_id"] - requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"epoch": c["epoch"]}), 202) + requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{}), 202) execSQL(t, s.db, `UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{drain_started_at}',to_jsonb($1::text))`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano)) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"epoch": c["epoch"], "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"force": true}), 202) driveTunnels(t, s) - state, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil { t.Fatal(err) } @@ -511,7 +511,7 @@ func TestCompletedEndpointDrainDoesNotMaskProviderFailure(t *testing.T) { testTunnelDeps(s).Provider = &appCreateFailure{f} configureTestTunnels(t, s) driveTunnels(t, s) - state, _, err := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, err := s.loadTunnel(t.Context(), c["node_id"]) if err != nil { t.Fatal(err) } diff --git a/api/internal/controlplane/migrations/001_initial.sql b/api/internal/controlplane/migrations/001_initial.sql index 34e6a5f..9b6e262 100644 --- a/api/internal/controlplane/migrations/001_initial.sql +++ b/api/internal/controlplane/migrations/001_initial.sql @@ -1,7 +1,7 @@ -- UP REVOKE ALL ON SCHEMA lpcc FROM PUBLIC; CREATE TABLE lpcc.machines ( - node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), + node_id TEXT PRIMARY KEY CHECK(node_id ~ '^[a-z2-7]{26}$'), fingerprint TEXT NOT NULL UNIQUE CHECK(fingerprint ~ '^[0-9a-f]{64}$'), owner_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, hostname TEXT NOT NULL, diff --git a/api/internal/controlplane/migrations/004_machine_tunnels.sql b/api/internal/controlplane/migrations/004_machine_tunnels.sql index 740d933..1fcf230 100644 --- a/api/internal/controlplane/migrations/004_machine_tunnels.sql +++ b/api/internal/controlplane/migrations/004_machine_tunnels.sql @@ -1,50 +1,48 @@ -- UP -ALTER TABLE lpcc.machines ADD COLUMN enrollment_epoch UUID NOT NULL DEFAULT gen_random_uuid(); ALTER TABLE lpcc.machines ADD COLUMN credential_version BIGINT NOT NULL DEFAULT 1 CHECK(credential_version>0); ALTER TABLE lpcc.machines ADD COLUMN tunnel_eligible BOOLEAN NOT NULL DEFAULT false; CREATE TABLE lpcc.enrollments ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, owner_id UUID NOT NULL, + node_id TEXT NOT NULL, owner_id UUID NOT NULL, fingerprint TEXT NOT NULL, hostname TEXT NOT NULL, install_dir TEXT NOT NULL, k3s_version TEXT NOT NULL, credential_version BIGINT NOT NULL CHECK(credential_version>0), retired_at TIMESTAMPTZ, removal_ack_at TIMESTAMPTZ, terminal_bundle BYTEA, terminal_sha256 TEXT, - PRIMARY KEY(node_id,epoch), + PRIMARY KEY(node_id), CHECK((terminal_bundle IS NULL)=(terminal_sha256 IS NULL)) ); CREATE TABLE lpcc.credential_refreshes ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, operation_id UUID NOT NULL, + node_id TEXT NOT NULL, operation_id UUID NOT NULL, expected_version BIGINT NOT NULL, resulting_version BIGINT NOT NULL, - PRIMARY KEY(node_id,epoch,operation_id) + PRIMARY KEY(node_id,operation_id) ); CREATE TABLE lpcc.machine_reports ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, component TEXT NOT NULL, + node_id TEXT NOT NULL, component TEXT NOT NULL, generation BIGINT NOT NULL, credential_version BIGINT NOT NULL, report JSONB NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY(node_id,epoch,component) + PRIMARY KEY(node_id,component) ); CREATE TABLE lpcc.machine_tunnels ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, - state JSONB NOT NULL, revision BIGINT NOT NULL DEFAULT 1, + node_id TEXT NOT NULL, state JSONB NOT NULL, revision BIGINT NOT NULL DEFAULT 1, lease_id UUID, lease_until TIMESTAMPTZ, next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), failures INTEGER NOT NULL DEFAULT 0, - PRIMARY KEY(node_id,epoch), FOREIGN KEY(node_id,epoch) REFERENCES lpcc.enrollments(node_id,epoch) + PRIMARY KEY(node_id), FOREIGN KEY(node_id) REFERENCES lpcc.enrollments(node_id) ); CREATE TABLE lpcc.access_credentials ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, version BIGINT NOT NULL, + node_id TEXT NOT NULL, version BIGINT NOT NULL, provider_id TEXT NOT NULL, key_id TEXT NOT NULL, ciphertext BYTEA NOT NULL, expires_at TIMESTAMPTZ NOT NULL, acknowledged_at TIMESTAMPTZ, acknowledged_generation BIGINT, revoked_at TIMESTAMPTZ, - PRIMARY KEY(node_id,epoch,version), FOREIGN KEY(node_id,epoch) REFERENCES lpcc.enrollments(node_id,epoch) + PRIMARY KEY(node_id,version), FOREIGN KEY(node_id) REFERENCES lpcc.enrollments(node_id) ); -- Auth deletion bypasses the HTTP API. This trigger captures retirement in the -- same transaction as the cascade, without relying on an application process. CREATE FUNCTION lpcc.retire_machine() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) - VALUES(OLD.node_id,OLD.enrollment_epoch,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) - ON CONFLICT(node_id,epoch) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; + INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) + VALUES(OLD.node_id,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) + ON CONFLICT(node_id) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; UPDATE lpcc.machine_tunnels SET state=jsonb_set(jsonb_set(state,'{lifecycle}','"removed"'),'{ready}','false'), - revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id; RETURN OLD; END $$; REVOKE ALL ON FUNCTION lpcc.retire_machine() FROM PUBLIC; @@ -69,4 +67,4 @@ END $$; DROP TRIGGER retire_machine ON lpcc.machines; DROP FUNCTION lpcc.retire_machine(); DROP TABLE lpcc.access_credentials,lpcc.machine_tunnels,lpcc.machine_reports,lpcc.credential_refreshes,lpcc.enrollments; -ALTER TABLE lpcc.machines DROP COLUMN tunnel_eligible,DROP COLUMN credential_version,DROP COLUMN enrollment_epoch; +ALTER TABLE lpcc.machines DROP COLUMN tunnel_eligible,DROP COLUMN credential_version; diff --git a/api/internal/controlplane/migrations/005_machine_configuration.sql b/api/internal/controlplane/migrations/005_machine_configuration.sql index 457af0e..ee30116 100644 --- a/api/internal/controlplane/migrations/005_machine_configuration.sql +++ b/api/internal/controlplane/migrations/005_machine_configuration.sql @@ -4,11 +4,11 @@ ALTER TABLE lpcc.machine_states ADD COLUMN rollout JSONB NOT NULL DEFAULT '{"lif CREATE OR REPLACE FUNCTION lpcc.retire_machine() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) - VALUES(OLD.node_id,OLD.enrollment_epoch,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) - ON CONFLICT(node_id,epoch) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; + INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) + VALUES(OLD.node_id,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) + ON CONFLICT(node_id) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{lifecycle}','"removed"')-'rollout_reason',state=jsonb_set(state,'{ready}','false'), - revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id; RETURN OLD; END $$; -- DOWN @@ -22,10 +22,10 @@ ALTER TABLE lpcc.machine_states RENAME TO machine_tunnels; CREATE OR REPLACE FUNCTION lpcc.retire_machine() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) - VALUES(OLD.node_id,OLD.enrollment_epoch,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) - ON CONFLICT(node_id,epoch) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; + INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) + VALUES(OLD.node_id,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) + ON CONFLICT(node_id) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; UPDATE lpcc.machine_tunnels SET state=jsonb_set(jsonb_set(state,'{lifecycle}','"removed"'),'{ready}','false'), - revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id; RETURN OLD; END $$; diff --git a/api/internal/controlplane/migrations/006_machine_apps.sql b/api/internal/controlplane/migrations/006_machine_apps.sql index ca4ee7f..5b7c63c 100644 --- a/api/internal/controlplane/migrations/006_machine_apps.sql +++ b/api/internal/controlplane/migrations/006_machine_apps.sql @@ -2,67 +2,67 @@ ALTER TABLE lpcc.machine_states ADD COLUMN apps_generation BIGINT NOT NULL DEFAULT 0 CHECK(apps_generation>=0); ALTER TABLE lpcc.machine_states ADD COLUMN apps_error TEXT; CREATE TABLE lpcc.machine_app_versions ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, revision_id UUID NOT NULL REFERENCES lpcc.app_revisions(revision_id), + node_id TEXT NOT NULL, revision_id UUID NOT NULL REFERENCES lpcc.app_revisions(revision_id), generation BIGINT NOT NULL CHECK(generation>0), intent JSONB NOT NULL, actor_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY(node_id,epoch,revision_id,generation), - FOREIGN KEY(node_id,epoch) REFERENCES lpcc.enrollments(node_id,epoch), + PRIMARY KEY(node_id,revision_id,generation), + FOREIGN KEY(node_id) REFERENCES lpcc.enrollments(node_id), CHECK(intent->>'revision_id'=revision_id::text AND (intent->>'generation')::bigint=generation), CHECK(intent->>'desired' IN ('present','absent')), CHECK((intent->>'activation_generation')::bigint BETWEEN 1 AND generation) ); -CREATE INDEX machine_app_latest ON lpcc.machine_app_versions(node_id,epoch,revision_id,generation DESC); +CREATE INDEX machine_app_latest ON lpcc.machine_app_versions(node_id,revision_id,generation DESC); CREATE VIEW lpcc.machine_app_heads WITH (security_invoker=true) AS - SELECT DISTINCT ON(node_id,epoch,revision_id) * FROM lpcc.machine_app_versions - ORDER BY node_id,epoch,revision_id,generation DESC; + SELECT DISTINCT ON(node_id,revision_id) * FROM lpcc.machine_app_versions + ORDER BY node_id,revision_id,generation DESC; CREATE TABLE lpcc.machine_app_deliveries ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, apps_digest TEXT NOT NULL CHECK(apps_digest ~ '^sha256:[0-9a-f]{64}$'), + node_id TEXT NOT NULL, apps_digest TEXT NOT NULL CHECK(apps_digest ~ '^sha256:[0-9a-f]{64}$'), bundle_sha256 TEXT NOT NULL CHECK(bundle_sha256 ~ '^[0-9a-f]{64}$'), apps_generation BIGINT NOT NULL CHECK(apps_generation>0), entries JSONB NOT NULL, terminal BOOLEAN NOT NULL, published_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY(node_id,epoch,apps_digest,bundle_sha256), - FOREIGN KEY(node_id,epoch) REFERENCES lpcc.enrollments(node_id,epoch) + PRIMARY KEY(node_id,apps_digest,bundle_sha256), + FOREIGN KEY(node_id) REFERENCES lpcc.enrollments(node_id) ); CREATE TABLE lpcc.machine_app_completions ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, revision_id UUID NOT NULL, generation BIGINT NOT NULL, + node_id TEXT NOT NULL, revision_id UUID NOT NULL, generation BIGINT NOT NULL, activation_generation BIGINT NOT NULL, phase TEXT NOT NULL CHECK(phase IN ('applied','removed')), apps_digest TEXT NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY(node_id,epoch,revision_id,generation,phase), - FOREIGN KEY(node_id,epoch,revision_id,generation) REFERENCES lpcc.machine_app_versions(node_id,epoch,revision_id,generation) + PRIMARY KEY(node_id,revision_id,generation,phase), + FOREIGN KEY(node_id,revision_id,generation) REFERENCES lpcc.machine_app_versions(node_id,revision_id,generation) ); CREATE TABLE lpcc.machine_app_diagnostics ( - node_id TEXT NOT NULL, epoch UUID NOT NULL, revision_id UUID NOT NULL, generation BIGINT NOT NULL, + node_id TEXT NOT NULL, revision_id UUID NOT NULL, generation BIGINT NOT NULL, reason TEXT NOT NULL CHECK(reason ~ '^[a-z][a-z0-9_]{0,63}$'), received_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY(node_id,epoch,revision_id), - FOREIGN KEY(node_id,epoch,revision_id,generation) REFERENCES lpcc.machine_app_versions(node_id,epoch,revision_id,generation) + PRIMARY KEY(node_id,revision_id), + FOREIGN KEY(node_id,revision_id,generation) REFERENCES lpcc.machine_app_versions(node_id,revision_id,generation) ); CREATE TRIGGER immutable_app_intent BEFORE UPDATE OR DELETE ON lpcc.machine_app_versions FOR EACH ROW EXECUTE FUNCTION lpcc.immutable_app_revision(); CREATE TRIGGER immutable_app_completion BEFORE UPDATE OR DELETE ON lpcc.machine_app_completions FOR EACH ROW EXECUTE FUNCTION lpcc.immutable_app_revision(); CREATE TRIGGER immutable_app_delivery BEFORE UPDATE OR DELETE ON lpcc.machine_app_deliveries FOR EACH ROW EXECUTE FUNCTION lpcc.immutable_app_revision(); -- Both administrative removal and auth.users cascades use this transition. -CREATE FUNCTION lpcc.remove_machine_apps(n TEXT,e UUID,actor TEXT) RETURNS integer LANGUAGE plpgsql +CREATE FUNCTION lpcc.remove_machine_apps(n TEXT,actor TEXT) RETURNS integer LANGUAGE plpgsql SET search_path=pg_catalog,lpcc AS $$ DECLARE changed integer; BEGIN - INSERT INTO lpcc.machine_app_versions(node_id,epoch,revision_id,generation,intent,actor_id) - SELECT node_id,epoch,revision_id,generation+1, + INSERT INTO lpcc.machine_app_versions(node_id,revision_id,generation,intent,actor_id) + SELECT node_id,revision_id,generation+1, (intent-ARRAY['revision','replicas','start_after','replacement']) || jsonb_build_object('generation',generation+1,'desired','absent','start_allowed',false),actor - FROM lpcc.machine_app_heads WHERE node_id=n AND epoch=e AND intent->>'desired'='present'; + FROM lpcc.machine_app_heads WHERE node_id=n AND intent->>'desired'='present'; GET DIAGNOSTICS changed=ROW_COUNT; IF changed>0 THEN - UPDATE lpcc.machine_states SET apps_generation=apps_generation+1,revision=revision+1,apps_error=NULL WHERE node_id=n AND epoch=e; + UPDATE lpcc.machine_states SET apps_generation=apps_generation+1,revision=revision+1,apps_error=NULL WHERE node_id=n; END IF; RETURN changed; END $$; CREATE OR REPLACE FUNCTION lpcc.retire_machine() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) - VALUES(OLD.node_id,OLD.enrollment_epoch,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) - ON CONFLICT(node_id,epoch) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; - PERFORM lpcc.remove_machine_apps(OLD.node_id,OLD.enrollment_epoch,'system:machine-retirement'); + INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) + VALUES(OLD.node_id,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) + ON CONFLICT(node_id) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; + PERFORM lpcc.remove_machine_apps(OLD.node_id,'system:machine-retirement'); UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{lifecycle}','"removed"')-'rollout_reason',state=jsonb_set(state,'{ready}','false'), - revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id; RETURN OLD; END $$; ALTER TABLE lpcc.machine_app_versions ENABLE ROW LEVEL SECURITY; @@ -70,13 +70,13 @@ ALTER TABLE lpcc.machine_app_deliveries ENABLE ROW LEVEL SECURITY; ALTER TABLE lpcc.machine_app_completions ENABLE ROW LEVEL SECURITY; ALTER TABLE lpcc.machine_app_diagnostics ENABLE ROW LEVEL SECURITY; REVOKE ALL ON lpcc.machine_app_versions,lpcc.machine_app_heads,lpcc.machine_app_deliveries,lpcc.machine_app_completions,lpcc.machine_app_diagnostics FROM PUBLIC; -REVOKE ALL ON FUNCTION lpcc.remove_machine_apps(TEXT,UUID,TEXT) FROM PUBLIC; +REVOKE ALL ON FUNCTION lpcc.remove_machine_apps(TEXT,TEXT) FROM PUBLIC; DO $$ DECLARE r TEXT; BEGIN FOREACH r IN ARRAY ARRAY['anon','authenticated'] LOOP IF EXISTS(SELECT FROM pg_roles WHERE rolname=r) THEN EXECUTE format('REVOKE ALL ON lpcc.machine_app_versions,lpcc.machine_app_heads,lpcc.machine_app_deliveries,lpcc.machine_app_completions,lpcc.machine_app_diagnostics FROM %I',r); - EXECUTE format('REVOKE ALL ON FUNCTION lpcc.remove_machine_apps(TEXT,UUID,TEXT) FROM %I',r); + EXECUTE format('REVOKE ALL ON FUNCTION lpcc.remove_machine_apps(TEXT,TEXT) FROM %I',r); END IF; END LOOP; END $$; @@ -87,13 +87,13 @@ END $$; CREATE OR REPLACE FUNCTION lpcc.retire_machine() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) - VALUES(OLD.node_id,OLD.enrollment_epoch,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) - ON CONFLICT(node_id,epoch) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; - UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{lifecycle}','"removed"')-'rollout_reason',state=jsonb_set(state,'{ready}','false'),revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,retired_at) + VALUES(OLD.node_id,OLD.owner_id,OLD.fingerprint,OLD.hostname,OLD.install_dir,OLD.k3s_version,OLD.credential_version,now()) + ON CONFLICT(node_id) DO UPDATE SET retired_at=COALESCE(lpcc.enrollments.retired_at,now()),credential_version=OLD.credential_version; + UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{lifecycle}','"removed"')-'rollout_reason',state=jsonb_set(state,'{ready}','false'),revision=revision+1,next_attempt_at=now() WHERE node_id=OLD.node_id; RETURN OLD; END $$; -DROP FUNCTION lpcc.remove_machine_apps(TEXT,UUID,TEXT); +DROP FUNCTION lpcc.remove_machine_apps(TEXT,TEXT); DROP VIEW lpcc.machine_app_heads; DROP TABLE lpcc.machine_app_diagnostics,lpcc.machine_app_completions,lpcc.machine_app_deliveries,lpcc.machine_app_versions; ALTER TABLE lpcc.machine_states DROP COLUMN apps_generation,DROP COLUMN apps_error; diff --git a/api/internal/controlplane/migrations/007_runtime_retirement.sql b/api/internal/controlplane/migrations/007_runtime_retirement.sql index 1a0d28a..cc3462f 100644 --- a/api/internal/controlplane/migrations/007_runtime_retirement.sql +++ b/api/internal/controlplane/migrations/007_runtime_retirement.sql @@ -8,7 +8,7 @@ CREATE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgs BEGIN UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c - WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + WHERE e.node_id=OLD.node_id AND c.node_id=OLD.node_id AND e.retained_bundle IS NULL; RETURN OLD; END $$; diff --git a/api/internal/controlplane/migrations/008_machine_certificates.sql b/api/internal/controlplane/migrations/008_machine_certificates.sql index 9372894..c1d3285 100644 --- a/api/internal/controlplane/migrations/008_machine_certificates.sql +++ b/api/internal/controlplane/migrations/008_machine_certificates.sql @@ -14,10 +14,9 @@ CREATE TABLE lpcc.machine_certificate_refs ( zone_id text NOT NULL, wildcard_host text NOT NULL, node_id text NOT NULL, - epoch uuid NOT NULL, - PRIMARY KEY (zone_id, wildcard_host, node_id, epoch), + PRIMARY KEY (zone_id, wildcard_host, node_id), FOREIGN KEY (zone_id, wildcard_host) REFERENCES lpcc.machine_certificates, - FOREIGN KEY (node_id, epoch) REFERENCES lpcc.enrollments + FOREIGN KEY (node_id) REFERENCES lpcc.enrollments ); ALTER TABLE lpcc.machine_certificates ENABLE ROW LEVEL SECURITY; ALTER TABLE lpcc.machine_certificate_refs ENABLE ROW LEVEL SECURITY; diff --git a/api/internal/controlplane/migrations/009_onchain.sql b/api/internal/controlplane/migrations/009_onchain.sql index 4ffe9be..087035f 100644 --- a/api/internal/controlplane/migrations/009_onchain.sql +++ b/api/internal/controlplane/migrations/009_onchain.sql @@ -3,33 +3,33 @@ CREATE TABLE lpcc.onchain_revision (id BOOLEAN PRIMARY KEY DEFAULT true CHECK(id), revision BIGINT NOT NULL DEFAULT 0); INSERT INTO lpcc.onchain_revision DEFAULT VALUES; CREATE TABLE lpcc.onchain_configs ( - node_id TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, - PRIMARY KEY(node_id,generation) + fingerprint TEXT NOT NULL, generation BIGINT NOT NULL, config JSONB NOT NULL, + PRIMARY KEY(fingerprint,generation) ); CREATE TABLE lpcc.onchain_state ( - node_id TEXT PRIMARY KEY CHECK(node_id ~ '^lp-[0-9a-f]{16}$'), + fingerprint TEXT PRIMARY KEY CHECK(fingerprint ~ '^[0-9a-f]{64}$'), recipient TEXT NOT NULL DEFAULT '', chain_id BIGINT NOT NULL DEFAULT 0, controller TEXT NOT NULL DEFAULT '', generation BIGINT NOT NULL CHECK(generation>0), initialized BOOLEAN NOT NULL DEFAULT false, - FOREIGN KEY(node_id,generation) REFERENCES lpcc.onchain_configs(node_id,generation) + FOREIGN KEY(fingerprint,generation) REFERENCES lpcc.onchain_configs(fingerprint,generation) ); CREATE TABLE lpcc.onchain_secrets (reference TEXT PRIMARY KEY, fingerprint TEXT NOT NULL); CREATE TABLE lpcc.onchain_grants ( - grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, epoch UUID NOT NULL, + grant_id UUID PRIMARY KEY, issued_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, node_id TEXT NOT NULL, onchain_generation BIGINT NOT NULL, config_digest TEXT NOT NULL, pod_uid TEXT NOT NULL, launch_id TEXT NOT NULL, process_id TEXT NOT NULL, observed_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, - UNIQUE(node_id,epoch,onchain_generation,pod_uid,launch_id,process_id) + UNIQUE(node_id,onchain_generation,pod_uid,launch_id,process_id) ); -CREATE INDEX onchain_grants_machine ON lpcc.onchain_grants(node_id,epoch); +CREATE INDEX onchain_grants_machine ON lpcc.onchain_grants(node_id); CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,lpcc AS $$ BEGIN - UPDATE lpcc.onchain_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id AND epoch=OLD.enrollment_epoch; + UPDATE lpcc.onchain_grants SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=OLD.node_id; UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c - WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + WHERE e.node_id=OLD.node_id AND c.node_id=OLD.node_id AND e.retained_bundle IS NULL; RETURN OLD; END $$; @@ -61,7 +61,7 @@ CREATE OR REPLACE FUNCTION lpcc.capture_runtime_retirement() RETURNS trigger LAN BEGIN UPDATE lpcc.enrollments e SET retained_bundle=c.bundle FROM lpcc.machine_configs c - WHERE e.node_id=OLD.node_id AND e.epoch=OLD.enrollment_epoch AND c.node_id=OLD.node_id + WHERE e.node_id=OLD.node_id AND c.node_id=OLD.node_id AND e.retained_bundle IS NULL; RETURN OLD; END $$; diff --git a/api/internal/controlplane/observed_state.go b/api/internal/controlplane/observed_state.go index 77fe8ce..2681f93 100644 --- a/api/internal/controlplane/observed_state.go +++ b/api/internal/controlplane/observed_state.go @@ -84,7 +84,6 @@ type tunnelObservation struct { type machineObservation struct { Onchain onchainView `json:"onchain"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` Hostname string `json:"hostname"` Lifecycle string `json:"lifecycle"` RolloutGeneration int64 `json:"rollout_generation"` @@ -127,15 +126,11 @@ func (s *Server) observedState(w http.ResponseWriter, r *http.Request) { s.respondError(w, err) return } - node, epoch := r.PathValue("node_id"), r.URL.Query().Get("epoch") - if epoch != "" && !appID(epoch) { - s.respondError(w, problem(400, "invalid_epoch", "Provide an enrollment UUID.")) - return - } + node := r.PathValue("node_id") var owner string var m Machine - err = s.db.QueryRowContext(r.Context(), `SELECT e.epoch::text,e.owner_id::text,e.hostname,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.enrollments e - WHERE e.node_id=$1 AND (($2<>'' AND e.epoch::text=$2) OR ($2='' AND EXISTS(SELECT FROM lpcc.machines m WHERE m.node_id=e.node_id AND m.enrollment_epoch=e.epoch)))`, node, epoch).Scan(&m.Epoch, &owner, &m.Hostname, &m.CredentialVersion, &m.Terminal) + err = s.db.QueryRowContext(r.Context(), `SELECT e.node_id::text,e.owner_id::text,e.hostname,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.enrollments e + WHERE e.node_id=$1`, node).Scan(&m.NodeID, &owner, &m.Hostname, &m.CredentialVersion, &m.Terminal) if errors.Is(err, sql.ErrNoRows) { err = problem(404, "machine_not_found", "Machine enrollment not found.") } @@ -165,12 +160,12 @@ func (s *Server) observedState(w http.ResponseWriter, r *http.Request) { func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObservation, error) { now := time.Now().UTC() - v := machineObservation{NodeID: m.NodeID, Epoch: m.Epoch, Hostname: m.Hostname, Assignments: []observedAssignment{}, Components: []componentObservation{}, Membership: map[string]fleet.Membership{}, ExternalReachability: "unverified", ServerTime: now} + v := machineObservation{NodeID: m.NodeID, Hostname: m.Hostname, Assignments: []observedAssignment{}, Components: []componentObservation{}, Membership: map[string]fleet.Membership{}, ExternalReachability: "unverified", ServerTime: now} ttl := s.params.TunnelStatusTTL if ttl <= 0 { ttl = 2 * time.Minute } - record, err := (machineconfig.Store{DB: s.db}).Load(ctx, m.NodeID, m.Epoch) + record, err := (machineconfig.Store{DB: s.db}).Load(ctx, m.NodeID) if errors.Is(err, sql.ErrNoRows) { record.State = machineconfig.InitialState(m.Terminal) } else if err != nil { @@ -183,7 +178,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse v.Lifecycle, v.RolloutGeneration = record.Lifecycle, record.Generation if m.Terminal { var ack *time.Time - if err := s.db.QueryRowContext(ctx, `SELECT removal_ack_at FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&ack); err != nil { + if err := s.db.QueryRowContext(ctx, `SELECT removal_ack_at FROM lpcc.enrollments WHERE node_id=$1`, m.NodeID).Scan(&ack); err != nil { return v, err } v.Lifecycle = "cleanup_pending" @@ -199,14 +194,14 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse if !route.VerifiedAt.IsZero() { v.Tunnel.ExpiresAt = timePointer(route.VerifiedAt.Add(ttl)) } - err = s.db.QueryRowContext(ctx, `SELECT apps_generation,COALESCE(apps_error,'') FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&v.Requested.Generation, &v.DeliveryReason) + err = s.db.QueryRowContext(ctx, `SELECT apps_generation,COALESCE(apps_error,'') FROM lpcc.machine_states WHERE node_id=$1`, m.NodeID).Scan(&v.Requested.Generation, &v.DeliveryReason) if err != nil && !errors.Is(err, sql.ErrNoRows) { return v, err } v.DeliveryReason = safeObservationReason(v.DeliveryReason) var delivered contract.StageIdentity var at time.Time - err = s.db.QueryRowContext(ctx, `SELECT apps_generation,apps_digest,'sha256:'||bundle_sha256,published_at FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 ORDER BY published_at DESC,apps_generation DESC LIMIT 1`, m.NodeID, m.Epoch).Scan(&delivered.Generation, &delivered.AppsDigest, &delivered.ArtifactDigest, &at) + err = s.db.QueryRowContext(ctx, `SELECT apps_generation,apps_digest,'sha256:'||bundle_sha256,published_at FROM lpcc.machine_app_deliveries WHERE node_id=$1 ORDER BY published_at DESC,apps_generation DESC LIMIT 1`, m.NodeID).Scan(&delivered.Generation, &delivered.AppsDigest, &delivered.ArtifactDigest, &at) if err == nil { v.Delivered, v.DeliveredAt = &delivered, &at } else if !errors.Is(err, sql.ErrNoRows) { @@ -216,7 +211,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse if err != nil { return v, err } - rows, err := s.db.QueryContext(ctx, `SELECT component,report,received_at FROM lpcc.machine_reports WHERE node_id=$1 AND epoch=$2 AND credential_version=$3 ORDER BY component`, m.NodeID, m.Epoch, m.CredentialVersion) + rows, err := s.db.QueryContext(ctx, `SELECT component,report,received_at FROM lpcc.machine_reports WHERE node_id=$1 AND credential_version=$2 ORDER BY component`, m.NodeID, m.CredentialVersion) if err != nil { return v, err } @@ -285,7 +280,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse v.DiscoveryEnabled, v.DiscoveryInitialized, v.DiscoverySelectionStale = status.Enabled, status.Initialized, status.SelectionStale v.DiscoverySelectionExpiresAt = status.SelectionExpiresAt for _, source := range status.Sources { - if source.NodeID == m.NodeID && source.Epoch == m.Epoch { + if source.NodeID == m.NodeID { v.DiscoverySource = &source break } @@ -303,7 +298,7 @@ func (s *Server) machineObservation(ctx context.Context, m Machine) (machineObse } queries = append(queries, a.membershipQueries(i, route.ServiceURL, route.ProxyURLTemplate)...) } - v.Membership = s.discovery.Memberships(m.NodeID, m.Epoch, queries) + v.Membership = s.discovery.Memberships(m.NodeID, queries) } } return v, nil @@ -331,9 +326,9 @@ func (a observedAssignment) membershipQueries(i contract.InstanceStatus, service func (s *Server) observedAssignments(ctx context.Context, m Machine) ([]observedAssignment, bool, error) { rows, err := s.db.QueryContext(ctx, `SELECT v.intent-'revision',r.app_name,r.app_version,r.revision,r.canonical,c.received_at,CASE WHEN c.received_at IS NULL THEN COALESCE(d.reason,'') ELSE '' END FROM lpcc.machine_app_heads v `+` JOIN lpcc.app_revisions r ON r.revision_id=v.revision_id - LEFT JOIN lpcc.machine_app_completions c ON c.node_id=v.node_id AND c.epoch=v.epoch AND c.revision_id=v.revision_id AND c.generation=v.generation - LEFT JOIN lpcc.machine_app_diagnostics d ON d.node_id=v.node_id AND d.epoch=v.epoch AND d.revision_id=v.revision_id AND d.generation=v.generation - WHERE v.node_id=$1 AND v.epoch=$2 AND (v.intent->>'desired'='present' OR c.received_at IS NULL) ORDER BY v.revision_id LIMIT 101`, m.NodeID, m.Epoch) + LEFT JOIN lpcc.machine_app_completions c ON c.node_id=v.node_id AND c.revision_id=v.revision_id AND c.generation=v.generation + LEFT JOIN lpcc.machine_app_diagnostics d ON d.node_id=v.node_id AND d.revision_id=v.revision_id AND d.generation=v.generation + WHERE v.node_id=$1 AND (v.intent->>'desired'='present' OR c.received_at IS NULL) ORDER BY v.revision_id LIMIT 101`, m.NodeID) if err != nil { return nil, false, err } @@ -375,7 +370,6 @@ func (s *Server) observedAssignments(ctx context.Context, m Machine) ([]observed type observedMachineSummary struct { NodeID string `json:"node_id"` - Epoch string `json:"epoch"` Hostname string `json:"hostname"` OwnerID *string `json:"owner_id,omitempty"` InstallDir string `json:"install_dir,omitempty"` @@ -390,16 +384,16 @@ type observedMachineSummary struct { func (s *Server) observedMachineList(ctx context.Context, owner string, admin bool) ([]observedMachineSummary, error) { rows, err := s.db.QueryContext(ctx, `WITH inventory AS ( - SELECT m.node_id,m.enrollment_epoch AS epoch,m.hostname,m.owner_id,m.install_dir,m.k3s_version,m.created_at,m.last_config_fetch_at,m.credential_version,false AS terminal,COALESCE(s.rollout->>'lifecycle','active') AS lifecycle - FROM lpcc.machines m LEFT JOIN lpcc.machine_states s ON s.node_id=m.node_id AND s.epoch=m.enrollment_epoch + SELECT m.node_id,m.hostname,m.owner_id,m.install_dir,m.k3s_version,m.created_at,m.last_config_fetch_at,m.credential_version,false AS terminal,COALESCE(s.rollout->>'lifecycle','active') AS lifecycle + FROM lpcc.machines m LEFT JOIN lpcc.machine_states s ON s.node_id=m.node_id UNION ALL - SELECT e.node_id,e.epoch,e.hostname,e.owner_id,e.install_dir,e.k3s_version,e.retired_at,NULL::timestamptz,e.credential_version,true,'cleanup_pending' + SELECT e.node_id,e.hostname,e.owner_id,e.install_dir,e.k3s_version,e.retired_at,NULL::timestamptz,e.credential_version,true,'cleanup_pending' FROM lpcc.enrollments e WHERE e.retired_at IS NOT NULL AND e.removal_ack_at IS NULL - ) SELECT i.node_id,i.epoch::text,i.hostname,i.owner_id::text,i.install_dir,i.k3s_version,i.created_at,i.last_config_fetch_at,i.terminal,i.lifecycle, + ) SELECT i.node_id,i.hostname,i.owner_id::text,i.install_dir,i.k3s_version,i.created_at,i.last_config_fetch_at,i.terminal,i.lifecycle, CASE WHEN COALESCE((r.report->>'clock_uncertain')::boolean,false) THEN NULL ELSE LEAST(r.received_at,(r.report->>'observed_at')::timestamptz) END, COALESCE((r.report->>'clock_uncertain')::boolean,false) - FROM inventory i LEFT JOIN lpcc.machine_reports r ON r.node_id=i.node_id AND r.epoch=i.epoch AND r.credential_version=i.credential_version AND r.component='runtime' - WHERE ($1='' OR i.owner_id::text=$1) ORDER BY i.created_at DESC,i.node_id,i.epoch`, owner) + FROM inventory i LEFT JOIN lpcc.machine_reports r ON r.node_id=i.node_id AND r.credential_version=i.credential_version AND r.component='runtime' + WHERE ($1='' OR i.owner_id::text=$1) ORDER BY i.created_at DESC,i.node_id`, owner) if err != nil { return nil, err } @@ -413,7 +407,7 @@ func (s *Server) observedMachineList(ctx context.Context, owner string, admin bo var m observedMachineSummary var id string var clockUncertain bool - if err = rows.Scan(&m.NodeID, &m.Epoch, &m.Hostname, &id, &m.InstallDir, &m.K3sVersion, &m.CreatedAt, &m.LastConfigFetchAt, &m.Terminal, &m.Lifecycle, &m.LastObservedAt, &clockUncertain); err != nil { + if err = rows.Scan(&m.NodeID, &m.Hostname, &id, &m.InstallDir, &m.K3sVersion, &m.CreatedAt, &m.LastConfigFetchAt, &m.Terminal, &m.Lifecycle, &m.LastObservedAt, &clockUncertain); err != nil { return nil, err } if admin { @@ -451,7 +445,7 @@ func (s *Server) onchainView(ctx context.Context, m Machine) (onchainView, error v.Desired.RedeemerGrants = nil var b []byte if m.Terminal { - err = s.db.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch).Scan(&b) + err = s.db.QueryRowContext(ctx, `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1`, m.NodeID).Scan(&b) } else { err = s.db.QueryRowContext(ctx, `SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, m.NodeID).Scan(&b) } diff --git a/api/internal/controlplane/observed_state_test.go b/api/internal/controlplane/observed_state_test.go index 49bcf3c..2e68176 100644 --- a/api/internal/controlplane/observed_state_test.go +++ b/api/internal/controlplane/observed_state_test.go @@ -61,7 +61,7 @@ func observationFixture(t *testing.T) (*Server, map[string]string, contract.Meta if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } - requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/status", c["token"], currentReport(t, s, c["node_id"], machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "applying"})), 200) + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/status", c["token"], currentReport(t, s, c["node_id"], machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runtime", Generation: 1, BundleFormat: contract.BundleFormat, Reason: "applying"})), 200) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func observationFixture(t *testing.T) (*Server, map[string]string, contract.Meta } var intent []byte - if err := s.db.QueryRow(`SELECT entries FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 AND apps_digest=$3 LIMIT 1`, m.NodeID, m.Epoch, m.AppsDigest).Scan(&intent); err != nil { + if err := s.db.QueryRow(`SELECT entries FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND apps_digest=$2 LIMIT 1`, m.NodeID, m.AppsDigest).Scan(&intent); err != nil { t.Fatal(err) } var entries []schema.AppAssignment @@ -93,7 +93,7 @@ func observationFixture(t *testing.T) (*Server, map[string]string, contract.Meta func observationReport(m contract.Metadata, a schema.AppAssignment) machineconfig.Report { now := time.Now().UTC() - return machineconfig.Report{ReportVersion: 1, ObservedAt: now, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Component: "runner", Generation: m.Generation, BundleFormat: contract.BundleFormat, Sequence: 1, Ready: true, Reason: "ready", Apps: &contract.AppStatus{DesiredGeneration: m.AppsGeneration, DesiredDigest: m.AppsDigest, Assignments: []contract.AssignmentStatus{{RevisionID: a.RevisionID, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, Instances: 1, Ready: 1, Registered: 1}}, InstancesTotal: 1, Instances: []contract.InstanceStatus{{RevisionID: a.RevisionID, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, InstanceID: "instance-1", PodUID: "pod-1", RunnerID: "runner-1", AppID: "app-1", Phase: "running", Ready: true, Registered: true, Capacity: 1, Sessions: 0, NodeObservedAt: now, NodeExpiresAt: now.Add(30 * time.Second), AcceptedSequence: new(uint64(1))}}}} + return machineconfig.Report{ReportVersion: 1, ObservedAt: now, NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, Component: "runner", Generation: m.Generation, BundleFormat: contract.BundleFormat, Sequence: 1, Ready: true, Reason: "ready", Apps: &contract.AppStatus{DesiredGeneration: m.AppsGeneration, DesiredDigest: m.AppsDigest, Assignments: []contract.AssignmentStatus{{RevisionID: a.RevisionID, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, Instances: 1, Ready: 1, Registered: 1}}, InstancesTotal: 1, Instances: []contract.InstanceStatus{{RevisionID: a.RevisionID, Generation: a.Generation, ActivationGeneration: a.ActivationGeneration, InstanceID: "instance-1", PodUID: "pod-1", RunnerID: "runner-1", AppID: "app-1", Phase: "running", Ready: true, Registered: true, Capacity: 1, Sessions: 0, NodeObservedAt: now, NodeExpiresAt: now.Add(30 * time.Second), AcceptedSequence: new(uint64(1))}}}} } func TestObservedStateOwnerAdminBoundariesAndRedaction(t *testing.T) { @@ -101,7 +101,7 @@ func TestObservedStateOwnerAdminBoundariesAndRedaction(t *testing.T) { report := observationReport(m, a) path := "/v1/nodes/" + m.NodeID + "/status" requireStatus(t, request(t, s, "POST", path, c["token"], report), 200) - read := "/api/machines/" + m.NodeID + "/status?epoch=" + m.Epoch + read := "/api/machines/" + m.NodeID + "/status" w := request(t, s, "GET", read, "session-a", nil) requireStatus(t, w, 200) var v machineObservation @@ -119,7 +119,7 @@ func TestObservedStateOwnerAdminBoundariesAndRedaction(t *testing.T) { requireStatus(t, request(t, s, "GET", read, "session-b", nil), 404) requireStatus(t, request(t, s, "GET", read, c["token"], nil), 401) other := enroll(t, s, ownerB, strings.Repeat("b", 64)) - requireStatus(t, request(t, s, "GET", "/api/machines/"+other["node_id"]+"/status?epoch="+other["epoch"], "session-a", nil), 200) + requireStatus(t, request(t, s, "GET", "/api/machines/"+other["node_id"]+"/status", "session-a", nil), 200) // Owner B can inspect its status, but has no assignment/admin mutation authority. requireStatus(t, request(t, s, "GET", "/api/machines/"+other["node_id"]+"/status", "session-b", nil), 200) requireStatus(t, request(t, s, "PUT", "/api/admin/machines/"+other["node_id"]+"/apps/"+a.RevisionID, "session-b", map[string]any{}), 403) @@ -156,7 +156,7 @@ func TestObservedStateOwnerAdminBoundariesAndRedaction(t *testing.T) { } var generation int64 var digest string - if err := s.db.QueryRow(`SELECT apps_generation,apps_digest FROM lpcc.machine_app_deliveries WHERE node_id=$1 AND epoch=$2 ORDER BY apps_generation DESC LIMIT 1`, m.NodeID, m.Epoch).Scan(&generation, &digest); err != nil { + if err := s.db.QueryRow(`SELECT apps_generation,apps_digest FROM lpcc.machine_app_deliveries WHERE node_id=$1 ORDER BY apps_generation DESC LIMIT 1`, m.NodeID).Scan(&generation, &digest); err != nil { t.Fatal(err) } newer := observationReport(m, a) @@ -176,7 +176,7 @@ func TestNonRunnerOrderDuplicateAgeClockAndCredentialScope(t *testing.T) { p := "/v1/nodes/" + m.NodeID + "/status" runner := observationReport(m, a) requireStatus(t, request(t, s, "POST", p, c["token"], runner), 200) - r := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), Epoch: m.Epoch, CredentialVersion: 1, Component: "app-reconciler", Generation: m.Generation, Sequence: 2, Reason: "failed", Apps: &contract.AppStatus{Reason: "state_recovery_failed", Instances: []contract.InstanceStatus{}}} + r := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), NodeID: m.NodeID, CredentialVersion: 1, Component: "app-reconciler", Generation: m.Generation, Sequence: 2, Reason: "failed", Apps: &contract.AppStatus{Reason: "state_recovery_failed", Instances: []contract.InstanceStatus{}}} requireStatus(t, request(t, s, "POST", p, c["token"], r), 200) var at, before time.Time s.db.QueryRow(`SELECT received_at FROM lpcc.machine_reports WHERE node_id=$1 AND component='app-reconciler'`, m.NodeID).Scan(&before) @@ -191,7 +191,7 @@ func TestNonRunnerOrderDuplicateAgeClockAndCredentialScope(t *testing.T) { r.ObservedAt = r.ObservedAt.Add(-time.Hour) r.Ready = true requireStatus(t, request(t, s, "POST", p, c["token"], r), 200) - stored, effective, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}), "app-reconciler") + stored, effective, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}), "app-reconciler") if err != nil || !stored.ClockUncertain || !effective.IsZero() { t.Fatal("clock regression attested readiness", stored, effective, err) } @@ -202,7 +202,7 @@ func TestNonRunnerOrderDuplicateAgeClockAndCredentialScope(t *testing.T) { runtime.Sequence = sequence runtime.ObservedAt = runtime.ObservedAt.Add(time.Second) requireStatus(t, request(t, s, "POST", p, c["token"], runtime), 200) - _, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}), "runtime") + _, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}), "runtime") if err != nil || (!at.IsZero() && time.Since(at) < 2*time.Minute) { t.Fatal("continuing old clock established fresh runtime readiness", at, err) } @@ -236,7 +236,7 @@ func TestNonRunnerOrderDuplicateAgeClockAndCredentialScope(t *testing.T) { } runtime.Sequence, runtime.ObservedAt = 6, time.Now().UTC() requireStatus(t, request(t, s, "POST", p, c["token"], runtime), 200) - recovered, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}), "runtime") + recovered, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}), "runtime") if err != nil || recovered.ClockUncertain || at.IsZero() || time.Since(at) > 2*time.Minute { t.Fatal("valid clock did not recover trusted observation", recovered, at, err) } @@ -247,7 +247,7 @@ func TestNonRunnerOrderDuplicateAgeClockAndCredentialScope(t *testing.T) { for _, sequence := range []uint64{5, 6} { r.Sequence, r.ClockUncertain, r.ObservedAt = sequence, true, time.Now().UTC() requireStatus(t, request(t, s, "POST", p, c["token"], r), 200) - stored, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}), "app-reconciler") + stored, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}), "app-reconciler") if err != nil || !stored.ClockUncertain || !at.IsZero() { t.Fatal("producer clock uncertainty discarded", stored, at, err) } @@ -285,7 +285,7 @@ func TestInvalidAppDownloadKeepsManagementReportsIngestible(t *testing.T) { handler := s.Handler() backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == p+"/config" { - w.Header().Set("X-Livepeer-Epoch", m.Epoch) + w.Header().Set("X-Livepeer-Node-ID", m.NodeID) w.Header().Set("X-Livepeer-Credential-Version", "1") _, _ = w.Write(data) return @@ -305,15 +305,15 @@ func TestInvalidAppDownloadKeepsManagementReportsIngestible(t *testing.T) { t.Fatal(err) } identity := filepath.Join(directory, "identity.json") - if err := os.WriteFile(identity, []byte(fmt.Sprintf(`{"epoch":%q,"credential_version":1}`, m.Epoch)), 0600); err != nil { + if err := os.WriteFile(identity, []byte(fmt.Sprintf(`{"node_id":%q,"credential_version":1}`, m.NodeID)), 0600); err != nil { t.Fatal(err) } reportDir := filepath.Join(directory, "reports") if err := os.MkdirAll(reportDir, 0700); err != nil { t.Fatal(err) } - counter := filepath.Join(reportDir, "runtime-"+strings.TrimPrefix(artifact.Digest([]byte(m.Epoch)), "sha256:")+".json") - if err := os.WriteFile(counter, []byte(fmt.Sprintf(`{"epoch":%q,"credential_version":1,"sequence":1}`, m.Epoch)), 0600); err != nil { + counter := filepath.Join(reportDir, "runtime-"+strings.TrimPrefix(artifact.Digest([]byte(m.NodeID)), "sha256:")+".json") + if err := os.WriteFile(counter, []byte(fmt.Sprintf(`{"node_id":%q,"credential_version":1,"sequence":1}`, m.NodeID)), 0600); err != nil { t.Fatal(err) } source := &httpsource.Source{IdentityFile: identity, Control: control, Reporter: &transport.Reports{Client: control, Directory: reportDir}, Kube: &transport.Kube{Base: kube.URL, Client: kube.Client()}, Store: artifact.Store{Directory: filepath.Join(directory, "artifacts")}, ArtifactURL: "http://adapter.invalid"} @@ -324,7 +324,7 @@ func TestInvalidAppDownloadKeepsManagementReportsIngestible(t *testing.T) { t.Fatal(err) } store := machineconfig.Store{DB: s.db} - machine := configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}) + machine := configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}) first, _, err := store.Report(t.Context(), machine, "runtime") if err != nil || first.Downloaded == nil || first.Downloaded.AppsDigest != m.AppsDigest { t.Fatal("valid predecessor missing", first, err) @@ -363,7 +363,7 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { s, c, m, a := observationFixture(t) prior := observationReport(m, a) requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/status", c["token"], prior), 200) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{"epoch": m.Epoch, "force": true}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+m.NodeID, "session-a", map[string]any{"force": true}), 202) if err := s.reconcile(t.Context()); err != nil { t.Fatal(err) } @@ -387,9 +387,9 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { prior.Apps.Assignments = nil prior.Apps.Instances[0].Reason = "cleanup_unconfirmed" requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/status", c["token"], prior), 200) - diagnosis := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), Epoch: m.Epoch, CredentialVersion: 1, Component: "app-reconciler", Generation: terminal.Generation, Sequence: 1, Reason: "failed", Apps: &contract.AppStatus{Reason: "state_recovery_failed", Instances: []contract.InstanceStatus{}}} + diagnosis := machineconfig.Report{ReportVersion: 1, ObservedAt: time.Now().UTC(), NodeID: m.NodeID, CredentialVersion: 1, Component: "app-reconciler", Generation: terminal.Generation, Sequence: 1, Reason: "failed", Apps: &contract.AppStatus{Reason: "state_recovery_failed", Instances: []contract.InstanceStatus{}}} requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/status", c["token"], diagnosis), 200) - read := "/api/machines/" + m.NodeID + "/status?epoch=" + m.Epoch + read := "/api/machines/" + m.NodeID + "/status" w = request(t, s, "GET", read, "session-a", nil) requireStatus(t, w, 200) if !strings.Contains(w.Body.String(), "cleanup_unconfirmed") { @@ -397,7 +397,7 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { } list := request(t, s, "GET", "/api/machines", "session-a", nil) requireStatus(t, list, 200) - if !strings.Contains(list.Body.String(), m.Epoch) || !strings.Contains(list.Body.String(), "cleanup_pending") { + if !strings.Contains(list.Body.String(), m.NodeID) || !strings.Contains(list.Body.String(), "cleanup_pending") { t.Fatal("pending retirement disappeared") } prior.Sequence++ @@ -405,7 +405,7 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/status", c["token"], prior), 409) prior.Drained = false replacement := enroll(t, s, ownerB, strings.Repeat("a", 64)) - if replacement["node_id"] != m.NodeID || replacement["epoch"] == m.Epoch { + if replacement["node_id"] == m.NodeID { t.Fatal("expected replacement enrollment") } if _, err := s.db.Exec(`UPDATE lpcc.administrator_grants SET revoked_at=now() WHERE bound_user_id=$1`, ownerA); err != nil { @@ -413,8 +413,8 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { } requireStatus(t, request(t, s, "GET", read, "session-b", nil), 404) requireStatus(t, request(t, s, "GET", read, "session-a", nil), 200) - requireStatus(t, request(t, s, "GET", "/api/machines/"+m.NodeID+"/status?epoch="+replacement["epoch"], "session-a", nil), 404) - requireStatus(t, request(t, s, "GET", "/api/machines/"+m.NodeID+"/status?epoch="+replacement["epoch"], "session-b", nil), 200) + requireStatus(t, request(t, s, "GET", "/api/machines/"+replacement["node_id"]+"/status", "session-a", nil), 404) + requireStatus(t, request(t, s, "GET", "/api/machines/"+replacement["node_id"]+"/status", "session-b", nil), 200) prior.Sequence++ requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/status", c["token"], prior), 200) var removal schema.AppAssignmentSetV1 @@ -424,10 +424,10 @@ func TestTerminalDiagnosticsRetainEarlierInstanceLineage(t *testing.T) { for _, a := range removal.Entries { requireStatus(t, appReport(t, s, c, a, terminal.AppsDigest, "removed"), 200) } - requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/removal-ack", c["token"], map[string]any{"epoch": m.Epoch, "digest": terminalDigest, "connector_absent": true}), 200) + requireStatus(t, request(t, s, "POST", "/v1/nodes/"+m.NodeID+"/removal-ack", c["token"], map[string]any{"node_id": m.NodeID, "digest": terminalDigest, "connector_absent": true}), 200) list = request(t, s, "GET", "/api/machines", "session-a", nil) requireStatus(t, list, 200) - if strings.Contains(list.Body.String(), m.Epoch) { + if strings.Contains(list.Body.String(), m.NodeID) { t.Fatal("acknowledged retired enrollment still listed") } @@ -473,7 +473,7 @@ func TestObservedStateComposesExactDiscoveryMembership(t *testing.T) { } route := tunnel.RoutingState{ServiceURL: "https://orch.example", ProxyURLTemplate: "https://{proxy}.apps.example"} raw, _ := json.Marshal(route) - if _, err := s.db.Exec(`UPDATE lpcc.machine_states SET state=$3 WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch, string(raw)); err != nil { + if _, err := s.db.Exec(`UPDATE lpcc.machine_states SET state=$2 WHERE node_id=$1`, m.NodeID, string(raw)); err != nil { t.Fatal(err) } report := observationReport(m, shot) @@ -488,7 +488,7 @@ func TestObservedStateComposesExactDiscoveryMembership(t *testing.T) { var version atomic.Value version.Store("wrong-version") f, err := fleet.New(fleet.Config{RefreshInterval: time.Second, ReconcileInterval: time.Minute}, fleet.Dependencies{ - Store: statusDiscoverySource{fleet.Source{ID: "source", NodeID: m.NodeID, Epoch: m.Epoch, URL: "https://source.example/discovery", ServiceURL: route.ServiceURL, ProxyURLTemplate: route.ProxyURLTemplate, AuthMode: fleet.AuthNone, Lifecycle: "active", Ready: true, Generation: 1, VerifiedGeneration: 1}}, Logger: s.logger, + Store: statusDiscoverySource{fleet.Source{NodeID: m.NodeID, URL: "https://source.example/discovery", ServiceURL: route.ServiceURL, ProxyURLTemplate: route.ProxyURLTemplate, AuthMode: fleet.AuthNone, Lifecycle: "active", Ready: true, Generation: 1, VerifiedGeneration: 1}}, Logger: s.logger, Transport: fleetRoundTripFunc(func(*http.Request) (*http.Response, error) { body := `[{"address":"https://orch.example","runners":[{"url":"https://shot-app.apps.example","app":"whoami","version":"1","observed_at":"` + time.Now().UTC().Format(time.RFC3339Nano) + `"},{"url":"https://orch.example/apps/persistent-app/session","app":"whoami-persistent","version":"` + version.Load().(string) + `","observed_at":"` + time.Now().UTC().Format(time.RFC3339Nano) + `"}]}]` return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil @@ -511,7 +511,7 @@ func TestObservedStateComposesExactDiscoveryMembership(t *testing.T) { } deadline := time.Now().Add(5 * time.Second) for { - w := request(t, s, "GET", "/api/machines/"+m.NodeID+"/status?epoch="+m.Epoch, "session-a", nil) + w := request(t, s, "GET", "/api/machines/"+m.NodeID+"/status", "session-a", nil) requireStatus(t, w, 200) var view machineObservation if err := json.Unmarshal(w.Body.Bytes(), &view); err != nil { @@ -531,14 +531,14 @@ func TestObservedStateComposesExactDiscoveryMembership(t *testing.T) { func TestLargeObservedReportCrossesRelayAndIngestion(t *testing.T) { s, c, m, a := observationFixture(t) store := machineconfig.Store{DB: s.db} - state, err := store.Load(t.Context(), m.NodeID, m.Epoch) + state, err := store.Load(t.Context(), m.NodeID) if err != nil { t.Fatal(err) } now := time.Now().UTC() state.DrainRequested, state.DrainStartedAt = true, now.Add(-time.Second) raw, _ := json.Marshal(state.State) - if _, err := s.db.Exec(`UPDATE lpcc.machine_states SET rollout=$3 WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch, string(raw)); err != nil { + if _, err := s.db.Exec(`UPDATE lpcc.machine_states SET rollout=$2 WHERE node_id=$1`, m.NodeID, string(raw)); err != nil { t.Fatal(err) } backend := httptest.NewServer(s.Handler()) @@ -554,7 +554,7 @@ func TestLargeObservedReportCrossesRelayAndIngestion(t *testing.T) { relay := management.AppReports{Control: control, Desired: func() (contract.Metadata, bool) { return m, true }} r := observationReport(m, a) r.Drained, r.Ready, r.Reason = true, false, "drain_pending" - r.Evidence = &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(m.NodeID, m.Epoch, state.State), OwnerID: "retained-owner", CredentialFingerprint: "sha256:" + strings.Repeat("f", 64), WithdrawalID: "withdrawal", MutationSequence: new(uint64(0)), ObservedAt: now, ExpiresAt: now.Add(time.Minute)} + r.Evidence = &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(m.NodeID, state.State), OwnerID: "retained-owner", CredentialFingerprint: "sha256:" + strings.Repeat("f", 64), WithdrawalID: "withdrawal", MutationSequence: new(uint64(0)), ObservedAt: now, ExpiresAt: now.Add(time.Minute)} proof := *r.Evidence r.Apps.Instances = nil r.Apps.Assignments[0].Instances, r.Apps.Assignments[0].Ready, r.Apps.Assignments[0].Registered = 128, 0, 0 @@ -591,7 +591,7 @@ func TestLargeObservedReportCrossesRelayAndIngestion(t *testing.T) { w := httptest.NewRecorder() relay.ServeHTTP(w, httptest.NewRequest("POST", "http://management/status", bytes.NewReader(body))) requireStatus(t, w, 200) - stored, _, err := store.Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, Epoch: m.Epoch, CredentialVersion: 1}), "runner") + stored, _, err := store.Report(t.Context(), configurationMachine(Machine{NodeID: m.NodeID, CredentialVersion: 1}), "runner") if err != nil || stored.Evidence == nil || !reflect.DeepEqual(*stored.Evidence, proof) || len(stored.Apps.Instances) != len(r.Apps.Instances) || stored.Apps.InstancesOmitted != r.Apps.InstancesOmitted || stored.Apps.InstancesTotal != 128 { t.Fatal("relay/ingestion changed bounded state or proof", len(body), stored, err) } diff --git a/api/internal/controlplane/onchain_credentials.go b/api/internal/controlplane/onchain_credentials.go index 5ef1083..f7e4428 100644 --- a/api/internal/controlplane/onchain_credentials.go +++ b/api/internal/controlplane/onchain_credentials.go @@ -43,7 +43,7 @@ func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { } defer tx.Rollback() var current int64 - e = tx.QueryRowContext(r.Context(), `SELECT credential_version FROM lpcc.machines WHERE node_id=$1 AND enrollment_epoch=$2 FOR UPDATE`, m.NodeID, m.Epoch).Scan(¤t) + e = tx.QueryRowContext(r.Context(), `SELECT credential_version FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, m.NodeID).Scan(¤t) if e != nil || current != m.CredentialVersion { fail(w, 409, "enrollment changed") return @@ -59,7 +59,7 @@ func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { if e == nil { metadata, e = transport.ReadMetadata(files["runtime.json"]) } - if e != nil || metadata.Epoch != m.Epoch || metadata.CredentialVersion != m.CredentialVersion || !metadata.Onchain.Onchain() || metadata.Onchain.Generation != in.OnchainGeneration || metadata.ConfigDigest != in.ConfigDigest { + if e != nil || metadata.NodeID != m.NodeID || metadata.CredentialVersion != m.CredentialVersion || !metadata.Onchain.Onchain() || metadata.Onchain.Generation != in.OnchainGeneration || metadata.ConfigDigest != in.ConfigDigest { fail(w, 409, "onchain configuration changed") return } @@ -76,13 +76,13 @@ func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { return } var initialized bool - if e = tx.QueryRowContext(r.Context(), `SELECT initialized FROM lpcc.onchain_state WHERE node_id=$1`, m.NodeID).Scan(&initialized); e != nil { + if e = tx.QueryRowContext(r.Context(), `SELECT initialized FROM lpcc.onchain_state WHERE fingerprint=(SELECT fingerprint FROM lpcc.enrollments WHERE node_id=$1)`, m.NodeID).Scan(&initialized); e != nil { s.databaseError(w, e) return } id := uuid.New().String() var revoked sql.NullTime - e = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.onchain_grants(grant_id,node_id,epoch,onchain_generation,config_digest,pod_uid,launch_id,process_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(node_id,epoch,onchain_generation,pod_uid,launch_id,process_id) DO UPDATE SET grant_id=lpcc.onchain_grants.grant_id RETURNING grant_id::text,revoked_at`, id, m.NodeID, m.Epoch, in.OnchainGeneration, in.ConfigDigest, in.PodUID, in.LaunchID, in.ProcessID).Scan(&id, &revoked) + e = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.onchain_grants(grant_id,node_id,onchain_generation,config_digest,pod_uid,launch_id,process_id) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(node_id,onchain_generation,pod_uid,launch_id,process_id) DO UPDATE SET grant_id=lpcc.onchain_grants.grant_id RETURNING grant_id::text,revoked_at`, id, m.NodeID, in.OnchainGeneration, in.ConfigDigest, in.PodUID, in.LaunchID, in.ProcessID).Scan(&id, &revoked) if e != nil { s.databaseError(w, e) return @@ -95,7 +95,7 @@ func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { s.databaseError(w, e) return } - respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, OnchainGeneration: in.OnchainGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) + respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, CredentialVersion: m.CredentialVersion, OnchainGeneration: in.OnchainGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) } func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { @@ -132,7 +132,7 @@ func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { allowed := count == 1 && ok && appID(id) && len(s.params.MachineTokenSecret) >= 32 && hmac.Equal([]byte(token), []byte(s.submissionToken(id))) && json.Unmarshal(in.Ticket, &ticket) == nil && onchain.Address.MatchString(ticket.Recipient) if allowed { var recipient string - e := s.db.QueryRowContext(r.Context(), `SELECT v.config->>'recipient' FROM lpcc.onchain_grants g JOIN lpcc.onchain_configs v ON v.node_id=g.node_id AND v.generation=g.onchain_generation JOIN lpcc.machines m ON m.node_id=g.node_id AND m.enrollment_epoch=g.epoch WHERE g.grant_id=$1 AND g.revoked_at IS NULL`, id).Scan(&recipient) + e := s.db.QueryRowContext(r.Context(), `SELECT v.config->>'recipient' FROM lpcc.onchain_grants g JOIN lpcc.machines m ON m.node_id=g.node_id JOIN lpcc.onchain_configs v ON v.fingerprint=m.fingerprint AND v.generation=g.onchain_generation WHERE g.grant_id=$1 AND g.revoked_at IS NULL`, id).Scan(&recipient) allowed = e == nil && strings.EqualFold(recipient, ticket.Recipient) } status := 403 @@ -159,7 +159,7 @@ func (s *Server) observeOnchainGrant(ctx context.Context, m Machine, reportOncha } defer tx.Rollback() var b []byte - e = tx.QueryRowContext(ctx, `SELECT c.bundle FROM lpcc.machines m JOIN lpcc.machine_configs c USING(node_id) WHERE m.node_id=$1 AND m.enrollment_epoch=$2 AND m.credential_version=$3 FOR UPDATE OF m`, m.NodeID, m.Epoch, m.CredentialVersion).Scan(&b) + e = tx.QueryRowContext(ctx, `SELECT c.bundle FROM lpcc.machines m JOIN lpcc.machine_configs c USING(node_id) WHERE m.node_id=$1 AND m.credential_version=$2 FOR UPDATE OF m`, m.NodeID, m.CredentialVersion).Scan(&b) if errors.Is(e, sql.ErrNoRows) { return nil } @@ -180,26 +180,26 @@ func (s *Server) observeOnchainGrant(ctx context.Context, m Machine, reportOncha if p.Mode == "offchain" { // The replacement has no submission bearer to observe. Retire the held // onchain workload's grants only after its offchain successor is applied. - _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL`, m.NodeID, m.Epoch) + _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND revoked_at IS NULL`, m.NodeID) if e != nil { return e } return tx.Commit() } var id string - e = tx.QueryRowContext(ctx, `UPDATE lpcc.onchain_grants SET observed_at=now() WHERE grant_id=$1 AND node_id=$2 AND epoch=$3 AND onchain_generation=$4 AND config_digest=$5 AND pod_uid=$6 AND revoked_at IS NULL RETURNING grant_id::text`, p.GrantID, m.NodeID, m.Epoch, p.Generation, digest, p.PodUID).Scan(&id) + e = tx.QueryRowContext(ctx, `UPDATE lpcc.onchain_grants SET observed_at=now() WHERE grant_id=$1 AND node_id=$2 AND onchain_generation=$3 AND config_digest=$4 AND pod_uid=$5 AND revoked_at IS NULL RETURNING grant_id::text`, p.GrantID, m.NodeID, p.Generation, digest, p.PodUID).Scan(&id) if errors.Is(e, sql.ErrNoRows) { return nil } if e != nil { return e } - _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND epoch=$2 AND grant_id<>$3 AND revoked_at IS NULL AND issued_sequence<(SELECT issued_sequence FROM lpcc.onchain_grants WHERE grant_id=$3)`, m.NodeID, m.Epoch, id) + _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_grants SET revoked_at=now() WHERE node_id=$1 AND grant_id<>$2 AND revoked_at IS NULL AND issued_sequence<(SELECT issued_sequence FROM lpcc.onchain_grants WHERE grant_id=$2)`, m.NodeID, id) if e != nil { return e } if p.Ready { - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET initialized=true WHERE node_id=$1`, m.NodeID); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.onchain_state SET initialized=true WHERE fingerprint=(SELECT fingerprint FROM lpcc.enrollments WHERE node_id=$1)`, m.NodeID); e != nil { return e } } diff --git a/api/internal/controlplane/onchain_settings.go b/api/internal/controlplane/onchain_settings.go index c4aef48..fa6e1be 100644 --- a/api/internal/controlplane/onchain_settings.go +++ b/api/internal/controlplane/onchain_settings.go @@ -26,9 +26,13 @@ import ( ) func loadOnchain(ctx context.Context, q rowQuerier, node string) (onchain.Config, error) { + return loadInstallationOnchain(ctx, q, `(SELECT fingerprint FROM lpcc.enrollments WHERE node_id=$1)`, node) +} + +func loadInstallationOnchain(ctx context.Context, q rowQuerier, key, identity string) (onchain.Config, error) { c := onchain.Offchain() var b []byte - err := q.QueryRowContext(ctx, `SELECT c.config FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.node_id=b.node_id AND c.generation=b.generation WHERE b.node_id=$1`, node).Scan(&b) + err := q.QueryRowContext(ctx, `SELECT c.config FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.fingerprint=b.fingerprint AND c.generation=b.generation WHERE b.fingerprint=`+key, identity).Scan(&b) if errors.Is(err, sql.ErrNoRows) { return c, nil } @@ -125,7 +129,7 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected c.Controller = strings.ToLower(c.Controller) c.ETHUSDFeed = strings.ToLower(c.ETHUSDFeed) input.Machines[node] = c - if !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(node) || c.Generation != 0 { + if !fingerprintPattern.MatchString(node) || c.Generation != 0 { return 0, errors.New("invalid onchain machine identity") } if e := c.Validate(); e != nil { @@ -162,7 +166,7 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected } // Import is a complete desired snapshot: omission never silently disables onchain service. - rows, e := tx.QueryContext(ctx, `SELECT b.node_id FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.node_id=b.node_id AND c.generation=b.generation WHERE c.config->>'mode'='onchain'`) + rows, e := tx.QueryContext(ctx, `SELECT b.fingerprint FROM lpcc.onchain_state b JOIN lpcc.onchain_configs c ON c.fingerprint=b.fingerprint AND c.generation=b.generation WHERE c.config->>'mode'='onchain'`) if e != nil { return 0, e } @@ -199,7 +203,7 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected changed := false for _, node := range nodes { c := input.Machines[node] - old, e := loadOnchain(ctx, tx, node) + old, e := loadInstallationOnchain(ctx, tx, "$1", node) if e != nil { return 0, e } @@ -210,13 +214,13 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected continue } // Same locking order as assignment mutation and configuration publication. - var epoch string - e = tx.QueryRowContext(ctx, `SELECT enrollment_epoch::text FROM lpcc.machines WHERE node_id=$1 FOR UPDATE`, node).Scan(&epoch) + var activeNode string + e = tx.QueryRowContext(ctx, `SELECT node_id FROM lpcc.machines WHERE fingerprint=$1 FOR UPDATE`, node).Scan(&activeNode) if e != nil && !errors.Is(e, sql.ErrNoRows) { return 0, e } - if epoch != "" { - a, e := machineapps.Snapshot(ctx, tx, node, epoch) + if activeNode != "" { + a, e := machineapps.Snapshot(ctx, tx, activeNode) if e != nil { return 0, e } @@ -232,7 +236,7 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected } var recipient, controller string var chain uint64 - e = tx.QueryRowContext(ctx, `SELECT recipient,chain_id,controller FROM lpcc.onchain_state WHERE node_id=$1 FOR UPDATE`, node).Scan(&recipient, &chain, &controller) + e = tx.QueryRowContext(ctx, `SELECT recipient,chain_id,controller FROM lpcc.onchain_state WHERE fingerprint=$1 FOR UPDATE`, node).Scan(&recipient, &chain, &controller) if e != nil && !errors.Is(e, sql.ErrNoRows) { return 0, e } @@ -251,11 +255,11 @@ func (s *Server) applyOnchain(ctx context.Context, input onchainInput, expected if _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_configs VALUES($1,$2,$3)`, node, c.Generation, string(after)); e != nil { return 0, e } - _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_state(node_id,recipient,chain_id,controller,generation) VALUES($1,$2,$3,$4,$5) ON CONFLICT(node_id) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation`, node, recipient, chain, controller, c.Generation) + _, e = tx.ExecContext(ctx, `INSERT INTO lpcc.onchain_state(fingerprint,recipient,chain_id,controller,generation) VALUES($1,$2,$3,$4,$5) ON CONFLICT(fingerprint) DO UPDATE SET recipient=EXCLUDED.recipient,chain_id=EXCLUDED.chain_id,controller=EXCLUDED.controller,generation=EXCLUDED.generation`, node, recipient, chain, controller, c.Generation) if e != nil { return 0, e } - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, node); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.machine_states SET revision=revision+1,next_attempt_at=now() WHERE node_id=$1`, activeNode); e != nil { return 0, e } if e = writeAudit(ctx, tx, "system", "deployment:onchain", "onchain.apply", AdminTarget{Kind: "machine", ID: node, Revision: revisionString(c.Generation)}, "success", "changed"); e != nil { diff --git a/api/internal/controlplane/onchain_test.go b/api/internal/controlplane/onchain_test.go index 786a70b..9f078f6 100644 --- a/api/internal/controlplane/onchain_test.go +++ b/api/internal/controlplane/onchain_test.go @@ -28,8 +28,8 @@ func onchainSettings(t *testing.T, s *Server) onchain.Config { func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" - in := onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}} + node := strings.Repeat("a", 64) + in := onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}} if rev, e := s.applyOnchain(t.Context(), in, 0); e != nil || rev != 1 { t.Fatal(rev, e) } @@ -41,7 +41,7 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { } stale := c stale.CredentialRevision++ - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: stale}}, 0); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): stale}}, 0); e == nil { t.Fatal("stale edit accepted") } var n int @@ -50,13 +50,13 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { } // Omission and immutable bindings fail without committing another audit event. other := onchain.Offchain() - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{"lp-bbbbbbbbbbbbbbbb": other}}, 1); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{strings.Repeat("b", 64): other}}, 1); e == nil { t.Fatal("omission disabled onchain machine") } for _, mutate := range []func(*onchain.Config){func(c *onchain.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *onchain.Config) { c.ChainID++ }, func(c *onchain.Config) { c.TicketWinProb = "0" }} { next := c mutate(&next) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: next}}, 1); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): next}}, 1); e == nil { t.Fatal("invalid change accepted") } } @@ -75,7 +75,7 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { c := onchainSettings(t, s) machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) node := machine["node_id"] - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}}, 0); e != nil { t.Fatal(e) } cfg, e := loadOnchain(t.Context(), s.db, node) @@ -84,7 +84,7 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { } // Install an applying bundle; this test exercises the real API boundary, not // Kubernetes attestation (covered by the Runtime consumer tests). - desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: machine["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: cfg, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: cfg, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} b, digest, e := machineconfig.Build(desired) if e != nil { t.Fatal(e) @@ -150,11 +150,11 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { t.Fatal("forced retirement did not revoke") } fresh := enroll(t, s, ownerA, strings.Repeat("a", 64)) - if fresh["epoch"] == machine["epoch"] { + if fresh["node_id"] == machine["node_id"] { t.Fatal("enrollment not replaced") } c.Recipient = "0x" + strings.Repeat("3", 40) - if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: c}}, 1); e == nil { + if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}}, 1); e == nil { t.Fatal("re-enrollment reset pinned recipient") } } @@ -162,11 +162,13 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { func TestOnchainActivationAndNormalDrain(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { + node := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { t.Fatal(e) } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) + node = c["node_id"] + node = c["node_id"] if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -198,7 +200,7 @@ func TestOnchainActivationAndNormalDrain(t *testing.T) { report := func() { t.Helper() m := metadata() - r := currentReport(t, s, node, machineconfig.Report{Epoch: c["epoch"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Onchain: &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, Handoff: "unverified"}}) + r := currentReport(t, s, node, machineconfig.Report{NodeID: c["node_id"], CredentialVersion: 1, Component: "runtime", Generation: m.Generation, ConfigDigest: m.ConfigDigest, K3sVersion: "v1.37.2+k3s1", Ready: true, Reason: "ready", Onchain: &onchain.Observation{Generation: m.Onchain.Generation, Mode: "onchain", PodUID: "node-pod", GrantID: grant.GrantID, Applied: true, Ready: true, Handoff: "unverified"}}) requireStatus(t, request(t, s, "POST", "/v1/nodes/"+node+"/status", c["token"], r), 200) } report() @@ -209,7 +211,7 @@ func TestOnchainActivationAndNormalDrain(t *testing.T) { t.Fatal("fresh applied Node did not activate") } adminA(t, s) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+node, "session-a", map[string]any{"epoch": c["epoch"]}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+node, "session-a", map[string]any{}), 202) if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -226,11 +228,13 @@ func TestOnchainActivationAndNormalDrain(t *testing.T) { func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { + node := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { t.Fatal(e) } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) + node = c["node_id"] + node = c["node_id"] var b []byte if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { t.Fatal(e) @@ -277,7 +281,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { } off := onchain.Offchain() off.Generation = m.Onchain.Generation + 1 - desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, Epoch: c["epoch"], CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: off, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} + desired := machineconfig.Desired{Machine: machineconfig.Machine{NodeID: node, CredentialVersion: 1, InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1"}, Onchain: off, RuntimeImage: s.params.RuntimeImage, NodeImage: s.params.RuntimeNodeImage} b, digest, e := machineconfig.Build(desired) if e != nil { t.Fatal(e) @@ -306,7 +310,7 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { func TestOnchainIsolationAndGenericCatalogCompatibility(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - onchainNode := "lp-aaaaaaaaaaaaaaaa" + onchainNode := strings.Repeat("a", 64) if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{onchainNode: cfg}}, 0); e != nil { t.Fatal(e) } @@ -339,13 +343,13 @@ func TestOnchainIsolationAndGenericCatalogCompatibility(t *testing.T) { func TestConcurrentOnchainApplyCannotCommitTwoDifferentTargets(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" + node := strings.Repeat("a", 64) errors := make(chan error, 2) for n := range 2 { copy := c copy.CredentialRevision = uint64(n + 1) go func() { - _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: copy}}, 0) + _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): copy}}, 0) errors <- e }() } @@ -366,11 +370,11 @@ func TestConcurrentOnchainApplyCannotCommitTwoDifferentTargets(t *testing.T) { func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := "lp-aaaaaaaaaaaaaaaa" - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: cfg}}, 0); e != nil { + node := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { t.Fatal(e) } - enroll(t, s, ownerA, strings.Repeat("a", 64)) + node = enroll(t, s, ownerA, strings.Repeat("a", 64))["node_id"] read := func() contract.Metadata { t.Helper() var b []byte @@ -394,7 +398,7 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) if after.ConfigDigest == before.ConfigDigest || !after.Onchain.Onchain() || after.OnchainActive || after.Onchain.Generation != before.Onchain.Generation { t.Fatal("unapproved onchain target could not repair its image under the same onchain binding", after) } - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{node: onchain.Offchain()}}, 1); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): onchain.Offchain()}}, 1); e != nil { t.Fatal(e) } if e := s.reconcile(t.Context()); e != nil { @@ -404,3 +408,15 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) t.Fatal("failed onchain startup bypassed normal drain to offchain") } } + +func installationFingerprint(t *testing.T, s *Server, node string) string { + t.Helper() + if fingerprintPattern.MatchString(node) { + return node + } + var fingerprint string + if err := s.db.QueryRow(`SELECT fingerprint FROM lpcc.enrollments WHERE node_id=$1`, node).Scan(&fingerprint); err != nil { + t.Fatal(err) + } + return fingerprint +} diff --git a/api/internal/controlplane/registry_test.go b/api/internal/controlplane/registry_test.go index f2ea775..2dbb5dd 100644 --- a/api/internal/controlplane/registry_test.go +++ b/api/internal/controlplane/registry_test.go @@ -168,7 +168,7 @@ func TestRegistryPolicyAndBindingSeam(t *testing.T) { t.Fatal(err) } defer tx.Rollback() - _, err = revisionForBinding(t.Context(), tx, current, ref, "lp-0000000000000001") + _, err = revisionForBinding(t.Context(), tx, current, ref, "aaaaaaaaaaaacaaaaaaaaaaaaa") if want == 200 && err != nil { t.Fatal(err) } diff --git a/api/internal/controlplane/server.go b/api/internal/controlplane/server.go index 3abae63..7c6a7cd 100644 --- a/api/internal/controlplane/server.go +++ b/api/internal/controlplane/server.go @@ -2,8 +2,10 @@ package controlplane import ( "context" + "crypto/rand" "database/sql" "embed" + "encoding/base32" "encoding/json" "errors" "io" @@ -35,7 +37,6 @@ type Machine struct { K3sVersion string `json:"k3s_version"` CreatedAt time.Time `json:"created_at"` LastConfigFetchAt *time.Time `json:"last_config_fetch_at"` - Epoch string `json:"-"` CredentialVersion int64 `json:"-"` Terminal bool `json:"-"` DevelopmentHTTP bool `json:"development_http,omitempty"` @@ -198,7 +199,12 @@ func (s *Server) register(w http.ResponseWriter, r *http.Request) { fail(w, 400, "invalid machine metadata") return } - m.NodeID = "lp-" + m.Fingerprint[:16] + var id [16]byte + if _, err = rand.Read(id[:]); err != nil { + fail(w, 500, "cannot generate node identity") + return + } + m.NodeID = strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(id[:])) m.OwnerID = owner tx, err := s.db.BeginTx(r.Context(), nil) if err != nil { @@ -206,14 +212,14 @@ func (s *Server) register(w http.ResponseWriter, r *http.Request) { return } defer tx.Rollback() - // The unique node ID also catches truncated fingerprint collisions. An existing - // row is reusable only by the same owner with the same installation identity. + // An active installation retains its ID on retry. A retired installation gets + // a fresh ID; its retained cleanup records remain scoped to the previous ID. row := tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.machines(node_id,fingerprint,owner_id,hostname,install_dir,k3s_version,credential_version,tunnel_eligible) VALUES($1,$2,$3,$4,$5,$6,1,$7) - ON CONFLICT(node_id) DO UPDATE SET hostname=EXCLUDED.hostname,updated_at=now() + ON CONFLICT(fingerprint) DO UPDATE SET hostname=EXCLUDED.hostname,updated_at=now() WHERE lpcc.machines.owner_id=EXCLUDED.owner_id AND lpcc.machines.fingerprint=EXCLUDED.fingerprint AND lpcc.machines.install_dir=EXCLUDED.install_dir AND lpcc.machines.k3s_version=EXCLUDED.k3s_version - RETURNING enrollment_epoch::text,credential_version`, m.NodeID, m.Fingerprint, owner, m.Hostname, m.InstallDir, m.K3sVersion, strings.HasPrefix(s.params.PublicAPIURL, "https://") && !m.DevelopmentHTTP) - err = row.Scan(&m.Epoch, &m.CredentialVersion) + RETURNING node_id,credential_version`, m.NodeID, m.Fingerprint, owner, m.Hostname, m.InstallDir, m.K3sVersion, strings.HasPrefix(s.params.PublicAPIURL, "https://") && !m.DevelopmentHTTP) + err = row.Scan(&m.NodeID, &m.CredentialVersion) if errors.Is(err, sql.ErrNoRows) { fail(w, 409, "machine already registered with a different owner or installation") return @@ -222,7 +228,11 @@ func (s *Server) register(w http.ResponseWriter, r *http.Request) { s.databaseError(w, err) return } - if _, err = tx.ExecContext(r.Context(), `INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(node_id,epoch) DO NOTHING`, m.NodeID, m.Epoch, m.OwnerID, m.Fingerprint, m.Hostname, m.InstallDir, m.K3sVersion, m.CredentialVersion); err != nil { + // A random collision with a retained node must fail, never reuse cleanup state. + if err = tx.QueryRowContext(r.Context(), `INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version) VALUES($1,$2,$3,$4,$5,$6,$7) + ON CONFLICT(node_id) DO UPDATE SET hostname=EXCLUDED.hostname + WHERE lpcc.enrollments.retired_at IS NULL AND lpcc.enrollments.owner_id=EXCLUDED.owner_id AND lpcc.enrollments.fingerprint=EXCLUDED.fingerprint + RETURNING node_id`, m.NodeID, m.OwnerID, m.Fingerprint, m.Hostname, m.InstallDir, m.K3sVersion, m.CredentialVersion).Scan(&m.NodeID); err != nil { s.databaseError(w, err) return } @@ -244,7 +254,7 @@ func (s *Server) register(w http.ResponseWriter, r *http.Request) { } func (s *Server) machineCredentials(m Machine) map[string]any { - return map[string]any{"node_id": m.NodeID, "epoch": m.Epoch, "credential_version": m.CredentialVersion, "token": s.enrollmentToken(m), "config_url": strings.TrimRight(s.params.PublicAPIURL, "/") + "/v1/nodes/" + m.NodeID + "/config"} + return map[string]any{"node_id": m.NodeID, "credential_version": m.CredentialVersion, "token": s.enrollmentToken(m), "config_url": strings.TrimRight(s.params.PublicAPIURL, "/") + "/v1/nodes/" + m.NodeID + "/config"} } func (s *Server) configuration(w http.ResponseWriter, r *http.Request) { @@ -256,9 +266,9 @@ func (s *Server) configuration(w http.ResponseWriter, r *http.Request) { var digest string var data []byte if m.Terminal { - err = s.db.QueryRowContext(r.Context(), `SELECT terminal_bundle,terminal_sha256 FROM lpcc.enrollments WHERE node_id=$1 AND epoch=$2 AND terminal_bundle IS NOT NULL`, m.NodeID, m.Epoch).Scan(&data, &digest) + err = s.db.QueryRowContext(r.Context(), `SELECT terminal_bundle,terminal_sha256 FROM lpcc.enrollments WHERE node_id=$1 AND terminal_bundle IS NOT NULL`, m.NodeID).Scan(&data, &digest) } else { - err = s.db.QueryRowContext(r.Context(), `SELECT c.bundle,c.sha256 FROM lpcc.machine_configs c JOIN lpcc.machines m USING(node_id) WHERE m.node_id=$1 AND m.enrollment_epoch=$2`, m.NodeID, m.Epoch).Scan(&data, &digest) + err = s.db.QueryRowContext(r.Context(), `SELECT c.bundle,c.sha256 FROM lpcc.machine_configs c JOIN lpcc.machines m USING(node_id) WHERE m.node_id=$1`, m.NodeID).Scan(&data, &digest) } if errors.Is(err, sql.ErrNoRows) { fail(w, 404, "machine configuration not found") @@ -268,15 +278,15 @@ func (s *Server) configuration(w http.ResponseWriter, r *http.Request) { s.databaseError(w, err) return } - if _, err := s.db.ExecContext(r.Context(), `UPDATE lpcc.machines SET last_config_fetch_at=now() WHERE node_id=$1 AND enrollment_epoch=$2`, m.NodeID, m.Epoch); err != nil { + if _, err := s.db.ExecContext(r.Context(), `UPDATE lpcc.machines SET last_config_fetch_at=now() WHERE node_id=$1`, m.NodeID); err != nil { s.databaseError(w, err) return } w.Header().Set("Content-Type", "application/gzip") w.Header().Set("ETag", `"`+digest+`"`) - w.Header().Set("X-Livepeer-Epoch", m.Epoch) + w.Header().Set("X-Livepeer-Node-ID", m.NodeID) if m.Terminal { - pending, err := machineapps.Pending(r.Context(), s.db, m.NodeID, m.Epoch) + pending, err := machineapps.Pending(r.Context(), s.db, m.NodeID) if err != nil { s.databaseError(w, err) return diff --git a/api/internal/controlplane/tunnel/certificates.go b/api/internal/controlplane/tunnel/certificates.go index a498120..aa61718 100644 --- a/api/internal/controlplane/tunnel/certificates.go +++ b/api/internal/controlplane/tunnel/certificates.go @@ -229,7 +229,7 @@ func (l *tunnelLease) ensureCertificate(ctx context.Context, template string) (b defer cert.close() // Fence acquisition against machine retirement and superseded workers. var node string - err = l.s.db.QueryRowContext(ctx, `INSERT INTO lpcc.machine_certificate_refs(zone_id,wildcard_host,node_id,epoch) SELECT $1,$2,$3,$4 WHERE EXISTS(SELECT FROM lpcc.machine_states s JOIN lpcc.enrollments e USING(node_id,epoch) WHERE s.node_id=$3 AND s.epoch=$4 AND s.lease_id=$5 AND s.revision=$6 AND s.lease_until>now() AND e.retired_at IS NULL) ON CONFLICT(zone_id,wildcard_host,node_id,epoch) DO UPDATE SET node_id=EXCLUDED.node_id RETURNING node_id`, l.state.ZoneID, wildcard, l.Machine.NodeID, l.Machine.Epoch, l.Lease.ID, l.Revision).Scan(&node) + err = l.s.db.QueryRowContext(ctx, `INSERT INTO lpcc.machine_certificate_refs(zone_id,wildcard_host,node_id) SELECT $1,$2,$3 WHERE EXISTS(SELECT FROM lpcc.machine_states s JOIN lpcc.enrollments e USING(node_id) WHERE s.node_id=$3 AND s.lease_id=$4 AND s.revision=$5 AND s.lease_until>now() AND e.retired_at IS NULL) ON CONFLICT(zone_id,wildcard_host,node_id) DO UPDATE SET node_id=EXCLUDED.node_id RETURNING node_id`, l.state.ZoneID, wildcard, l.Machine.NodeID, l.Lease.ID, l.Revision).Scan(&node) if errors.Is(err, sql.ErrNoRows) { return false, errTunnelFenced } @@ -248,7 +248,7 @@ func (l *tunnelLease) ensureCertificate(ctx context.Context, template string) (b // Release only this enrollment's references. Namespace reconciliation, rather // than an enrollment's resource sweep, owns every certificate DELETE. func (l *tunnelLease) releaseCertificates(ctx context.Context, keep ...string) error { - rows, err := l.s.db.QueryContext(ctx, `SELECT r.zone_id,r.wildcard_host,c.account_id FROM lpcc.machine_certificate_refs r JOIN lpcc.machine_certificates c USING(zone_id,wildcard_host) WHERE r.node_id=$1 AND r.epoch=$2`, l.Machine.NodeID, l.Machine.Epoch) + rows, err := l.s.db.QueryContext(ctx, `SELECT r.zone_id,r.wildcard_host,c.account_id FROM lpcc.machine_certificate_refs r JOIN lpcc.machine_certificates c USING(zone_id,wildcard_host) WHERE r.node_id=$1`, l.Machine.NodeID) if err != nil { return err } @@ -275,7 +275,7 @@ func (l *tunnelLease) releaseCertificates(ctx context.Context, keep ...string) e if err != nil { return err } - _, err = l.s.db.ExecContext(ctx, `DELETE FROM lpcc.machine_certificate_refs WHERE zone_id=$1 AND wildcard_host=$2 AND node_id=$3 AND epoch=$4 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$3 AND epoch=$4 AND lease_id=$5 AND revision=$6 AND lease_until>now())`, n.zone, n.host, l.Machine.NodeID, l.Machine.Epoch, l.Lease.ID, l.Revision) + _, err = l.s.db.ExecContext(ctx, `DELETE FROM lpcc.machine_certificate_refs WHERE zone_id=$1 AND wildcard_host=$2 AND node_id=$3 AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$3 AND lease_id=$4 AND revision=$5 AND lease_until>now())`, n.zone, n.host, l.Machine.NodeID, l.Lease.ID, l.Revision) if err == nil { _, err = cert.reconcile(ctx) } diff --git a/api/internal/controlplane/tunnel/certificates_test.go b/api/internal/controlplane/tunnel/certificates_test.go index c1c34a1..2b624a8 100644 --- a/api/internal/controlplane/tunnel/certificates_test.go +++ b/api/internal/controlplane/tunnel/certificates_test.go @@ -1,12 +1,9 @@ package tunnel import ( - "bytes" "context" - "database/sql" "encoding/json" "errors" - "regexp" "slices" "testing" "time" @@ -76,37 +73,6 @@ func certificateTestLease(t *testing.T) (*Manager, *certificateFixture, *tunnelL t.Cleanup(func() { l.Lease.Release(context.Background()) }) return s, f, l } -func TestEndpointSuffixPersistenceAndRandomFailure(t *testing.T) { - s, _, l := claimTestTunnel(t) - if !regexp.MustCompile(`^[a-z2-7]{7}$`).MatchString(l.state.EndpointSuffix) { - t.Fatal("invalid base32 suffix") - } - first := l.state.EndpointSuffix - s.endpointRandom = bytes.NewReader(nil) - if _, err := s.claimTunnel(t.Context(), l.Machine); !errors.Is(err, sql.ErrNoRows) { - t.Fatal("concurrent worker acquired enrollment", err) - } - l.Lease.Release(t.Context()) - next, err := s.claimTunnel(t.Context(), l.Machine) - if err != nil { - t.Fatal(err) - } - defer next.Lease.Release(t.Context()) - if next.state.EndpointSuffix != first || next.state.ServiceURL != l.state.ServiceURL { - t.Fatal("retry changed endpoint identity") - } - m := l.Machine - m.Epoch = uuid.New().String() - if _, err = s.newEndpointSuffix(t.Context(), m); err == nil { - t.Fatal("randomness failure ignored") - } - execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=jsonb_set(state,'{endpoint_suffix}','"aaaaaaa"') WHERE node_id=$1`, m.NodeID) - s.endpointRandom = bytes.NewReader([]byte{0, 0, 0, 0, 255, 255, 255, 255}) - suffix, err := s.newEndpointSuffix(t.Context(), m) - if err != nil || suffix != "777777y" { - t.Fatal("previous enrollment suffix was not resampled", suffix, err) - } -} func TestCertificateLostOrderPendingValidationAndCoverage(t *testing.T) { s, f, l := certificateTestLease(t) f.lostOrder = true diff --git a/api/internal/controlplane/tunnel/cloudflare_access_test.go b/api/internal/controlplane/tunnel/cloudflare_access_test.go index 6680a9b..aa50d36 100644 --- a/api/internal/controlplane/tunnel/cloudflare_access_test.go +++ b/api/internal/controlplane/tunnel/cloudflare_access_test.go @@ -10,7 +10,7 @@ import ( ) func TestSharedAccessApplicationReadbackAndConflicts(t *testing.T) { - state := RoutingFor("lp-aaaaaaaaaaaaaaaa", "example.invalid", "aaaaaaa") + state := RoutingFor("vkvkvkvkvkvkuaaaaaaaaaaaaa", "example.invalid") want := CFResource{Kind: "app", Name: "owned", Host: endpointHost(state.DiscoveryURL), Hosts: []string{endpointHost(state.ServiceURL), endpointHost(state.DiscoveryURL)}} var current cfObject var foreign *cfObject @@ -52,7 +52,7 @@ func TestSharedAccessApplicationReadbackAndConflicts(t *testing.T) { t.Fatal("public override accepted", err) } current.Destinations[0].Overrides = nil - current.Destinations = append(current.Destinations, accessDestination{Type: "public", URI: "*.lp-aaaaaaaaaaaaaaaa.example.invalid"}) + current.Destinations = append(current.Destinations, accessDestination{Type: "public", URI: "*.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid"}) if _, err := provider.Find(t.Context(), created); !errors.Is(err, ErrUnsafeProtection) { t.Fatal("wildcard protection accepted", err) } @@ -64,7 +64,7 @@ func TestSharedAccessApplicationReadbackAndConflicts(t *testing.T) { if found, err := provider.FindOwned(t.Context(), created); err != nil || len(found) != 1 { t.Fatal("foreign conflict prevented owned cleanup", found, err) } - for _, hostname := range []string{"api-*.lp-aaaaaaaaaaaaaaaa.example.invalid", "discovery-*.lp-aaaaaaaaaaaaaaaa.example.invalid", "*-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid", "api-*.*.example.invalid"} { + for _, hostname := range []string{"ap*.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "discover*.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "a*.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "ap*.*.example.invalid"} { foreign.Destinations[0].URI = hostname + "/apps" if _, err := provider.Find(t.Context(), created); !errors.Is(err, ErrResourceConflict) { t.Fatal("partial-label overlap missed", hostname, err) diff --git a/api/internal/controlplane/tunnel/cloudflare_deletion_test.go b/api/internal/controlplane/tunnel/cloudflare_deletion_test.go index bbd6778..3d7f218 100644 --- a/api/internal/controlplane/tunnel/cloudflare_deletion_test.go +++ b/api/internal/controlplane/tunnel/cloudflare_deletion_test.go @@ -11,7 +11,7 @@ import ( func TestDeletedTunnelTombstoneAllowsEnrollmentRecovery(t *testing.T) { now := time.Now().UTC() - want := CFResource{Kind: "tunnel", ID: "old", Name: "owned-epoch-tunnel", Watch: true} + want := CFResource{Kind: "tunnel", ID: "old", Name: "owned-enrollment-tunnel", Watch: true} object := cfObject{ID: want.ID, Name: want.Name, DeletedAt: &now} var listed []cfObject server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/api/internal/controlplane/tunnel/endpoints_test.go b/api/internal/controlplane/tunnel/endpoints_test.go index 749e8db..4d2b2f4 100644 --- a/api/internal/controlplane/tunnel/endpoints_test.go +++ b/api/internal/controlplane/tunnel/endpoints_test.go @@ -78,7 +78,7 @@ func endpointFixture(t *testing.T, state RoutingState, node http.Handler, accept } func TestReadinessAuthenticatesBothOriginsAndIsolation(t *testing.T) { - state := RoutingFor("lp-aaaaaaaaaaaaaaaa", "example.invalid", "aaaaaaa").RoutingState + state := RoutingFor("vkvkvkvkvkvkuaaaaaaaaaaaaa", "example.invalid").RoutingState creds := AccessCredential{ClientID: "current", ClientSecret: "secret"} node := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Host != endpointHost(PrivateOrchestrator) { @@ -167,7 +167,7 @@ func TestNodeSharedAccessIntegration(t *testing.T) { if binary == "" { t.Skip("set NODE_BINARY to a compatible livepeer-orchestrator binary") } - state := RoutingFor("lp-aaaaaaaaaaaaaaaa", "example.invalid", "aaaaaaa").RoutingState + state := RoutingFor("vkvkvkvkvkvkuaaaaaaaaaaaaa", "example.invalid").RoutingState app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/echo" { _ = json.NewEncoder(w).Encode(r.Header) @@ -250,7 +250,7 @@ func TestNodeSharedAccessIntegration(t *testing.T) { if response.StatusCode != 200 || string(body) != "application response" { t.Fatal("Host-preserving public proxy failed", response.StatusCode, string(body)) } - for _, host := range []string{"api.lp-aaaaaaaaaaaaaaaa.example.invalid", "discovery.lp-aaaaaaaaaaaaaaaa.example.invalid", "api-wrongsuffix.lp-aaaaaaaaaaaaaaaa.example.invalid", "discovery-wrongsuffix.lp-aaaaaaaaaaaaaaaa.example.invalid", "api-wrongsuffix.lp-aaaaaaaaaaaaaaaa.example.invalid:443", "valid-app.lp-aaaaaaaaaaaaaaaa.example.invalid:443", "valid-app.lp-aaaaaaaaaaaaaaaa.example.invalid.", "nested.valid-app.lp-aaaaaaaaaaaaaaaa.example.invalid"} { + for _, host := range []string{"api.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "api-wrongsuffix.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "discovery-wrongsuffix.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "api-wrongsuffix.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid:443", "valid-app.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid:443", "valid-app.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid.", "nested.valid-app.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid"} { response, err = client.Post("https://"+host+"/apps/app-fixture/session", "application/json", nil) if err != nil { t.Fatal(err) diff --git a/api/internal/controlplane/tunnel/identity.go b/api/internal/controlplane/tunnel/identity.go deleted file mode 100644 index c75e8ff..0000000 --- a/api/internal/controlplane/tunnel/identity.go +++ /dev/null @@ -1,41 +0,0 @@ -package tunnel - -import ( - "context" - "encoding/base32" - "errors" - "io" - "strings" -) - -func (s *Manager) newEndpointSuffix(ctx context.Context, m Machine) (string, error) { - rows, err := s.db.QueryContext(ctx, `SELECT state->>'endpoint_suffix' FROM lpcc.machine_states WHERE node_id=$1 AND epoch<>$2 AND state->>'endpoint_suffix' IS NOT NULL`, m.NodeID, m.Epoch) - if err != nil { - return "", err - } - previous := map[string]bool{} - for rows.Next() { - var suffix string - if err := rows.Scan(&suffix); err != nil { - rows.Close() - return "", err - } - previous[suffix] = true - } - err = rows.Err() - rows.Close() - if err != nil { - return "", err - } - for range 32 { - var raw [4]byte - if _, err := io.ReadFull(s.endpointRandom, raw[:]); err != nil { - return "", errors.New("endpoint randomness unavailable") - } - suffix := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw[:])) - if !previous[suffix] { - return suffix, nil - } - } - return "", errors.New("endpoint randomness repeatedly reused an enrollment suffix") -} diff --git a/api/internal/controlplane/tunnel/ingress.go b/api/internal/controlplane/tunnel/ingress.go index aa3fbac..b42c2e0 100644 --- a/api/internal/controlplane/tunnel/ingress.go +++ b/api/internal/controlplane/tunnel/ingress.go @@ -38,11 +38,10 @@ const reservedPath = `(?i)(?:^|/)(?:discovery|runners?|metrics|healthz|readyz)(? // The protected API Host needs only reservation, stop and payment control. const clientPath = `^/(?:apps/[A-Za-z0-9_-]{1,128}/session(?:/[A-Za-z0-9_-]{1,128}/(?:stop|payment))?|refresh-payment)$` -func RoutingFor(node, domain, suffix string) Snapshot { +func RoutingFor(node, domain string) Snapshot { return Snapshot{State: machineconfig.InitialState(false), RoutingState: RoutingState{EndpointGeneration: 1, CredentialGeneration: 1, SourceGeneration: 1, AccessVersion: 1, - EndpointSuffix: suffix, - ServiceURL: "https://api-" + suffix + "." + node + "." + domain, - ProxyURLTemplate: "https://{proxy}." + node + "." + domain, DiscoveryURL: "https://discovery-" + suffix + "." + node + "." + domain + "/discovery", Resources: map[string]CFResource{}}} + ServiceURL: "https://api." + node + "." + domain, + ProxyURLTemplate: "https://{proxy}." + node + "." + domain, DiscoveryURL: "https://discovery." + node + "." + domain + "/discovery", Resources: map[string]CFResource{}}} } func ingressFor(state RoutingState, p Config, audience string) []IngressRule { api := endpointHost(state.ServiceURL) @@ -56,8 +55,6 @@ func ingressFor(state RoutingState, p Config, audience string) []IngressRule { {Hostname: api, Service: "http_status:404"}, {Hostname: discovery, Path: `^/discovery$`, Service: ConnectorOrigin, OriginRequest: origin}, {Hostname: discovery, Service: "http_status:404"}, - {Hostname: "api." + namespace, Service: "http_status:404"}, - {Hostname: "discovery." + namespace, Service: "http_status:404"}, {Hostname: apps, Path: reservedPath, Service: "http_status:404"}, {Hostname: apps, Service: ConnectorOrigin}, {Service: "http_status:404"}, @@ -82,6 +79,6 @@ func ingressHash(r []IngressRule) string { h := sha256.Sum256(b) return hex.EncodeToString(h[:]) } -func credentialRef(node, epoch string, version int64) string { - return fmt.Sprintf("access/%s/%s/%d", node, epoch, version) +func credentialRef(node string, version int64) string { + return fmt.Sprintf("access/%s/%d", node, version) } diff --git a/api/internal/controlplane/tunnel/ingress_cli_test.go b/api/internal/controlplane/tunnel/ingress_cli_test.go index a2de70e..92a76f9 100644 --- a/api/internal/controlplane/tunnel/ingress_cli_test.go +++ b/api/internal/controlplane/tunnel/ingress_cli_test.go @@ -20,7 +20,7 @@ func TestPinnedCloudflaredIngress(t *testing.T) { if e != nil || !strings.Contains(string(v), "version 2026.10.7 ") { t.Fatal("requires pinned cloudflared", e) } - rules := ingressFor(RoutingFor("lp-aaaaaaaaaaaaaaaa", "example.invalid", "aaaaaaa").RoutingState, Config{CloudflareBaseDomain: "example.invalid", CloudflareTeamName: "team"}, "audience") + rules := ingressFor(RoutingFor("vkvkvkvkvkvkuaaaaaaaaaaaaa", "example.invalid").RoutingState, Config{CloudflareBaseDomain: "example.invalid", CloudflareTeamName: "team"}, "audience") data, _ := json.Marshal(map[string]any{"ingress": rules}) path := filepath.Join(t.TempDir(), "config.yaml") if e := os.WriteFile(path, data, 0600); e != nil { @@ -30,29 +30,28 @@ func TestPinnedCloudflaredIngress(t *testing.T) { t.Fatalf("invalid pinned ingress: %s (%v)", out, err) } for _, fixture := range []struct{ host, path, service string }{ - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/discovery", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/prefix/discovery", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/runners/heartbeat", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/runner/a/session/b/channels", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/session", ConnectorOrigin}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/session/b/payment", ConnectorOrigin}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/app/v1", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/session/b/app", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/session/b/app/ws", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/run/a/x", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/proxy/a", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/refresh-payment", ConnectorOrigin}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/ai/trickle/a/0", "http_status:404"}, - {"api-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/unknown", "http_status:404"}, - {"api.lp-aaaaaaaaaaaaaaaa", "/apps/a/session", "http_status:404"}, - {"discovery.lp-aaaaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, - {"p.lp-aaaaaaaaaaaaaaaa", "/discovery", "http_status:404"}, - {"p.lp-aaaaaaaaaaaaaaaa", "/app/discovery", "http_status:404"}, - {"p.lp-aaaaaaaaaaaaaaaa", "/readyz", "http_status:404"}, - {"p.lp-aaaaaaaaaaaaaaaa", "/v1/completions", ConnectorOrigin}, - {"discovery-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/discovery", ConnectorOrigin}, - {"discovery-aaaaaaa.lp-aaaaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/discovery", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/prefix/discovery", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/runners/heartbeat", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/runner/a/session/b/channels", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/session", ConnectorOrigin}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/session/b/payment", ConnectorOrigin}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/app/v1", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/session/b/app", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/session/b/app/ws", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/run/a/x", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/proxy/a", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/refresh-payment", ConnectorOrigin}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/ai/trickle/a/0", "http_status:404"}, + {"api.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/unknown", "http_status:404"}, + {"discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, + {"p.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/discovery", "http_status:404"}, + {"p.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/app/discovery", "http_status:404"}, + {"p.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/readyz", "http_status:404"}, + {"p.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/v1/completions", ConnectorOrigin}, + {"discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/discovery", ConnectorOrigin}, + {"discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa", "/apps/a/app", "http_status:404"}, {"alias", "/discovery", "http_status:404"}, } { t.Run(fixture.host+fixture.path, func(t *testing.T) { diff --git a/api/internal/controlplane/tunnel/manager.go b/api/internal/controlplane/tunnel/manager.go index 57fda07..2ff807f 100644 --- a/api/internal/controlplane/tunnel/manager.go +++ b/api/internal/controlplane/tunnel/manager.go @@ -3,11 +3,9 @@ package tunnel import ( "context" - "crypto/rand" "database/sql" "errors" "github.com/livepeer/control-center/api/internal/controlplane/machineconfig" - "io" "log/slog" "net/http" "time" @@ -23,7 +21,6 @@ type Dependencies struct { Configurations *machineconfig.Manager Provider TunnelProvider VerifyEndpoints func(context.Context, RoutingState, AccessCredential) error - EndpointRandom io.Reader } type Manager struct { @@ -34,18 +31,14 @@ type Manager struct { provider TunnelProvider keys *accessKeyring endpointVerifier func(context.Context, RoutingState, AccessCredential) error - endpointRandom io.Reader } // New also supports reading persisted state while provisioning is disabled. // Configure enables provisioning; ConfigureCredentials enables credential reads. // Both are startup operations and must finish before workers start. func New(config Config, deps Dependencies) *Manager { - if deps.EndpointRandom == nil { - deps.EndpointRandom = rand.Reader - } return &Manager{db: deps.DB, params: config, logger: deps.Logger, rollout: deps.Configurations, - provider: deps.Provider, endpointVerifier: deps.VerifyEndpoints, endpointRandom: deps.EndpointRandom} + provider: deps.Provider, endpointVerifier: deps.VerifyEndpoints} } func (s *Manager) Configure(publicAPIURL string) error { diff --git a/api/internal/controlplane/tunnel/operations.go b/api/internal/controlplane/tunnel/operations.go index 8c74ea7..daca067 100644 --- a/api/internal/controlplane/tunnel/operations.go +++ b/api/internal/controlplane/tunnel/operations.go @@ -30,7 +30,7 @@ func (l *tunnelLease) storeResource(ctx context.Context, key string, r CFResourc var keyID string var ciphertext []byte if secret != nil { - keyID, ciphertext, e = l.s.keys.seal(credentialRef(l.Machine.NodeID, l.Machine.Epoch, r.CredentialVersion), *secret) + keyID, ciphertext, e = l.s.keys.seal(credentialRef(l.Machine.NodeID, r.CredentialVersion), *secret) if e != nil { return e } @@ -45,7 +45,7 @@ func (l *tunnelLease) storeResource(ctx context.Context, key string, r CFResourc return e } if secret != nil { - result, e := tx.ExecContext(ctx, `INSERT INTO lpcc.access_credentials(node_id,epoch,version,provider_id,key_id,ciphertext,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(node_id,epoch,version) DO NOTHING`, l.Machine.NodeID, l.Machine.Epoch, r.CredentialVersion, r.ID, keyID, ciphertext, expiry) + result, e := tx.ExecContext(ctx, `INSERT INTO lpcc.access_credentials(node_id,version,provider_id,key_id,ciphertext,expires_at) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(node_id,version) DO NOTHING`, l.Machine.NodeID, r.CredentialVersion, r.ID, keyID, ciphertext, expiry) if e != nil { return e } @@ -53,7 +53,7 @@ func (l *tunnelLease) storeResource(ctx context.Context, key string, r CFResourc return errors.New("Access credential version is already bound") } } else if r.CredentialVersion > 0 { - if _, e = tx.ExecContext(ctx, `UPDATE lpcc.access_credentials SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=$1 AND epoch=$2 AND version=$3`, l.Machine.NodeID, l.Machine.Epoch, r.CredentialVersion); e != nil { + if _, e = tx.ExecContext(ctx, `UPDATE lpcc.access_credentials SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=$1 AND version=$2`, l.Machine.NodeID, r.CredentialVersion); e != nil { return e } } diff --git a/api/internal/controlplane/tunnel/protection.go b/api/internal/controlplane/tunnel/protection.go index 00bc49b..1d4f18f 100644 --- a/api/internal/controlplane/tunnel/protection.go +++ b/api/internal/controlplane/tunnel/protection.go @@ -95,7 +95,7 @@ func (l *tunnelLease) restoreProtectedIngress(ctx context.Context) error { func (l *tunnelLease) accessAcknowledged(ctx context.Context) (bool, error) { var ack bool - e := l.s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=$3 AND acknowledged_at IS NOT NULL AND acknowledged_generation=$4 AND revoked_at IS NULL AND expires_at>now())`, l.Machine.NodeID, l.Machine.Epoch, l.state.AccessVersion, l.state.SourceGeneration).Scan(&ack) + e := l.s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.access_credentials WHERE node_id=$1 AND version=$2 AND acknowledged_at IS NOT NULL AND acknowledged_generation=$3 AND revoked_at IS NULL AND expires_at>now())`, l.Machine.NodeID, l.state.AccessVersion, l.state.SourceGeneration).Scan(&ack) return ack, e } diff --git a/api/internal/controlplane/tunnel/reconcile.go b/api/internal/controlplane/tunnel/reconcile.go index 1b42ba2..cecac5c 100644 --- a/api/internal/controlplane/tunnel/reconcile.go +++ b/api/internal/controlplane/tunnel/reconcile.go @@ -48,14 +48,14 @@ func (s *Manager) Reconcile(ctx context.Context) error { if e := s.ReencryptAccessCredentials(ctx); e != nil { return e } - rows, e := s.db.QueryContext(ctx, `SELECT e.node_id,e.epoch::text,e.install_dir,e.k3s_version,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.enrollments e WHERE e.retired_at IS NOT NULL OR EXISTS(SELECT FROM lpcc.machines m WHERE m.node_id=e.node_id AND m.enrollment_epoch=e.epoch)`) + rows, e := s.db.QueryContext(ctx, `SELECT e.node_id,e.install_dir,e.k3s_version,e.credential_version,e.retired_at IS NOT NULL FROM lpcc.enrollments e WHERE e.retired_at IS NOT NULL OR EXISTS(SELECT FROM lpcc.machines m WHERE m.node_id=e.node_id)`) if e != nil { return e } var machines []Machine for rows.Next() { var m Machine - if e = rows.Scan(&m.NodeID, &m.Epoch, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal); e != nil { + if e = rows.Scan(&m.NodeID, &m.InstallDir, &m.K3sVersion, &m.CredentialVersion, &m.Terminal); e != nil { rows.Close() return e } @@ -77,7 +77,7 @@ func (s *Manager) Reconcile(ctx context.Context) error { return e } if !safe { - state, _, err := s.Load(ctx, m.NodeID, m.Epoch) + state, _, err := s.Load(ctx, m.NodeID) if err != nil || state.TunnelID == "" && state.Lifecycle != "draining" { continue } @@ -140,16 +140,7 @@ func (l *tunnelLease) provision(ctx context.Context) error { if l.state.AccountID != p.CloudflareAccountID || l.state.ZoneID != p.CloudflareZoneID || l.state.TeamName != p.CloudflareTeamName { return errors.New("retire the previous provider scope before changing account, zone or team") } - var predecessor bool - if e := l.s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND epoch<>$2 AND COALESCE((state->>'cleanup_complete')::boolean,false)=false)`, l.Machine.NodeID, l.Machine.Epoch).Scan(&predecessor); e != nil { - return e - } - if predecessor { - l.state.Ready = false - l.state.Reason = "predecessor_cleanup_pending" - return l.save(ctx) - } - desired := RoutingFor(l.Machine.NodeID, p.CloudflareBaseDomain, l.state.EndpointSuffix) + desired := RoutingFor(l.Machine.NodeID, p.CloudflareBaseDomain) if l.state.Target != "" && l.state.Target != desired.ServiceURL { l.state.State.CancelTarget() l.state.Ready = false @@ -273,7 +264,7 @@ func (l *tunnelLease) provision(ctx context.Context) error { return e } } - credential, e := l.s.ResolveAccessCredential(ctx, credentialRef(l.Machine.NodeID, l.Machine.Epoch, l.state.AccessVersion)) + credential, e := l.s.ResolveAccessCredential(ctx, credentialRef(l.Machine.NodeID, l.state.AccessVersion)) if e != nil { return e } @@ -401,7 +392,7 @@ func (l *tunnelLease) rotateConnector(ctx context.Context) error { func (l *tunnelLease) prepareAccessRotation(ctx context.Context) error { var expires time.Time var revoked bool - e := l.s.db.QueryRowContext(ctx, `SELECT expires_at,revoked_at IS NOT NULL FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=$3`, l.Machine.NodeID, l.Machine.Epoch, l.state.AccessVersion).Scan(&expires, &revoked) + e := l.s.db.QueryRowContext(ctx, `SELECT expires_at,revoked_at IS NOT NULL FROM lpcc.access_credentials WHERE node_id=$1 AND version=$2`, l.Machine.NodeID, l.state.AccessVersion).Scan(&expires, &revoked) missing := errors.Is(e, sql.ErrNoRows) if e != nil && !missing { return e @@ -433,7 +424,7 @@ func (l *tunnelLease) prepareAccessRotation(ctx context.Context) error { return nil } var count int - if e = l.s.db.QueryRowContext(ctx, `SELECT count(*) FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL AND expires_at>now()`, l.Machine.NodeID, l.Machine.Epoch).Scan(&count); e != nil { + if e = l.s.db.QueryRowContext(ctx, `SELECT count(*) FROM lpcc.access_credentials WHERE node_id=$1 AND revoked_at IS NULL AND expires_at>now()`, l.Machine.NodeID).Scan(&count); e != nil { return e } if count > 1 { @@ -462,7 +453,7 @@ func (l *tunnelLease) retireAccessTokens(ctx context.Context, expiredOnly bool) } if expiredOnly { var expired bool - if e := l.s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=$3 AND (expires_at<=now() OR revoked_at IS NOT NULL))`, l.Machine.NodeID, l.Machine.Epoch, r.CredentialVersion).Scan(&expired); e != nil { + if e := l.s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.access_credentials WHERE node_id=$1 AND version=$2 AND (expires_at<=now() OR revoked_at IS NOT NULL))`, l.Machine.NodeID, r.CredentialVersion).Scan(&expired); e != nil { return e } if !expired { @@ -476,7 +467,7 @@ func (l *tunnelLease) retireAccessTokens(ctx context.Context, expiredOnly bool) return nil } func (s *Manager) activeAccessIDs(ctx context.Context, m Machine) ([]string, error) { - rows, e := s.db.QueryContext(ctx, `SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND revoked_at IS NULL AND expires_at>now() ORDER BY version`, m.NodeID, m.Epoch) + rows, e := s.db.QueryContext(ctx, `SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND revoked_at IS NULL AND expires_at>now() ORDER BY version`, m.NodeID) if e != nil { return nil, e } @@ -532,7 +523,7 @@ func (l *tunnelLease) retirePreviousEndpoints(ctx context.Context) error { } func (l *tunnelLease) cleanup(ctx context.Context) error { if !l.state.Compromised && !l.state.CompromisedAccess && !l.state.ConnectorRevoked { - pending, err := machineapps.Pending(ctx, l.s.db, l.Machine.NodeID, l.Machine.Epoch) + pending, err := machineapps.Pending(ctx, l.s.db, l.Machine.NodeID) if err != nil { return err } @@ -606,7 +597,7 @@ func (l *tunnelLease) cleanup(ctx context.Context) error { } } } - if _, e := l.s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=$1 AND epoch=$2`, l.Machine.NodeID, l.Machine.Epoch); e != nil { + if _, e := l.s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET revoked_at=COALESCE(revoked_at,now()) WHERE node_id=$1`, l.Machine.NodeID); e != nil { return e } if err := l.releaseCertificates(ctx, ""); err != nil { diff --git a/api/internal/controlplane/tunnel/store.go b/api/internal/controlplane/tunnel/store.go index 8181241..3c96a2b 100644 --- a/api/internal/controlplane/tunnel/store.go +++ b/api/internal/controlplane/tunnel/store.go @@ -14,8 +14,8 @@ import ( var errTunnelFenced = machineconfig.ErrFenced -func (s *Manager) Load(ctx context.Context, node, epoch string) (Snapshot, int64, error) { - r, err := (machineconfig.Store{DB: s.db}).Load(ctx, node, epoch) +func (s *Manager) Load(ctx context.Context, node string) (Snapshot, int64, error) { + r, err := (machineconfig.Store{DB: s.db}).Load(ctx, node) var state Snapshot if errors.Is(err, sql.ErrNoRows) { return state, 0, ErrPending @@ -62,17 +62,8 @@ func (s *Manager) claimTunnel(ctx context.Context, m Machine) (*tunnelLease, err lease.Release(ctx) return nil, err } - if !l.Machine.Terminal && l.state.EndpointSuffix == "" { - if l.state.ServiceURL != "" || l.state.TunnelID != "" || len(l.state.Resources) != 0 { - lease.Release(ctx) - return nil, errors.New("incomplete tunnel routing state") - } - suffix, err := s.newEndpointSuffix(ctx, m) - if err != nil { - lease.Release(ctx) - return nil, err - } - l.state.RoutingState = RoutingFor(m.NodeID, s.params.CloudflareBaseDomain, suffix).RoutingState + if !l.Machine.Terminal && l.state.ServiceURL == "" { + l.state.RoutingState = RoutingFor(m.NodeID, s.params.CloudflareBaseDomain).RoutingState initialized = true } if l.state.AccountID == "" { @@ -116,7 +107,7 @@ func (l *tunnelLease) save(ctx context.Context) error { } func (l *tunnelLease) finish(ctx context.Context, failed bool) { l.Lease.Finish(ctx, failed) } func resourceName(m Machine, purpose string) string { - return "lpcc-" + m.NodeID + "-" + strings.ReplaceAll(m.Epoch, "-", "") + "-" + purpose + return "lpcc-" + m.NodeID + "-" + purpose } func (l *tunnelLease) ensure(ctx context.Context, key, kind, host, target string) (CFResource, error) { r, exists := l.state.Resources[key] @@ -184,7 +175,7 @@ func (l *tunnelLease) ensure(ctx context.Context, key, kind, host, target string } if kind == "token" { var bound string - e = l.s.db.QueryRowContext(ctx, `SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=$3`, l.Machine.NodeID, l.Machine.Epoch, r.CredentialVersion).Scan(&bound) + e = l.s.db.QueryRowContext(ctx, `SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND version=$2`, l.Machine.NodeID, r.CredentialVersion).Scan(&bound) if e != nil && !errors.Is(e, sql.ErrNoRows) { return r, e } @@ -290,17 +281,17 @@ func (l *tunnelLease) ensure(ctx context.Context, key, kind, host, target string // DiscoverySources and ResolveAccessCredential are internal discovery // interfaces. No browser or machine endpoint exposes Collector credentials. func (s *Manager) DiscoverySources(ctx context.Context) ([]DiscoverySource, error) { - rows, e := s.db.QueryContext(ctx, `SELECT node_id,epoch::text,state,rollout FROM lpcc.machine_states ORDER BY node_id,epoch`) + rows, e := s.db.QueryContext(ctx, `SELECT node_id,state,rollout FROM lpcc.machine_states ORDER BY node_id`) if e != nil { return nil, e } defer rows.Close() var sources []DiscoverySource for rows.Next() { - var node, epoch string + var node string var b, rollout []byte var r Snapshot - if e = rows.Scan(&node, &epoch, &b, &rollout); e != nil { + if e = rows.Scan(&node, &b, &rollout); e != nil { return nil, e } if e = json.Unmarshal(b, &r.RoutingState); e != nil { @@ -312,7 +303,7 @@ func (s *Manager) DiscoverySources(ctx context.Context) ([]DiscoverySource, erro if r.TunnelID == "" { continue } - blocked := r.EndpointSuffix == "" || r.Quarantined || r.Reason == "ownership_conflict" || r.Reason == "predecessor_cleanup_pending" || r.Reason == "ingress_validation_required" + blocked := r.ServiceURL == "" || r.ProxyURLTemplate == "" || r.DiscoveryURL == "" || r.Quarantined || r.Reason == "ownership_conflict" || r.Reason == "ingress_validation_required" r.applyRolloutStatus() ready, reason := r.Ready, r.Reason if r.VerifiedGeneration != r.SourceGeneration { @@ -321,37 +312,37 @@ func (s *Manager) DiscoverySources(ctx context.Context) ([]DiscoverySource, erro if ready && (r.VerifiedAt.IsZero() || time.Since(r.VerifiedAt) > s.params.TunnelStatusTTL) { ready, reason = false, "observation_expired" } - sources = append(sources, DiscoverySource{ID: node + "/" + epoch, NodeID: node, Epoch: epoch, URL: r.DiscoveryURL, ServiceURL: r.ServiceURL, ProxyURLTemplate: r.ProxyURLTemplate, Lifecycle: r.Lifecycle, Ready: ready, Blocked: blocked, Generation: r.SourceGeneration, VerifiedGeneration: r.VerifiedGeneration, CredentialVersion: r.AccessVersion, CredentialRef: credentialRef(node, epoch, r.AccessVersion), Reason: reason, RotationReason: r.RotationReason}) + sources = append(sources, DiscoverySource{NodeID: node, URL: r.DiscoveryURL, ServiceURL: r.ServiceURL, ProxyURLTemplate: r.ProxyURLTemplate, Lifecycle: r.Lifecycle, Ready: ready, Blocked: blocked, Generation: r.SourceGeneration, VerifiedGeneration: r.VerifiedGeneration, CredentialVersion: r.AccessVersion, CredentialRef: credentialRef(node, r.AccessVersion), Reason: reason, RotationReason: r.RotationReason}) } return sources, rows.Err() } func (s *Manager) ResolveAccessCredential(ctx context.Context, ref string) (AccessCredential, error) { var empty AccessCredential parts := strings.Split(ref, "/") - if len(parts) != 4 || parts[0] != "access" || s.keys == nil { + if len(parts) != 3 || parts[0] != "access" || s.keys == nil { return empty, errors.New("invalid Access credential reference") } - version, e := strconv.ParseInt(parts[3], 10, 64) + version, e := strconv.ParseInt(parts[2], 10, 64) if e != nil { return empty, e } var key string var b []byte - e = s.db.QueryRowContext(ctx, `SELECT c.key_id,c.ciphertext FROM lpcc.access_credentials c JOIN lpcc.enrollments e USING(node_id,epoch) WHERE c.node_id=$1 AND c.epoch=$2 AND c.version=$3 AND c.revoked_at IS NULL AND c.expires_at>now() AND e.retired_at IS NULL`, parts[1], parts[2], version).Scan(&key, &b) + e = s.db.QueryRowContext(ctx, `SELECT c.key_id,c.ciphertext FROM lpcc.access_credentials c JOIN lpcc.enrollments e USING(node_id) WHERE c.node_id=$1 AND c.version=$2 AND c.revoked_at IS NULL AND c.expires_at>now() AND e.retired_at IS NULL`, parts[1], version).Scan(&key, &b) if e != nil { return empty, errors.New("Access credential is unavailable") } return s.keys.open(key, ref, b) } func (s *Manager) AcknowledgeDiscovery(ctx context.Context, source DiscoverySource) error { - r, _, e := s.Load(ctx, source.NodeID, source.Epoch) + r, _, e := s.Load(ctx, source.NodeID) if e != nil { return e } - if r.Lifecycle != "active" || r.SourceGeneration != source.Generation || r.AccessVersion != source.CredentialVersion || r.DiscoveryURL != source.URL || source.ID != source.NodeID+"/"+source.Epoch || source.CredentialRef != credentialRef(source.NodeID, source.Epoch, source.CredentialVersion) { + if r.Lifecycle != "active" || r.SourceGeneration != source.Generation || r.AccessVersion != source.CredentialVersion || r.DiscoveryURL != source.URL || source.CredentialRef != credentialRef(source.NodeID, source.CredentialVersion) { return errors.New("stale discovery acknowledgement") } - result, e := s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET acknowledged_at=now(),acknowledged_generation=$4 WHERE node_id=$1 AND epoch=$2 AND version=$3 AND revoked_at IS NULL AND expires_at>now() AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND epoch=$2 AND rollout->>'lifecycle'='active' AND (state->>'source_generation')::bigint=$4 AND (state->>'access_version')::bigint=$3 AND state->>'discovery_url'=$5)`, source.NodeID, source.Epoch, source.CredentialVersion, source.Generation, source.URL) + result, e := s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET acknowledged_at=now(),acknowledged_generation=$3 WHERE node_id=$1 AND version=$2 AND revoked_at IS NULL AND expires_at>now() AND EXISTS(SELECT FROM lpcc.machine_states WHERE node_id=$1 AND rollout->>'lifecycle'='active' AND (state->>'source_generation')::bigint=$3 AND (state->>'access_version')::bigint=$2 AND state->>'discovery_url'=$4)`, source.NodeID, source.CredentialVersion, source.Generation, source.URL) if e != nil { return e } @@ -362,19 +353,19 @@ func (s *Manager) AcknowledgeDiscovery(ctx context.Context, source DiscoverySour return nil } func (s *Manager) ReencryptAccessCredentials(ctx context.Context) error { - rows, e := s.db.QueryContext(ctx, `SELECT node_id,epoch::text,version,key_id,ciphertext FROM lpcc.access_credentials WHERE key_id<>$1`, s.keys.current) + rows, e := s.db.QueryContext(ctx, `SELECT node_id,version,key_id,ciphertext FROM lpcc.access_credentials WHERE key_id<>$1`, s.keys.current) if e != nil { return e } type record struct { - node, epoch, key string - version int64 - b []byte + node, key string + version int64 + b []byte } var records []record for rows.Next() { var r record - if e = rows.Scan(&r.node, &r.epoch, &r.version, &r.key, &r.b); e != nil { + if e = rows.Scan(&r.node, &r.version, &r.key, &r.b); e != nil { rows.Close() return e } @@ -386,7 +377,7 @@ func (s *Manager) ReencryptAccessCredentials(ctx context.Context) error { return e } for _, r := range records { - ref := credentialRef(r.node, r.epoch, r.version) + ref := credentialRef(r.node, r.version) v, e := s.keys.open(r.key, ref, r.b) if e != nil { return e @@ -395,7 +386,7 @@ func (s *Manager) ReencryptAccessCredentials(ctx context.Context) error { if e != nil { return e } - if _, e = s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET key_id=$4,ciphertext=$5 WHERE node_id=$1 AND epoch=$2 AND version=$3 AND key_id=$6`, r.node, r.epoch, r.version, id, b, r.key); e != nil { + if _, e = s.db.ExecContext(ctx, `UPDATE lpcc.access_credentials SET key_id=$3,ciphertext=$4 WHERE node_id=$1 AND version=$2 AND key_id=$5`, r.node, r.version, id, b, r.key); e != nil { return e } } @@ -404,7 +395,7 @@ func (s *Manager) ReencryptAccessCredentials(ctx context.Context) error { func (s *Manager) SecureRuntime(ctx context.Context, m Machine) (bool, error) { var yes bool - e := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_reports r JOIN lpcc.machines m ON m.node_id=r.node_id AND m.enrollment_epoch=r.epoch WHERE r.node_id=$1 AND r.epoch=$2 AND component='runtime' AND r.credential_version=$3 AND m.credential_version=$3 AND m.tunnel_eligible AND report->>'https'='true' AND received_at>now()-make_interval(secs=>$4) AND (report->>'report_version')::int=1 AND COALESCE((report->>'clock_uncertain')::boolean,false)=false AND (report->>'observed_at')::timestamptz>now()-make_interval(secs=>$4) AND (report->>'observed_at')::timestamptz<=now()+interval '5 seconds')`, m.NodeID, m.Epoch, m.CredentialVersion, s.params.TunnelStatusTTL.Seconds()).Scan(&yes) + e := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT FROM lpcc.machine_reports r JOIN lpcc.machines m ON m.node_id=r.node_id WHERE r.node_id=$1 AND component='runtime' AND r.credential_version=$2 AND m.credential_version=$2 AND m.tunnel_eligible AND report->>'https'='true' AND received_at>now()-make_interval(secs=>$3) AND (report->>'report_version')::int=1 AND COALESCE((report->>'clock_uncertain')::boolean,false)=false AND (report->>'observed_at')::timestamptz>now()-make_interval(secs=>$3) AND (report->>'observed_at')::timestamptz<=now()+interval '5 seconds')`, m.NodeID, m.CredentialVersion, s.params.TunnelStatusTTL.Seconds()).Scan(&yes) return yes, e } func (s *Manager) report(ctx context.Context, m Machine, component string) (MachineReport, time.Time, error) { diff --git a/api/internal/controlplane/tunnel/tunnel_test.go b/api/internal/controlplane/tunnel/tunnel_test.go index 2b4d034..c8813ba 100644 --- a/api/internal/controlplane/tunnel/tunnel_test.go +++ b/api/internal/controlplane/tunnel/tunnel_test.go @@ -96,7 +96,7 @@ func (f *recoveryCloudflare) Delete(_ context.Context, r CFResource, _ string) e return nil } func TestTunnelIngressContract(t *testing.T) { - rules := ingressFor(RoutingFor("lp-aaaaaaaaaaaaaaaa", "example.invalid", "aaaaaaa").RoutingState, Config{CloudflareBaseDomain: "example.invalid", CloudflareTeamName: "team"}, "aud") + rules := ingressFor(RoutingFor("vkvkvkvkvkvkuaaaaaaaaaaaaa", "example.invalid").RoutingState, Config{CloudflareBaseDomain: "example.invalid", CloudflareTeamName: "team"}, "aud") match := func(host, path string) IngressRule { for _, r := range rules { hostOK := r.Hostname == "" || r.Hostname == host || strings.HasPrefix(r.Hostname, "*.") && strings.HasSuffix(host, r.Hostname[1:]) @@ -107,8 +107,8 @@ func TestTunnelIngressContract(t *testing.T) { t.Fatal("no catch-all") return IngressRule{} } - api := "api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid" - app := "proxy.lp-aaaaaaaaaaaaaaaa.example.invalid" + api := "api.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid" + app := "proxy.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid" for _, host := range []string{api, app} { for _, path := range []string{"/discovery", "/prefix/discovery", "/runners/heartbeat", "/runner/a/session/b/channels", "/ai/trickle/x/0", "/metrics", "/readyz"} { if match(host, path).Service != "http_status:404" { @@ -127,7 +127,7 @@ func TestTunnelIngressContract(t *testing.T) { t.Fatalf("application data reached protected API Host: %s", path) } } - for _, host := range []string{api, "discovery-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid", "api.lp-aaaaaaaaaaaaaaaa.example.invalid", "discovery.lp-aaaaaaaaaaaaaaaa.example.invalid"} { + for _, host := range []string{api, "discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "api.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid"} { if match(host, "/unknown").Service != "http_status:404" { t.Fatal("exact hostname fell through to wildcard", host) } @@ -135,7 +135,7 @@ func TestTunnelIngressContract(t *testing.T) { if rule := match(app, "/v1/completions"); rule.Service != ConnectorOrigin || rule.OriginRequest != nil { t.Fatal("proxy Host was not preserved") } - protected := match("discovery-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid", "/discovery") + protected := match("discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "/discovery") if protected.OriginRequest == nil || !protected.OriginRequest.Access.Required || protected.OriginRequest.Access.Audience[0] != "aud" { t.Fatal("discovery not audience protected") } @@ -153,7 +153,7 @@ func TestAccessKeyringBindingAndRotation(t *testing.T) { if e != nil { t.Fatal(e) } - ref := "access/node/epoch/1" + ref := "access/node/1" secret := AccessCredential{"id", "high-entropy-secret"} id, b, e := k.seal(ref, secret) if e != nil || bytes.Contains(b, []byte(secret.ClientSecret)) { @@ -162,7 +162,7 @@ func TestAccessKeyringBindingAndRotation(t *testing.T) { if v, e := k.open(id, ref, b); e != nil || v != secret { t.Fatal(e) } - for _, wrong := range []string{"access/other/epoch/1", "access/node/epoch/2"} { + for _, wrong := range []string{"access/other/1", "access/node/2"} { if _, e := k.open(id, wrong, b); e == nil { t.Fatal("credential reference substitution") } @@ -201,7 +201,7 @@ func TestCloudflareOwnershipAndDeletionReadback(t *testing.T) { w.WriteHeader(404) return } - name := "epoch-owner" + name := "node-owner" if renamed.Load() { name = "foreign-owner" } @@ -209,7 +209,7 @@ func TestCloudflareOwnershipAndDeletionReadback(t *testing.T) { })) defer api.Close() cf := &cloudflareHTTP{base: api.URL, client: api.Client(), params: Config{CloudflareAccountID: strings.Repeat("a", 32)}} - r := CFResource{Kind: "tunnel", ID: "tunnel-id", Name: "epoch-owner"} + r := CFResource{Kind: "tunnel", ID: "tunnel-id", Name: "node-owner"} if e := cf.Delete(t.Context(), r, ""); e == nil { t.Fatal("unconfirmed provider deletion counted as absent") } @@ -258,7 +258,7 @@ func TestCloudflareDNSRecordEnvelopes(t *testing.T) { })) defer server.Close() c := &cloudflareHTTP{client: server.Client(), base: server.URL, params: Config{CloudflareZoneID: "zone"}} - r := CFResource{Kind: "dns", Name: "owned-epoch-dns", Host: "api.example.invalid"} + r := CFResource{Kind: "dns", Name: "owned-node-dns", Host: "api.example.invalid"} created, _, _, e := c.Create(t.Context(), r, "tunnel-id") if e != nil { t.Fatal(e) @@ -288,12 +288,12 @@ func claimTestTunnel(t *testing.T) (*Manager, *recoveryCloudflare, *tunnelLease) } owner := "11111111-1111-4111-8111-111111111111" execSQL(t, db, `INSERT INTO auth.users(id) VALUES($1)`, owner) - m := Machine{NodeID: "lp-aaaaaaaaaaaaaaaa", InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1", CredentialVersion: 1} - err := db.QueryRow(`INSERT INTO lpcc.machines(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,tunnel_eligible) VALUES($1,$2,$3,'test',$4,$5,1,true) RETURNING enrollment_epoch::text`, m.NodeID, owner, strings.Repeat("a", 64), m.InstallDir, m.K3sVersion).Scan(&m.Epoch) + m := Machine{NodeID: "vkvkvkvkvkvkuaaaaaaaaaaaaa", InstallDir: "/srv/livepeer", K3sVersion: "v1.37.2+k3s1", CredentialVersion: 1} + err := db.QueryRow(`INSERT INTO lpcc.machines(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version,tunnel_eligible) VALUES($1,$2,$3,'test',$4,$5,1,true) RETURNING node_id::text`, m.NodeID, owner, strings.Repeat("a", 64), m.InstallDir, m.K3sVersion).Scan(&m.NodeID) if err != nil { t.Fatal(err) } - execSQL(t, db, `INSERT INTO lpcc.enrollments(node_id,epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version) SELECT node_id,enrollment_epoch,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version FROM lpcc.machines`) + execSQL(t, db, `INSERT INTO lpcc.enrollments(node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version) SELECT node_id,owner_id,fingerprint,hostname,install_dir,k3s_version,credential_version FROM lpcc.machines`) key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) fake := newRecoveryCloudflare() s := New(Config{CloudflareBaseDomain: "fleet.example.invalid", CloudflareAccessLifetime: 24 * time.Hour, @@ -376,7 +376,7 @@ func TestCreateRecoveryRetainsSelectionAndAbsentWatch(t *testing.T) { } var original AccessCredential if kind == "token" { - original, e = s.ResolveAccessCredential(t.Context(), credentialRef(m.NodeID, m.Epoch, 1)) + original, e = s.ResolveAccessCredential(t.Context(), credentialRef(m.NodeID, 1)) if e != nil { t.Fatal(e) } @@ -392,7 +392,7 @@ func TestCreateRecoveryRetainsSelectionAndAbsentWatch(t *testing.T) { t.Fatal("late result replaced selected identity", again, f.resources) } if kind == "token" { - current, e := s.ResolveAccessCredential(t.Context(), credentialRef(m.NodeID, m.Epoch, 1)) + current, e := s.ResolveAccessCredential(t.Context(), credentialRef(m.NodeID, 1)) if e != nil || current != original { t.Fatal("immutable secret changed", e) } @@ -483,7 +483,7 @@ func TestAccessSecretCheckpointAndStrandedDeletionRecovery(t *testing.T) { t.Fatal(e) } var bound string - if e = s.db.QueryRow(`SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND epoch=$2 AND version=1`, m.NodeID, m.Epoch).Scan(&bound); e != nil || bound != selected.ID || len(base.resources) != 1 { + if e = s.db.QueryRow(`SELECT provider_id FROM lpcc.access_credentials WHERE node_id=$1 AND version=1`, m.NodeID).Scan(&bound); e != nil || bound != selected.ID || len(base.resources) != 1 { t.Fatal("resource/secret binding did not converge", bound, selected, e) } } @@ -526,7 +526,7 @@ func TestSupersededCreateHandoffSurvivesCleanupFailure(t *testing.T) { if _, e = l.ensure(t.Context(), key, "policy", "app-id", "token-b"); e == nil { t.Fatal("cleanup failure not injected") } - persisted, _, e := s.Load(t.Context(), m.NodeID, m.Epoch) + persisted, _, e := s.Load(t.Context(), m.NodeID) if e != nil { t.Fatal(e) } diff --git a/api/internal/controlplane/tunnel/types.go b/api/internal/controlplane/tunnel/types.go index 65458d7..7c34ed9 100644 --- a/api/internal/controlplane/tunnel/types.go +++ b/api/internal/controlplane/tunnel/types.go @@ -10,7 +10,6 @@ import ( // reconciler renders it. A source generation changes when its URL or credential // reference changes; transport health alone does not replace a Collector source. type RoutingState struct { - EndpointSuffix string `json:"endpoint_suffix"` CertificatePackID string `json:"certificate_pack_id,omitempty"` CertificateStatus string `json:"certificate_status,omitempty"` EndpointGeneration int64 `json:"endpoint_generation"` @@ -75,9 +74,7 @@ type AccessCredential struct { } type DiscoverySource struct { - ID string `json:"id"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` URL string `json:"url"` ServiceURL string `json:"service_url"` ProxyURLTemplate string `json:"proxy_url_template"` diff --git a/api/internal/controlplane/tunnel_recovery_test.go b/api/internal/controlplane/tunnel_recovery_test.go index 053708d..4fed7c1 100644 --- a/api/internal/controlplane/tunnel_recovery_test.go +++ b/api/internal/controlplane/tunnel_recovery_test.go @@ -27,10 +27,10 @@ func TestArtifactPublicationFencesAfterLockWait(t *testing.T) { if e != nil { t.Fatal(e) } - old := tunnel.RoutingFor(m.NodeID, "example.invalid", "aaaaaaa") + old := tunnel.RoutingFor(m.NodeID, "example.invalid") raw, _ := json.Marshal(old.RoutingState) rollout, _ := json.Marshal(old.State) - execSQL(t, s.db, `INSERT INTO lpcc.machine_states(node_id,epoch,state,rollout) VALUES($1,$2,$3,$4)`, m.NodeID, m.Epoch, string(raw), string(rollout)) + execSQL(t, s.db, `INSERT INTO lpcc.machine_states(node_id,state,rollout) VALUES($1,$2,$3)`, m.NodeID, string(raw), string(rollout)) if e = s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -56,13 +56,13 @@ func TestArtifactPublicationFencesAfterLockWait(t *testing.T) { if _, e = tx.Exec(`UPDATE lpcc.machines SET credential_version=$2 WHERE node_id=$1`, m.NodeID, m.CredentialVersion); e != nil { t.Fatal(e) } - if _, e = tx.Exec(`UPDATE lpcc.enrollments SET credential_version=$3 WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch, m.CredentialVersion); e != nil { + if _, e = tx.Exec(`UPDATE lpcc.enrollments SET credential_version=$2 WHERE node_id=$1`, m.NodeID, m.CredentialVersion); e != nil { t.Fatal(e) } } else { raw, _ = json.Marshal(newer.RoutingState) rollout, _ = json.Marshal(newer.State) - if _, e = tx.Exec(`UPDATE lpcc.machine_states SET state=$3,rollout=$4,revision=revision+1 WHERE node_id=$1 AND epoch=$2`, m.NodeID, m.Epoch, string(raw), string(rollout)); e != nil { + if _, e = tx.Exec(`UPDATE lpcc.machine_states SET state=$2,rollout=$3,revision=revision+1 WHERE node_id=$1`, m.NodeID, string(raw), string(rollout)); e != nil { t.Fatal(e) } } @@ -144,19 +144,19 @@ func TestOfflineSecurityMaintenanceAndRotationRecovery(t *testing.T) { adminA(t, s) path := "/api/admin/machines/" + c["node_id"] + "/tunnel/rotate" for _, kind := range []string{"connector", "access"} { - requireStatus(t, request(t, s, "POST", path, "session-a", map[string]any{"epoch": c["epoch"], "kind": kind, "compromised": true}), 202) + requireStatus(t, request(t, s, "POST", path, "session-a", map[string]any{"kind": kind, "compromised": true}), 202) } execSQL(t, s.db, `UPDATE lpcc.machine_reports SET received_at=now()-interval '1 hour'`) driveTunnels(t, s) driveTunnels(t, s) - current, _, e := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + current, _, e := s.loadTunnel(t.Context(), c["node_id"]) if e != nil || current.CredentialGeneration != initial.CredentialGeneration+1 || current.AccessVersion != initial.AccessVersion+1 || current.Ready || base.disconnected != 1 { t.Fatal(current, base.disconnected, e) } if f.calls != map[bool]int{false: 2, true: 1}[lose] { t.Fatal("rotation replayed after success", f.calls) } - if _, e = s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], c["epoch"], initial.AccessVersion)); e == nil { + if _, e = s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], initial.AccessVersion)); e == nil { t.Fatal("compromised credential still resolves") } requireStatus(t, request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/tunnel/connector-token", c["token"], map[string]any{}), 409) @@ -169,18 +169,18 @@ func TestExpiredUnacknowledgedAccessVersionsRecover(t *testing.T) { c := enroll(t, s, ownerA, strings.Repeat("5", 64)) initial := readyTunnel(t, s, c) adminA(t, s) - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": "access"}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": "access"}), 202) driveTunnels(t, s) if n := count(t, s, `SELECT count(*) FROM lpcc.access_credentials WHERE revoked_at IS NULL`); n != 2 { t.Fatal(n) } execSQL(t, s.db, `UPDATE lpcc.access_credentials SET expires_at=now()-interval '1 minute'`) driveTunnels(t, s) - current, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + current, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if current.AccessVersion != initial.AccessVersion+2 { t.Fatal(current) } - if _, e := s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], c["epoch"], current.AccessVersion)); e != nil { + if _, e := s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], current.AccessVersion)); e != nil { t.Fatal(e) } sources, e := s.tunnels.DiscoverySources(t.Context()) @@ -219,7 +219,7 @@ func TestEndpointFailurePreservesConnectorAndRollbackReusesOwnership(t *testing. if _, exists := f.certificatePacks[initial.CertificatePackID]; !exists { t.Fatal("failed replacement deleted predecessor certificate coverage") } - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) bundle := request(t, s, "GET", "/v1/nodes/"+c["node_id"]+"/config", c["token"], nil) files := archiveFiles(t, bundle.Body.Bytes()) if !strings.Contains(files["system/connector/tunnel.yaml"], initial.ProxyURLTemplate) || !strings.Contains(files["system/connector/tunnel.yaml"], initial.ServiceURL) { @@ -256,16 +256,16 @@ func TestLateDrainReportNeedsAuditedRetry(t *testing.T) { readyTunnel(t, s, c) adminA(t, s) path := "/api/admin/machines/" + c["node_id"] - requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"epoch": c["epoch"]}), 202) + requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{}), 202) execSQL(t, s.db, `UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{drain_started_at}',to_jsonb($1::text))`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano)) reportRuntime(t, s, c, "runner", true) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if state.Reason != "drain_timeout" || count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { t.Fatal("late report crossed drain deadline", state) } - requireStatus(t, request(t, s, "POST", path+"/drain/retry", "session-a", map[string]any{"epoch": c["epoch"], "generation": state.Generation - 1}), 409) - requireStatus(t, request(t, s, "POST", path+"/drain/retry", "session-a", map[string]any{"epoch": c["epoch"], "generation": state.Generation}), 202) + requireStatus(t, request(t, s, "POST", path+"/drain/retry", "session-a", map[string]any{"generation": state.Generation - 1}), 409) + requireStatus(t, request(t, s, "POST", path+"/drain/retry", "session-a", map[string]any{"generation": state.Generation}), 202) driveTunnels(t, s) if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { t.Fatal("old drain report satisfied new generation") @@ -328,11 +328,11 @@ func TestOfflineAccessReplacementStatusSurvivesFailure(t *testing.T) { reason, recovered = "access_credential_expired", "" } else { adminA(t, s) - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": "access"}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": "access"}), 202) } for i := 0; i < 2; i++ { driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if state.AccessVersion != initial.AccessVersion+1 || state.Reason != "runtime_offline" || state.RotationReason != reason { t.Fatal("lost credential failure cause", state) } @@ -341,7 +341,7 @@ func TestOfflineAccessReplacementStatusSurvivesFailure(t *testing.T) { // Allow the persisted retry deadline without waiting in the test. execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=jsonb_set(state,'{resources,token-2,attempt_at}',to_jsonb($1::text))`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano)) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if state.Reason != "runtime_offline" || state.RotationReason != recovered || state.Ready { t.Fatal("recovery lost independent Runtime state", state) } @@ -357,7 +357,7 @@ func (f *dnsDeleteFailure) Delete(ctx context.Context, r tunnel.CFResource, targ } return f.simulatedCloudflare.Delete(ctx, r, target) } -func TestLateRetiredResultWithdrawsSuccessorReadiness(t *testing.T) { +func TestLateRetiredResultCannotAffectReplacementReadiness(t *testing.T) { s, base := tunnelTestServer(t) c := enroll(t, s, ownerA, strings.Repeat("c", 64)) old := readyTunnel(t, s, c) @@ -372,7 +372,7 @@ func TestLateRetiredResultWithdrawsSuccessorReadiness(t *testing.T) { readyTunnel(t, s, newC) late.ID = "late-old-dns" base.resources[late.ID] = late - execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=jsonb_set(state,'{resources,g1-dns-0,audit_after}',to_jsonb($1::text)) WHERE epoch=$2`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano), c["epoch"]) + execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=jsonb_set(state,'{resources,g1-dns-0,audit_after}',to_jsonb($1::text)) WHERE node_id=$2`, time.Now().Add(-time.Hour).Format(time.RFC3339Nano), c["node_id"]) testTunnelDeps(s).Provider = &dnsDeleteFailure{base} configureTestTunnels(t, s) // Two passes remove dependence on enrollment row enumeration order. @@ -382,11 +382,18 @@ func TestLateRetiredResultWithdrawsSuccessorReadiness(t *testing.T) { if e != nil { t.Fatal(e) } + found := false for _, source := range sources { - if source.Epoch == newC["epoch"] && (source.Ready || source.Reason != "predecessor_cleanup_pending") { - t.Fatal("advertised successor with unresolved predecessor", source) + if source.NodeID == newC["node_id"] { + found = true + if !source.Ready { + t.Fatal("retired node cleanup changed replacement readiness", source) + } } } + if !found { + t.Fatal("replacement source was removed by old cleanup") + } testTunnelDeps(s).Provider = base configureTestTunnels(t, s) driveTunnels(t, s) @@ -415,7 +422,7 @@ func TestOfflineAcknowledgementRetiresOverlapAndPermitsNextRotation(t *testing.T readyTunnel(t, s, c) adminA(t, s) path := "/api/admin/machines/" + c["node_id"] + "/tunnel/rotate" - rotate := map[string]any{"epoch": c["epoch"], "kind": "access"} + rotate := map[string]any{"kind": "access"} requireStatus(t, request(t, s, "POST", path, "session-a", rotate), 202) driveTunnels(t, s) sources, e := s.tunnels.DiscoverySources(t.Context()) @@ -427,7 +434,7 @@ func TestOfflineAcknowledgementRetiresOverlapAndPermitsNextRotation(t *testing.T } execSQL(t, s.db, `UPDATE lpcc.machine_reports SET received_at=now()-interval '1 hour'`) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) current := state.Resources["token-2"].ID if count(t, s, `SELECT count(*) FROM lpcc.access_credentials WHERE revoked_at IS NULL`) != 1 { t.Fatal("acknowledged predecessor retained offline") @@ -439,7 +446,7 @@ func TestOfflineAcknowledgementRetiresOverlapAndPermitsNextRotation(t *testing.T } requireStatus(t, request(t, s, "POST", path, "session-a", rotate), 202) driveTunnels(t, s) - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if state.AccessVersion != 3 { t.Fatal("acknowledged overlap blocked next rotation", state) } @@ -465,7 +472,7 @@ func TestEndpointDrainCancellationAndFailedStageRollback(t *testing.T) { testTunnelDeps(s).Provider = f configureTestTunnels(t, s) driveTunnels(t, s) - current, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + current, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if current.DrainRequested || current.Target != "" || current.ServiceURL != initial.ServiceURL { t.Fatal("obsolete endpoint drain survived rollback", current) } @@ -473,7 +480,7 @@ func TestEndpointDrainCancellationAndFailedStageRollback(t *testing.T) { reportRuntime(t, s, c, "runtime", true) reportRuntime(t, s, c, "connector", true) driveTunnels(t, s) - current, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + current, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if !current.Ready { t.Fatal("rollback to applied workload imposed another drain", current) } @@ -491,15 +498,15 @@ func TestUnfinishedEndpointDrainCannotResetItsDeadline(t *testing.T) { execSQL(t, s.db, `UPDATE lpcc.machine_states SET rollout=jsonb_set(rollout,'{drain_started_at}',to_jsonb($1::text))`, old.Format(time.RFC3339Nano)) reportRuntime(t, s, c, "runner", true) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if state.Reason != "drain_timeout" || state.ServiceURL != initial.ServiceURL || !state.DrainStartedAt.Equal(old) { t.Fatal("same-target retry revived expired drain", state) } adminA(t, s) - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/drain/retry", "session-a", map[string]any{"epoch": c["epoch"], "generation": state.Generation}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/drain/retry", "session-a", map[string]any{"generation": state.Generation}), 202) reportRuntime(t, s, c, "runner", true) driveTunnels(t, s) - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if state.ServiceURL == initial.ServiceURL { t.Fatal("audited endpoint retry did not proceed", state) } @@ -533,13 +540,13 @@ func TestProtectionFailuresPreserveOrRestoreAppliedIngressOffline(t *testing.T) } f.failure = tunnel.ErrUnsafeProtection driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if !state.Quarantined || len(base.configurations[initial.TunnelID]) != 1 { t.Fatal("unsafe policy left routes exposed", state) } f.failure = nil driveTunnels(t, s) - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if state.Quarantined || state.Reason != "runtime_offline" || ingressHash(base.configurations[initial.TunnelID]) != initial.IngressDigest { t.Fatal("verified offline protection did not restore applied ingress", state) } @@ -576,7 +583,7 @@ func TestRemovalRevokesReconnectingConnectorAndResumesLostResponse(t *testing.T) } driveTunnels(t, s) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if !state.CleanupComplete || len(base.resources) != 0 { t.Fatal("connector could reauthenticate during deletion", state, base.resources) } @@ -594,7 +601,7 @@ func TestModernIneligibleMachineCanCompleteRemoval(t *testing.T) { c := enroll(t, s, ownerA, strings.Repeat("e", 64)) execSQL(t, s.db, `UPDATE lpcc.machines SET tunnel_eligible=false`) adminA(t, s) - requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{"epoch": c["epoch"]}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+c["node_id"], "session-a", map[string]any{}), 202) reportRuntime(t, s, c, "runner", true) driveTunnels(t, s) driveTunnels(t, s) @@ -618,24 +625,24 @@ func TestAcknowledgedRetirementCheckpointCanResumeReplacement(t *testing.T) { } if compromised { adminA(t, s) - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": "access", "compromised": true}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": "access", "compromised": true}), 202) } else { execSQL(t, s.db, `UPDATE lpcc.access_credentials SET expires_at=now()-interval '1 minute'`) } testTunnelDeps(s).Provider = &lostTokenCheckpoint{simulatedCloudflare: base, lostDelete: true} configureTestTunnels(t, s) driveTunnels(t, s) - checkpoint, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + checkpoint, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if checkpoint.AccessVersion != initial.AccessVersion || !checkpoint.Resources["token-1"].Absent || count(t, s, `SELECT count(*) FROM lpcc.access_credentials WHERE revoked_at IS NOT NULL AND acknowledged_at IS NOT NULL`) != 1 { t.Fatal("retirement checkpoint was not reached", checkpoint) } // driveTunnels reloads the lease and JSON, including the retained old ack. driveTunnels(t, s) - recovered, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + recovered, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if recovered.AccessVersion != initial.AccessVersion+1 { t.Fatal("old acknowledgement blocked replacement", recovered) } - if _, e = s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], c["epoch"], recovered.AccessVersion)); e != nil { + if _, e = s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], recovered.AccessVersion)); e != nil { t.Fatal(e) } }) @@ -678,7 +685,7 @@ func TestCompletedCleanupAuditsDueWatchesBeforeDeletingLateTunnel(t *testing.T) t.Fatal(e) } driveTunnels(t, s) - state, revision, e := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, revision, e := s.loadTunnel(t.Context(), c["node_id"]) if e != nil || !state.CleanupComplete { t.Fatal(state, e) } @@ -686,7 +693,7 @@ func TestCompletedCleanupAuditsDueWatchesBeforeDeletingLateTunnel(t *testing.T) testTunnelDeps(s).Provider = f configureTestTunnels(t, s) driveTunnels(t, s) - _, after, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + _, after, _ := s.loadTunnel(t.Context(), c["node_id"]) if f.inventories != 0 || after != revision { t.Fatal("completed retirement ignored audit interval", f.inventories, revision, after) } @@ -696,7 +703,7 @@ func TestCompletedCleanupAuditsDueWatchesBeforeDeletingLateTunnel(t *testing.T) if f.inventories == 0 { t.Fatal("due watch was never inventoried") } - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if !state.CleanupComplete || !time.Now().Before(state.Resources["tunnel"].AuditAfter) { t.Fatal("empty audit did not reschedule", state) } @@ -708,12 +715,12 @@ func TestCompletedCleanupAuditsDueWatchesBeforeDeletingLateTunnel(t *testing.T) f.failDelete = true execSQL(t, s.db, `UPDATE lpcc.machine_states SET state=jsonb_set(state,'{resources,tunnel,audit_after}',to_jsonb($1::text))`, overdue) driveTunnels(t, s) - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if state.CleanupComplete || !state.ConnectorRevoked || f.rotations != 1 { t.Fatal("late tunnel bypassed revocation", state, f.rotations) } driveTunnels(t, s) - state, _, _ = s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ = s.loadTunnel(t.Context(), c["node_id"]) if !state.CleanupComplete || len(base.resources) != 0 || f.rotations != 1 { t.Fatal("reopened cleanup did not resume", state, f.rotations) } diff --git a/api/internal/controlplane/tunnels.go b/api/internal/controlplane/tunnels.go index a105466..6f716ec 100644 --- a/api/internal/controlplane/tunnels.go +++ b/api/internal/controlplane/tunnels.go @@ -38,8 +38,8 @@ func (s *Server) RunTunnels(ctx context.Context) { s.tunnels.Run(ctx, s.params.ConfigReconcileInterval, s.requestReconcile) } -func (s *Server) loadTunnel(ctx context.Context, node, epoch string) (tunnel.Snapshot, int64, error) { - state, revision, err := s.tunnels.Load(ctx, node, epoch) +func (s *Server) loadTunnel(ctx context.Context, node string) (tunnel.Snapshot, int64, error) { + state, revision, err := s.tunnels.Load(ctx, node) if errors.Is(err, tunnel.ErrPending) { err = problem(409, "tunnel_pending", "Tunnel is not provisioned.") } diff --git a/api/internal/controlplane/tunnels_test.go b/api/internal/controlplane/tunnels_test.go index e142fe6..93eb319 100644 --- a/api/internal/controlplane/tunnels_test.go +++ b/api/internal/controlplane/tunnels_test.go @@ -202,8 +202,8 @@ func ingressHash(r []tunnel.IngressRule) string { return hex.EncodeToString(h[:]) } -func credentialRef(node, epoch string, version int64) string { - return "access/" + node + "/" + epoch + "/" + strconv.FormatInt(version, 10) +func credentialRef(node string, version int64) string { + return "access/" + node + "/" + strconv.FormatInt(version, 10) } func driveTunnels(t *testing.T, s *Server) { @@ -227,12 +227,12 @@ func reportRuntime(t *testing.T, s *Server, c map[string]string, component strin if e != nil { t.Fatal(e) } - state, _, e := s.loadTunnel(t.Context(), m.NodeID, m.Epoch) + state, _, e := s.loadTunnel(t.Context(), m.NodeID) gen := int64(1) if e == nil { gen = state.Generation } - r := tunnel.MachineReport{Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Component: component, Generation: gen, K3sVersion: m.K3sVersion, ConfigDigest: machineconfig.Digest(desiredConfiguration(s, m, &state)), HTTPS: true, Ready: ready, ProviderVersion: state.ProviderVersion, TokenGeneration: state.CredentialGeneration, Reason: "ready"} + r := tunnel.MachineReport{NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, Component: component, Generation: gen, K3sVersion: m.K3sVersion, ConfigDigest: machineconfig.Digest(desiredConfiguration(s, m, &state)), HTTPS: true, Ready: ready, ProviderVersion: state.ProviderVersion, TokenGeneration: state.CredentialGeneration, Reason: "ready"} if component == "connector" { r.ConnectorObservedAt = time.Now().UTC() r.ConnectorExpiresAt = r.ConnectorObservedAt.Add(time.Minute) @@ -240,14 +240,14 @@ func reportRuntime(t *testing.T, s *Server, c map[string]string, component strin if component == "runner" { r.BundleFormat = contract.BundleFormat r.Apps = &contract.AppStatus{Instances: []contract.InstanceStatus{}} - rollout, err := (machineconfig.Store{DB: s.db}).Load(t.Context(), m.NodeID, m.Epoch) + rollout, err := (machineconfig.Store{DB: s.db}).Load(t.Context(), m.NodeID) if err != nil { t.Fatal(err) } if ready && rollout.DrainRequested { now := time.Now().UTC() r.Drained = true - r.Evidence = &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(m.NodeID, m.Epoch, rollout.State), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)} + r.Evidence = &contract.Evidence{Kind: "no_owner", Target: machineconfig.DrainTarget(m.NodeID, rollout.State), WithdrawalID: "withdrawal", ObservedAt: now, ExpiresAt: now.Add(30 * time.Second)} } } r = currentReport(t, s, m.NodeID, r) @@ -264,7 +264,7 @@ func readyTunnel(t *testing.T, s *Server, c map[string]string) tunnel.Snapshot { reportRuntime(t, s, c, "runtime", true) reportRuntime(t, s, c, "connector", true) driveTunnels(t, s) - state, _, e := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, e := s.loadTunnel(t.Context(), c["node_id"]) if e != nil || !state.Ready { m, _ := s.authenticateMachine(t.Context(), c["node_id"], c["token"], false) report, at, err := (machineconfig.Store{DB: s.db}).Report(t.Context(), configurationMachine(m), "runtime") @@ -280,7 +280,7 @@ func TestTunnelDurabilityPartialFailureAndIsolation(t *testing.T) { f.lostKind = "tunnel" reportRuntime(t, s, a, "runtime", false) driveTunnels(t, s) - first, _, e := s.loadTunnel(t.Context(), a["node_id"], a["epoch"]) + first, _, e := s.loadTunnel(t.Context(), a["node_id"]) if e != nil || !first.Resources["tunnel"].Pending { t.Fatal("create intent not retained", e) } @@ -293,7 +293,7 @@ func TestTunnelDurabilityPartialFailureAndIsolation(t *testing.T) { for i := 0; i < 3; i++ { driveTunnels(t, s) } - current, _, _ := s.loadTunnel(t.Context(), a["node_id"], a["epoch"]) + current, _, _ := s.loadTunnel(t.Context(), a["node_id"]) if current.TunnelID != oldID || f.creates["tunnel"] != 2 { t.Fatal("restart/retry replaced tunnel") } @@ -354,7 +354,7 @@ func TestLostAccessSecretIsReplacedWithoutOrphan(t *testing.T) { t.Fatal("stranded Access token", count, f.creates) } } -func TestEpochRetirementAndRefresh(t *testing.T) { +func TestNodeIdentityRetirementAndRefresh(t *testing.T) { s, _ := tunnelTestServer(t) c := enroll(t, s, ownerA, strings.Repeat("d", 64)) state := readyTunnel(t, s, c) @@ -371,8 +371,8 @@ func TestEpochRetirementAndRefresh(t *testing.T) { if repeated.Code != 200 || repeated.Body.String() != w.Body.String() { t.Fatal("refresh retry changed credential") } - if fresh["epoch"] != c["epoch"] || fresh["token"] == c["token"] { - t.Fatal("refresh changed epoch or reused credential") + if fresh["node_id"] != c["node_id"] || fresh["token"] == c["token"] { + t.Fatal("refresh changed node or reused credential") } if w = request(t, s, "GET", "/v1/nodes/"+c["node_id"]+"/config", c["token"], nil); w.Code != 401 { t.Fatal("old credential still works") @@ -395,22 +395,22 @@ func TestEpochRetirementAndRefresh(t *testing.T) { t.Fatal("terminal cleanup storage/upgrade inventory") } newer := enroll(t, s, ownerA, strings.Repeat("d", 64)) - if newer["epoch"] == fresh["epoch"] || newer["token"] == fresh["token"] { + if newer["node_id"] == fresh["node_id"] || newer["token"] == fresh["token"] { t.Fatal("new enrollment reused identity") } old := request(t, s, "GET", "/v1/nodes/"+c["node_id"]+"/config", fresh["token"], nil) - active := request(t, s, "GET", "/v1/nodes/"+c["node_id"]+"/config", newer["token"], nil) + active := request(t, s, "GET", "/v1/nodes/"+newer["node_id"]+"/config", newer["token"], nil) if old.Header().Get("X-Livepeer-Terminal") != "true" || active.Header().Get("X-Livepeer-Terminal") != "false" { - t.Fatal("epoch artifacts crossed") + t.Fatal("node artifacts crossed") } if w = request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/tunnel/connector-token", fresh["token"], map[string]any{}); w.Code != 401 { t.Fatal("retired credential got new tunnel token") } - if _, e := s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], c["epoch"], state.AccessVersion)); e == nil { + if _, e := s.tunnels.ResolveAccessCredential(t.Context(), credentialRef(c["node_id"], state.AccessVersion)); e == nil { t.Fatal("retired source secret resolved") } digest := sha256.Sum256(terminal.Body.Bytes()) - ack := request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/removal-ack", fresh["token"], map[string]any{"epoch": c["epoch"], "digest": hex.EncodeToString(digest[:]), "connector_absent": true}) + ack := request(t, s, "POST", "/v1/nodes/"+c["node_id"]+"/removal-ack", fresh["token"], map[string]any{"node_id": c["node_id"], "digest": hex.EncodeToString(digest[:]), "connector_absent": true}) if ack.Code != 200 { t.Fatal(ack.Code, ack.Body.String()) } @@ -423,7 +423,7 @@ func TestTunnelRotationNeedsConsumerAcknowledgement(t *testing.T) { t.Fatal(e) } driveTunnels(t, s) - next, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + next, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if next.AccessVersion != 2 || next.SourceGeneration != 2 || next.TunnelID != initial.TunnelID { t.Fatal("incorrect Access rotation", next) } @@ -442,9 +442,9 @@ func TestTunnelRotationNeedsConsumerAcknowledgement(t *testing.T) { t.Fatal("old Access token not retired") } adminA(t, s) - requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"epoch": c["epoch"], "kind": "connector"}), 202) + requireStatus(t, request(t, s, "POST", "/api/admin/machines/"+c["node_id"]+"/tunnel/rotate", "session-a", map[string]any{"kind": "connector"}), 202) driveTunnels(t, s) - rotated, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + rotated, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if rotated.TunnelID != initial.TunnelID || rotated.CredentialGeneration != 2 || f.creates["tunnel"] != 1 { t.Fatal("connector rotation replaced tunnel") } @@ -459,7 +459,7 @@ func TestSupabaseCascadeRetiresTunnels(t *testing.T) { } driveTunnels(t, s) var retired, complete bool - e := s.db.QueryRow(`SELECT e.retired_at IS NOT NULL,(t.state->>'cleanup_complete')::boolean FROM lpcc.enrollments e JOIN lpcc.machine_states t USING(node_id,epoch) WHERE e.node_id=$1`, c["node_id"]).Scan(&retired, &complete) + e := s.db.QueryRow(`SELECT e.retired_at IS NOT NULL,(t.state->>'cleanup_complete')::boolean FROM lpcc.enrollments e JOIN lpcc.machine_states t USING(node_id) WHERE e.node_id=$1`, c["node_id"]).Scan(&retired, &complete) if e != nil || !retired || !complete || len(f.resources) != 0 { t.Fatal("cascade lost cleanup", retired, complete, e, len(f.resources)) } @@ -474,11 +474,11 @@ func TestTunnelDrainRolloutAndObservationExpiry(t *testing.T) { if e != nil { t.Fatal(e) } - stateBefore := tunnel.RoutingFor(m.NodeID, s.params.CloudflareBaseDomain, "aaaaaaa") + stateBefore := tunnel.RoutingFor(m.NodeID, s.params.CloudflareBaseDomain) stateBefore.IngressDigest = "configured-before-drain-intent" raw, _ := json.Marshal(stateBefore.RoutingState) rollout, _ := json.Marshal(stateBefore.State) - execSQL(t, s.db, `INSERT INTO lpcc.machine_states(node_id,epoch,state,rollout) VALUES($1,$2,$3,$4)`, m.NodeID, m.Epoch, string(raw), string(rollout)) + execSQL(t, s.db, `INSERT INTO lpcc.machine_states(node_id,state,rollout) VALUES($1,$2,$3)`, m.NodeID, string(raw), string(rollout)) if e = s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -487,7 +487,7 @@ func TestTunnelDrainRolloutAndObservationExpiry(t *testing.T) { } reportRuntime(t, s, c, "runtime", false) driveTunnels(t, s) - state, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + state, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if !state.DrainRequested || state.HeldOrchestrator != old { t.Fatal("Node replacement not drain gated") } @@ -524,17 +524,17 @@ func TestTunnelAdministrativeDrainAndRotation(t *testing.T) { c := enroll(t, s, ownerA, strings.Repeat("8", 64)) state := readyTunnel(t, s, c) path := "/api/admin/machines/" + c["node_id"] - in := map[string]any{"epoch": c["epoch"], "kind": "connector", "compromised": true} + in := map[string]any{"kind": "connector", "compromised": true} requireStatus(t, request(t, s, "POST", path+"/tunnel/rotate", "session-a", in), 403) adminA(t, s) requireStatus(t, request(t, s, "POST", path+"/tunnel/rotate", "session-a", in), 202) driveTunnels(t, s) - rotated, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + rotated, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if rotated.TunnelID != state.TunnelID || rotated.CredentialGeneration != 2 || f.disconnected != 1 { t.Fatal("compromise rotation failed", rotated, f.disconnected) } - requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"epoch": uuid.New().String()}), 409) - requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{"epoch": c["epoch"]}), 202) + requireStatus(t, request(t, s, "DELETE", "/api/admin/machines/"+strings.Repeat("z", 26), "session-a", map[string]any{}), 404) + requireStatus(t, request(t, s, "DELETE", path, "session-a", map[string]any{}), 202) driveTunnels(t, s) if count(t, s, `SELECT count(*) FROM lpcc.machines`) != 1 { t.Fatal("removal skipped drain") @@ -566,7 +566,7 @@ func TestEndpointReplacementRequiresCurrentSourceAcknowledgement(t *testing.T) { reportRuntime(t, s, c, "runtime", true) reportRuntime(t, s, c, "connector", true) driveTunnels(t, s) - current, _, _ := s.loadTunnel(t.Context(), c["node_id"], c["epoch"]) + current, _, _ := s.loadTunnel(t.Context(), c["node_id"]) if current.TunnelID != initial.TunnelID || current.SourceGeneration != 2 || current.AccessVersion != initial.AccessVersion { t.Fatal("endpoint update changed identity", current) } @@ -638,7 +638,7 @@ func TestAccessCredentialReencryption(t *testing.T) { s, _ := tunnelTestServer(t) c := enroll(t, s, ownerA, strings.Repeat("5", 64)) readyTunnel(t, s, c) - ref := credentialRef(c["node_id"], c["epoch"], 1) + ref := credentialRef(c["node_id"], 1) before, e := s.tunnels.ResolveAccessCredential(t.Context(), ref) if e != nil { t.Fatal(e) diff --git a/deploy/onchain.example.json b/deploy/onchain.example.json index 5e04179..10a8cb4 100644 --- a/deploy/onchain.example.json +++ b/deploy/onchain.example.json @@ -1,7 +1,7 @@ { "version": 1, "machines": { - "lp-aaaaaaaaaaaaaaaa": { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": { "version": 1, "credential_revision": 1, "mode": "onchain", @@ -18,6 +18,6 @@ "max_pending_tickets": 100000, "max_tickets_per_recipient": 10000 }, - "lp-bbbbbbbbbbbbbbbb": {"version": 1, "mode": "offchain"} + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": {"version": 1, "mode": "offchain"} } } diff --git a/docs/app-registry.md b/docs/app-registry.md index 7396a3c..06363a7 100644 --- a/docs/app-registry.md +++ b/docs/app-registry.md @@ -172,15 +172,15 @@ bootstrap JWTs and machine service credentials cannot mutate assignments. Let | Method and route | Body or query | | --- | --- | | `GET M` | `limit` (50 default, 100 maximum), exclusive `after_revision_id` | -| `GET M/{revision_id}` | Optional retained `epoch`; history `limit`, exclusive `before_generation` | -| `PUT M/{revision_id}` | `epoch`, `digest`, `expected_generation`, optional `replicas` | -| `DELETE M/{revision_id}` | `epoch`, `expected_generation` | -| `POST M/{revision_id}/replace` | `epoch`, `expected_generation`, `target: {revision_id, digest, expected_generation, replicas?}` | +| `GET M/{revision_id}` | History `limit`, exclusive `before_generation` | +| `PUT M/{revision_id}` | `digest`, `expected_generation`, optional `replicas` | +| `DELETE M/{revision_id}` | `expected_generation` | +| `POST M/{revision_id}/replace` | `expected_generation`, `target: {revision_id, digest, expected_generation, replicas?}` | Writes require a current active enrollment with modern credentials. `expected_generation: 0` means never assigned. Replicas range from 1 to 100; omitting them uses the definition default on creation and preserves the count on -scaling. Changed operations return 202 and `{changed, epoch, assignments}`; +scaling. Changed operations return 202 and `{changed, node_id, assignments}`; identical completed retries return 200 without advancing generations. Concurrent edits return 409. A lost-response retry must match the immediately resulting version and complete desired result; an intervening edit conflicts even if values @@ -235,7 +235,7 @@ Runtime reports with the machine service credential to to 16 KiB: ```json -{"epoch":"","credential_version":1,"generation":2, +{"node_id":"","credential_version":1,"generation":2, "activation_generation":1,"apps_digest":"sha256:", "phase":"removed","reason":""} ``` @@ -267,7 +267,7 @@ waits for app cleanup and machine drain completion. Force removal and owner deletion retain terminal instructions and history. Terminal removal acknowledgement also requires app cleanup. A retired enrollment can fetch its terminal bundle and acknowledge exact terminal app cleanup, but cannot report active state or -administer apps. Terminal snapshots are write-once, and old-epoch cleanup cannot +administer apps. Terminal snapshots are write-once, and retired-node cleanup cannot affect reenrollment. Node, routes, the Reconciler and connector credentials remain available until app cleanup receipts complete; credential compromise overrides that hold. diff --git a/docs/fleet-discovery.md b/docs/fleet-discovery.md index b7d78a7..c72f6d5 100644 --- a/docs/fleet-discovery.md +++ b/docs/fleet-discovery.md @@ -41,9 +41,8 @@ withdraws the source immediately. An empty selection is valid. Unverified provisioning generations are excluded; previously approved offline generations continue polling, including after restart. Draining sources remain selected to observe withdrawals. Removed enrollments and blocked ingress are -excluded. Replacement resets the predecessor's cache even when the URL is -reused; an unverified replacement cannot retain that cache or admit its new -endpoint or credential. Follow the tunnel runbook's drain, acknowledgement and +excluded. Re-enrollment has a fresh node ID and endpoint. Removing the old +source removes its cached inventory; an unverified replacement stays excluded. Follow the tunnel runbook's drain, acknowledgement and provider cleanup order before retiring resources. Credentials are immutable, AES-GCM encrypted PostgreSQL versions; only the @@ -56,14 +55,15 @@ there is no plaintext credential export or unauthenticated fallback. Requests use verified TLS, a three-second timeout, no environment proxy, cookies or redirects, and Node's destination policy and 1 MiB source-body limit. The Collector ignores advertised peer metadata and never collects its own origin. -Credential changes trigger a refresh, including a bounded follow-up when older -work was already in flight. HTTP reads never poll sources. +Credential changes apply to the next scheduled poll. Existing snapshots retain +their original times across credential rotation. HTTP reads never poll sources. For ordinary Access rotation, publish the new credential with provider overlap as described in the tunnel runbook. Confirm discovery acknowledgement and subsequent provider retirement before finishing. Acknowledgement requires a new, -successfully decoded observation for the exact source incarnation and credential -version with the expected owning address. An old in-flight response, login HTML +successfully decoded response using the current source credential with the +expected owning address. The transport validates bounded response bytes using +Node's shared codec; the Collector independently owns cached observations. An old in-flight response, login HTML or eviction cannot acknowledge it; an unsafe app URL alone does not block retirement. Use the runbook's compromise path for immediate revocation and its controlled restart/re-encryption procedure for keyring rotation. diff --git a/docs/machine-tunnels.md b/docs/machine-tunnels.md index 7e409db..e780ef4 100644 --- a/docs/machine-tunnels.md +++ b/docs/machine-tunnels.md @@ -83,9 +83,11 @@ Cloudflare. See ## Enrollment, refresh and status -Identity is `(node_id, enrollment_epoch)`, with a separate credential version. -Idempotent active registration retains both; refresh increments only credential -version. Deletion and re-enrollment create a new epoch and tunnel UUID. +Node IDs are lowercase, unpadded base32 encodings of 128 random bits. Active +registration retries retain the node ID; credential refresh changes only its +credential version. Re-enrollment creates a fresh node ID and tunnel UUID. +The full installation fingerprint associates persistent payment infrastructure +with the installation; cleanup and credentials remain scoped to the node ID. Cloudflare Tunnel must be the HTTPS front door, with the API origin reachable only through the trusted connector. The API does not infer transport security from arbitrary forwarded headers. HTTPS enrollment is eligible even when @@ -99,7 +101,7 @@ development mode cannot enable live provisioning. Machine endpoints provide configuration, connector tokens, component status and terminal removal acknowledgement. They are origin-bound, reject redirects and return `Cache-Control: no-store`. Retired credentials can fetch their terminal -artifact, acknowledge its epoch and digest, and send scoped cleanup diagnostics. +artifact, acknowledge its node ID and digest, and send scoped cleanup diagnostics. See [machine and app status](machine-status.md) for evidence and recovery rules. Reports retain their observation time and expiry across delivery retries. The @@ -158,16 +160,16 @@ Existing administrator authentication/auditing protects: ```text POST /api/admin/machines//tunnel/rotate -{"epoch":"","kind":"connector|access","compromised":false} +{"kind":"connector|access","compromised":false} POST /api/admin/machines//drain/retry -{"epoch":"","generation":} +{"generation":} DELETE /api/admin/machines/ -{"epoch":"","force":false} +{"force":false} ``` -The administrator fleet response supplies the epoch. Connector rotation keeps +The administrator fleet response supplies the node ID. Connector rotation keeps the tunnel UUID, advances token generation and replaces the process. Compromise rotation also disconnects existing connectors: rotation alone leaves established connections active. Access rotation overlaps versions until successful Collector @@ -182,8 +184,8 @@ start a fresh drain with `drain/retry`, or deliberately remove with `force:true` Deletion denies token delivery, installs deny-only ingress, revokes connector authentication before disconnecting, deletes DNS/tunnel resources before Access protection, and revokes source tokens. -Cleanup proceeds even with the machine offline. A new epoch cannot reuse stable -hostnames until the predecessor's external cleanup is complete. +Cleanup proceeds even with the machine offline. Each enrollment has its own hostname namespace, so late cleanup of a retired +node cannot delete a replacement node's routes or certificates. The terminal artifact prunes the connector and orchestrator and delivers app-removal intents; Runtime cleans up assigned apps. diff --git a/runtime/README.md b/runtime/README.md index 027b441..92f578c 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -122,6 +122,10 @@ environment variable as shown in Quick start. Backend `PUBLIC_API_URL` must use the same reachable base URL. The installer rejects literal loopback configuration URLs because pods cannot use host loopback. +Each enrollment receives a fresh random base32 node ID. Registration retries +and credential refresh preserve that ID. Re-enrollment keeps payment continuity +through the full installation fingerprint and gives cleanup a separate node ID. + The one-hour bootstrap JWT can enroll multiple machines. The installer saves long-lived service credentials in owner-only files and reuses them on reruns, even after the JWT expires. A fresh registration retry requires the original diff --git a/runtime/appbundle/bundle.go b/runtime/appbundle/bundle.go index 5bf377a..cb1850d 100644 --- a/runtime/appbundle/bundle.go +++ b/runtime/appbundle/bundle.go @@ -46,11 +46,11 @@ type Payload struct { } type Options struct{ StopSignals bool } -func Key(epoch, revision string, activation int64, slot int) string { - return artifact.Digest([]byte(fmt.Sprintf("%s/%s/%d/%d", epoch, revision, activation, slot)))[7:27] +func Key(node, revision string, activation int64, slot int) string { + return artifact.Digest([]byte(fmt.Sprintf("%s/%s/%d/%d", node, revision, activation, slot)))[7:27] } func newGroup(set schema.AppAssignmentSetV1, a schema.AppAssignment, slot int) Group { - key := Key(set.Epoch, a.RevisionID, a.ActivationGeneration, slot) + key := Key(set.NodeID, a.RevisionID, a.ActivationGeneration, slot) base := "app-desired/groups/" + key + "/" return Group{Key: key, RevisionID: a.RevisionID, ActivationGeneration: a.ActivationGeneration, Slot: slot, Name: "lp-app-" + key, Files: []string{base + "pod.json", base + "service.json"}} } @@ -115,7 +115,7 @@ func payloadBytes(files map[string][]byte) int { type object = map[string]any func renderGroup(g Group, set schema.AppAssignmentSetV1, d schema.DefinitionV1) []object { - labels := map[string]string{"app": "livepeer-app", "livepeer.io/instance": g.Name, "livepeer.io/epoch": set.Epoch, "livepeer.io/egress": d.Network.Egress} + labels := map[string]string{"app": "livepeer-app", "livepeer.io/instance": g.Name, "livepeer.io/node": set.NodeID, "livepeer.io/egress": d.Network.Egress} metadata := func() object { return object{"name": g.Name, "namespace": Namespace, "labels": labels, "annotations": map[string]string{"livepeer.io/revision-id": g.RevisionID}} } @@ -204,7 +204,7 @@ func Read(files map[string][]byte, m contract.Metadata) (Payload, error) { return p, errors.New("app_digest") } set, err := schema.DecodeAssignmentSet(raw) - if err != nil || set.NodeID != m.NodeID || set.Epoch != m.Epoch || set.Generation != m.AppsGeneration { + if err != nil || set.NodeID != m.NodeID || set.Generation != m.AppsGeneration { return p, errors.New("app_identity") } expected := map[string]Group{} diff --git a/runtime/appbundle/bundle_test.go b/runtime/appbundle/bundle_test.go index 4644653..16be0c2 100644 --- a/runtime/appbundle/bundle_test.go +++ b/runtime/appbundle/bundle_test.go @@ -13,7 +13,7 @@ import ( func fixture(t *testing.T) schema.AppAssignmentSetV1 { return testutil.Assignment(t) } func metadata(p Payload) contract.Metadata { - return contract.Metadata{NodeID: p.Intent.NodeID, Epoch: p.Intent.Epoch, AppsGeneration: p.Intent.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()} + return contract.Metadata{NodeID: p.Intent.NodeID, AppsGeneration: p.Intent.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()} } func TestRenderedGroupsAndIncarnations(t *testing.T) { set := fixture(t) @@ -76,7 +76,7 @@ func TestPayloadValidationAndUnsupportedSettings(t *testing.T) { t.Fatal("accepted changed resource") } p, _ = Render(set, Options{}) - m.Epoch = "33333333-3333-4333-8333-333333333333" + m.NodeID = "33333333-3333-4333-8333-333333333333" if _, err := Read(p.Files, m); err == nil { t.Fatal("accepted foreign enrollment") } diff --git a/runtime/appreconciler/controller.go b/runtime/appreconciler/controller.go index 0a2e795..39b149d 100644 --- a/runtime/appreconciler/controller.go +++ b/runtime/appreconciler/controller.go @@ -58,7 +58,7 @@ func (c *Controller) hooks() OwnerHooks { }} } func (c *Controller) failed(f OwnerFailure) { - if c.Journal.View().OwnerEpoch != f.Epoch { + if c.Journal.View().Identity.RunnerID != f.RunnerID { return } c.mu.Lock() @@ -77,7 +77,7 @@ func (c *Controller) observe(o Observation) error { if o.Credential == "" { return errors.New("owner_credential") } - if o.Epoch != s.OwnerEpoch || s.Identity.RunnerID != o.RunnerID { + if s.Identity.RunnerID != o.RunnerID { return ErrSuperseded } if s.Identity.Credential != o.PreviousCredential && s.Identity.Credential != o.Credential { @@ -235,7 +235,7 @@ func (c *Controller) Tick(ctx context.Context) error { } if inputErr == nil { m := input.Metadata - if before.InputDigest != "" && (m.NodeID != before.Metadata.NodeID || m.Epoch != before.Metadata.Epoch || m.CredentialVersion < before.Metadata.CredentialVersion || (before.Metadata.Terminal && !m.Terminal)) { + if before.InputDigest != "" && (m.NodeID != before.Metadata.NodeID || m.CredentialVersion < before.Metadata.CredentialVersion || (before.Metadata.Terminal && !m.Terminal)) { return errors.New("input_enrollment_regression") } if m.Generation < before.Metadata.Generation || (input.Payload.Index.Available && before.Payload.Intent != nil && (input.Payload.Intent.Generation < before.Payload.Intent.Generation || (input.Payload.Intent.Generation == before.Payload.Intent.Generation && input.Payload.Index.IntentDigest != before.Payload.Index.IntentDigest))) { @@ -569,7 +569,7 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo } if err := c.Journal.Update(func(s *State) error { s.Identity = Identity{} - s.OwnerEpoch, s.OwnerReason, s.Retirement = "", "", nil + s.OwnerReason, s.Retirement = "", nil for _, i := range s.Instances { i.RegistrationPending = false if i.AppID == "" && i.WithdrawalID != "" { @@ -636,9 +636,6 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo s = c.Journal.View() } if err := c.Journal.Update(func(s *State) error { - if s.OwnerEpoch == "" { - s.OwnerEpoch = randomID() - } for _, e := range entries { if i := s.Instances[e.InstanceID]; i != nil && i.AppID == "" { i.RegistrationPending = true @@ -649,7 +646,7 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo return err } s = c.Journal.View() - r := OwnerRequest{Epoch: s.OwnerEpoch, Identity: s.Identity, Entries: entries, Tracked: tracked} + r := OwnerRequest{Identity: s.Identity, Entries: entries, Tracked: tracked} if err := c.Owner.Sync(ctx, r, c.hooks()); err != nil { c.mu.Lock() reason := c.fault @@ -657,7 +654,7 @@ func (c *Controller) syncOwner(ctx context.Context, s State, ready map[string]bo if reason == "" { reason = "registration_pending" } - c.failed(OwnerFailure{Epoch: r.Epoch, Reason: reason}) + c.failed(OwnerFailure{RunnerID: r.Identity.RunnerID, Reason: reason}) return errors.Join(err, c.Journal.Update(func(s *State) error { s.OwnerReason = reason; return nil })) } return c.Journal.Update(func(s *State) error { s.OwnerReason = ""; return nil }) @@ -683,7 +680,6 @@ func (c *Controller) retireOwner(ctx context.Context, s State) error { } } s.Identity = Identity{} - s.OwnerEpoch = "" s.OwnerReason = "" return nil }) diff --git a/runtime/appreconciler/controller_test.go b/runtime/appreconciler/controller_test.go index f18d530..1579ff3 100644 --- a/runtime/appreconciler/controller_test.go +++ b/runtime/appreconciler/controller_test.go @@ -43,7 +43,7 @@ func (i *testInputs) set(t *testing.T, set schema.AppAssignmentSetV1) { if err != nil { t.Fatal(err) } - i.value = Input{Metadata: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} + i.value = Input{Metadata: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, AppsGeneration: set.Generation, AppsDigest: p.Index.IntentDigest, AppsPayloadDigest: p.Digest()}, Payload: p, Digest: artifact.Digest([]byte(p.Digest()))} } type testCluster struct { @@ -125,7 +125,7 @@ func (o *testOwner) Sync(_ context.Context, r OwnerRequest, h OwnerHooks) error if credential == "" { credential = "issued-secret" } - obs := Observation{Epoch: r.Epoch, RunnerID: r.Identity.RunnerID, Credential: credential, PreviousCredential: r.Identity.Credential, Accepted: true, Sequence: n, Bootstrap: r.Identity.Credential == "" || (o.credential != "" && o.credential != r.Identity.Credential), At: h.Now(), TTL: 30 * time.Second, Entries: r.Entries, Withdrawals: r.Tracked} + obs := Observation{RunnerID: r.Identity.RunnerID, Credential: credential, PreviousCredential: r.Identity.Credential, Accepted: true, Sequence: n, Bootstrap: r.Identity.Credential == "" || (o.credential != "" && o.credential != r.Identity.Credential), At: h.Now(), TTL: 30 * time.Second, Entries: r.Entries, Withdrawals: r.Tracked} submitted := map[string]bool{} for _, e := range r.Entries { id := e.Options.ID @@ -207,7 +207,7 @@ func TestOwnerFailureKeepsClassificationAndUsesCurrentRecoveryDecision(t *testin } o.syncFailure = func(r OwnerRequest, h OwnerHooks) error { calls++ - h.Failure(OwnerFailure{Epoch: r.Epoch, Reason: reason, Reset: reset}) + h.Failure(OwnerFailure{RunnerID: r.Identity.RunnerID, Reason: reason, Reset: reset}) if reset { return &transport.HTTPError{Status: 401} } @@ -526,13 +526,12 @@ func TestUnavailableInputAndStateLossNeverPublishEmpty(t *testing.T) { func TestRemovalObservationIsBoundAndDurable(t *testing.T) { c, _, _, _, _, now := fixtureController(t) c.Journal.Update(func(s *State) error { - s.OwnerEpoch = "epoch" s.Identity = Identity{RunnerID: "owner", Credential: "issued"} s.Instances["i"] = &Instance{ID: "i", AppID: "app", WithdrawalID: "withdrawal", PodUID: "pod"} return nil }) e := Registration{InstanceID: "i", WithdrawalID: "wrong", PodUID: "pod"} - o := Observation{Epoch: "epoch", RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, At: *now, TTL: time.Minute, Apps: []AppObservation{}, Withdrawals: []Registration{e}} + o := Observation{RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, At: *now, TTL: time.Minute, Apps: []AppObservation{}, Withdrawals: []Registration{e}} c.observe(o) if c.Journal.View().Instances["i"].RegistrationGone { t.Fatal("wrong withdrawal accepted") @@ -561,14 +560,13 @@ func TestRemovalObservationIsBoundAndDurable(t *testing.T) { } } -func TestCredentialLineageAndOwnerEpochFence(t *testing.T) { +func TestCredentialLineageAndOwnerIdentityFence(t *testing.T) { c, _, _, _, _, _ := fixtureController(t) c.Journal.Update(func(s *State) error { s.Identity = Identity{RunnerID: "owner", Credential: "old", Confirmed: true} - s.OwnerEpoch = "epoch" return nil }) - o := Observation{RunnerID: "owner", Epoch: "epoch", PreviousCredential: "old", Credential: "rotated", Bootstrap: true} + o := Observation{RunnerID: "owner", PreviousCredential: "old", Credential: "rotated", Bootstrap: true} if err := c.observe(o); err != nil { t.Fatal(err) } @@ -582,20 +580,19 @@ func TestCredentialLineageAndOwnerEpochFence(t *testing.T) { } o.PreviousCredential = "rotated" o.Credential = "other" - o.Epoch = "other" + o.RunnerID = "other" if err := c.observe(o); !errors.Is(err, ErrSuperseded) { - t.Fatal("stale epoch accepted", err) + t.Fatal("stale node accepted", err) } } func TestRetirementPersistsCredentialIssuedBeforeHeartbeatJoin(t *testing.T) { c, _, _, _, _, _ := fixtureController(t) c.Journal.Update(func(s *State) error { - s.OwnerEpoch = "epoch" s.Identity = Identity{RunnerID: "owner", Credential: "issued", Confirmed: true, Retiring: true} return nil }) - o := Observation{Epoch: "epoch", RunnerID: "owner", PreviousCredential: "issued", Credential: "rotated", Bootstrap: true, Accepted: true, Sequence: 0} + o := Observation{RunnerID: "owner", PreviousCredential: "issued", Credential: "rotated", Bootstrap: true, Accepted: true, Sequence: 0} if err := c.observe(o); err != nil { t.Fatal("lost credential while joining SDK loop", err) } @@ -948,7 +945,6 @@ func TestAppRemovalRequiresCompleteNodeAbsence(t *testing.T) { i := &Instance{ID: "shared", PodUID: "pod", Definition: definition, WithdrawalID: "withdrawal", WithdrawnAt: *now, Phase: "withdrawing"} i.AppID = appID(i, 0) if err := c.Journal.Update(func(s *State) error { - s.OwnerEpoch = "epoch" s.Identity = Identity{RunnerID: "owner", Credential: "issued"} s.Instances[i.ID] = i return nil @@ -959,7 +955,7 @@ func TestAppRemovalRequiresCompleteNodeAbsence(t *testing.T) { if err != nil { t.Fatal(err) } - o := Observation{Epoch: "epoch", RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, At: *now, TTL: time.Minute, Withdrawals: tracked, Apps: []AppObservation{{ID: appID(i, 1), Status: "draining", SessionIDs: []string{"work"}}}} + o := Observation{RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, At: *now, TTL: time.Minute, Withdrawals: tracked, Apps: []AppObservation{{ID: appID(i, 1), Status: "draining", SessionIDs: []string{"work"}}}} if err = c.observe(o); err != nil { t.Fatal(err) } diff --git a/runtime/appreconciler/hostnames_test.go b/runtime/appreconciler/hostnames_test.go index 4761133..6e82621 100644 --- a/runtime/appreconciler/hostnames_test.go +++ b/runtime/appreconciler/hostnames_test.go @@ -23,7 +23,7 @@ func TestReservedHostnamesCannotBecomeAcceptedAppIdentities(t *testing.T) { if before.Identity.Sequence != nil { sequence = *before.Identity.Sequence + 1 } - observation := Observation{Epoch: request.Epoch, RunnerID: request.Identity.RunnerID, Credential: before.Identity.Credential, PreviousCredential: before.Identity.Credential, Accepted: true, Sequence: sequence, At: c.now(), TTL: 30 * time.Second, Entries: request.Entries} + observation := Observation{RunnerID: request.Identity.RunnerID, Credential: before.Identity.Credential, PreviousCredential: before.Identity.Credential, Accepted: true, Sequence: sequence, At: c.now(), TTL: 30 * time.Second, Entries: request.Entries} for _, entry := range request.Entries { observation.Apps = append(observation.Apps, AppObservation{ID: entry.Options.ID, Status: "ready", SessionIDs: []string{}}) } diff --git a/runtime/appreconciler/input.go b/runtime/appreconciler/input.go index 151d31a..18f9fa3 100644 --- a/runtime/appreconciler/input.go +++ b/runtime/appreconciler/input.go @@ -69,7 +69,7 @@ func (s Source) Read(ctx context.Context) (Input, error) { return input, errors.New("management_enrollment") } identity, err := transport.ReadIdentity(s.IdentityFile) - if err != nil || identity.Epoch != m.Epoch || identity.CredentialVersion != m.CredentialVersion { + if err != nil || identity.NodeID != m.NodeID || identity.CredentialVersion != m.CredentialVersion { return input, errors.New("management_enrollment") } if m.Onchain.Onchain() && m.OnchainActive { diff --git a/runtime/appreconciler/node_integration_test.go b/runtime/appreconciler/node_integration_test.go index 6b7461e..a58f0f4 100644 --- a/runtime/appreconciler/node_integration_test.go +++ b/runtime/appreconciler/node_integration_test.go @@ -110,7 +110,7 @@ func TestMergedNodeSDKDrain(t *testing.T) { for _, id := range []string{"first", "sibling"} { entries = append(entries, Registration{InstanceID: id, PodUID: "pod-" + id, Options: runner.AppOptions{ID: id, App: id, RunnerURL: app.URL + "/" + id, Mode: mode, Status: "not-ready", Capacity: 2}}) } - r := OwnerRequest{Epoch: "epoch", Identity: Identity{RunnerID: "owner"}, Entries: entries, Tracked: append([]Registration{}, entries...)} + r := OwnerRequest{Identity: Identity{RunnerID: "owner"}, Entries: entries, Tracked: append([]Registration{}, entries...)} ch := make(chan Observation, 1024) hooks := OwnerHooks{Observe: func(o Observation) error { ch <- o; return nil }} if err := owner.Sync(t.Context(), r, hooks); err != nil { @@ -248,7 +248,7 @@ func TestMergedNodeSDKRestoredMembership(t *testing.T) { } defer owner.Close(context.Background()) e := Registration{InstanceID: "instance", PodUID: "pod", Options: runner.AppOptions{ID: "app", App: "app", RunnerURL: app.URL, Mode: "persistent", Status: "not-ready", Capacity: 2}} - r := OwnerRequest{Epoch: "epoch", Identity: Identity{RunnerID: "owner"}, Entries: []Registration{e}, Tracked: []Registration{e}} + r := OwnerRequest{Identity: Identity{RunnerID: "owner"}, Entries: []Registration{e}, Tracked: []Registration{e}} events := make(chan Observation, 1024) hooks := OwnerHooks{Observe: func(o Observation) error { events <- o; return nil }} if err := owner.Sync(t.Context(), r, hooks); err != nil { @@ -360,7 +360,7 @@ func TestNativeNodeSharedAppsAndOwnedDrain(t *testing.T) { t.Fatal(err) } defer owner.Close(t.Context()) - request := OwnerRequest{Epoch: "epoch", Identity: Identity{RunnerID: "owner"}, Entries: entries, Tracked: append([]Registration{}, entries...)} + request := OwnerRequest{Identity: Identity{RunnerID: "owner"}, Entries: entries, Tracked: append([]Registration{}, entries...)} observations := make(chan Observation, 1024) hooks := OwnerHooks{Observe: func(o Observation) error { observations <- o; return nil }} if err = owner.Sync(t.Context(), request, hooks); err != nil { diff --git a/runtime/appreconciler/owner.go b/runtime/appreconciler/owner.go index b81b197..2dac0ed 100644 --- a/runtime/appreconciler/owner.go +++ b/runtime/appreconciler/owner.go @@ -29,7 +29,6 @@ type Registration struct { Options runner.AppOptions } type OwnerRequest struct { - Epoch string Identity Identity Entries []Registration Tracked []Registration @@ -37,19 +36,19 @@ type OwnerRequest struct { type AppObservation = runner.HeartbeatAppStatus type Observation struct { - Request runner.HeartbeatRequest - Epoch, RunnerID, Credential, PreviousCredential string - Sequence uint64 - Accepted bool - Bootstrap bool - At time.Time - TTL time.Duration - Entries, Withdrawals []Registration - Apps []AppObservation + Request runner.HeartbeatRequest + RunnerID, Credential, PreviousCredential string + Sequence uint64 + Accepted bool + Bootstrap bool + At time.Time + TTL time.Duration + Entries, Withdrawals []Registration + Apps []AppObservation } type OwnerFailure struct { - Epoch, Reason string - Reset, Partial bool + RunnerID, Reason string + Reset, Partial bool } type OwnerHooks struct { Observe func(Observation) error @@ -217,7 +216,7 @@ func (o *SDKOwner) heartbeat(event runner.HeartbeatEvent) { h, r, lineage := o.hooks, copyRequest(o.request), o.lineage fail := func(reason string, reset bool) { if h.Failure != nil { - h.Failure(OwnerFailure{Epoch: r.Epoch, Reason: reason, Reset: reset}) + h.Failure(OwnerFailure{RunnerID: r.Identity.RunnerID, Reason: reason, Reset: reset}) } } if event.Err != nil { @@ -252,7 +251,7 @@ func (o *SDKOwner) heartbeat(event runner.HeartbeatEvent) { o.mu.Unlock() return } - obs := Observation{Request: event.Request, Epoch: r.Epoch, RunnerID: resp.RunnerID, Credential: resp.HeartbeatSecret, PreviousCredential: lineage, Sequence: event.Request.Seq, Accepted: event.AcceptedSeq != nil, Bootstrap: event.Credential == o.bootstrap, At: event.At.UTC(), TTL: event.TTL, Apps: resp.Apps} + obs := Observation{Request: event.Request, RunnerID: resp.RunnerID, Credential: resp.HeartbeatSecret, PreviousCredential: lineage, Sequence: event.Request.Seq, Accepted: event.AcceptedSeq != nil, Bootstrap: event.Credential == o.bootstrap, At: event.At.UTC(), TTL: event.TTL, Apps: resp.Apps} if obs.Credential == "" { obs.Credential = event.Credential } @@ -300,7 +299,7 @@ func (o *SDKOwner) heartbeat(event runner.HeartbeatEvent) { } o.accepted = Identity{RunnerID: resp.RunnerID, Credential: obs.Credential, Confirmed: obs.Accepted && !obs.Bootstrap, Sequence: event.AcceptedSeq} if time.Now().Before(o.rejectedUntil) && len(obs.Entries) < len(o.request.Entries) && h.Failure != nil { - h.Failure(OwnerFailure{Epoch: r.Epoch, Reason: o.rejectedReason, Partial: true}) + h.Failure(OwnerFailure{RunnerID: r.Identity.RunnerID, Reason: o.rejectedReason, Partial: true}) } _ = o.setAppsLocked() } diff --git a/runtime/appreconciler/owner_test.go b/runtime/appreconciler/owner_test.go index 36b730d..9e3e944 100644 --- a/runtime/appreconciler/owner_test.go +++ b/runtime/appreconciler/owner_test.go @@ -117,7 +117,7 @@ func nativeFixture(t *testing.T) (*SDKOwner, *nativeNode, OwnerRequest, OwnerHoo } t.Cleanup(func() { o.Close(context.Background()) }) e := Registration{InstanceID: "one", PodUID: "pod", Options: runner.AppOptions{App: "app", RunnerURL: "http://immutable.invalid:8080", Status: "not-ready", Mode: "persistent"}} - req := OwnerRequest{Epoch: "epoch", Identity: Identity{RunnerID: "owner"}, Entries: []Registration{e}, Tracked: []Registration{e}} + req := OwnerRequest{Identity: Identity{RunnerID: "owner"}, Entries: []Registration{e}, Tracked: []Registration{e}} events := make(chan Observation, 1024) hooks := OwnerHooks{Observe: func(o Observation) error { events <- o; return nil }} return o, n, req, hooks, events @@ -446,7 +446,7 @@ func TestNativeRestoredMembershipRejectionPreservesSibling(t *testing.T) { controller, _, _, _, _, _ := fixtureController(t) controller.Now = nil if err := controller.Journal.Update(func(s *State) error { - s.OwnerEpoch, s.Identity = r.Epoch, r.Identity + s.Identity.RunnerID, s.Identity = r.Identity.RunnerID, r.Identity s.Instances["one"] = &Instance{ID: "one", PodUID: "pod"} return nil }); err != nil { @@ -527,7 +527,7 @@ func TestNativeRestoredMembershipRejectionPreservesSibling(t *testing.T) { if err := restored.Close(t.Context()); err != nil { t.Fatal(err) } - controller.failed(OwnerFailure{Epoch: r.Epoch, Reason: "node_unavailable"}) + controller.failed(OwnerFailure{RunnerID: r.Identity.RunnerID, Reason: "node_unavailable"}) if len(controller.proofs) != 0 { t.Fatal("ordinary failure retained readiness proof") } diff --git a/runtime/appreconciler/report.go b/runtime/appreconciler/report.go index 67dd84c..ad4791a 100644 --- a/runtime/appreconciler/report.go +++ b/runtime/appreconciler/report.go @@ -16,7 +16,7 @@ type Report struct { ReportVersion int `json:"report_version,omitempty"` ObservedAt time.Time `json:"observed_at,omitempty"` ClockUncertain bool `json:"clock_uncertain,omitempty"` - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Component string `json:"component"` Generation int64 `json:"generation"` @@ -46,7 +46,7 @@ func DiagnoseMetadata(ctx context.Context, m contract.Metadata, reporter Reporte if reason == "" { status = "ready" } - _ = reporter.Status(ctx, Report{ObservedAt: time.Now().UTC(), ClockUncertain: reason == "clock_uncertain", Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, Component: "app-reconciler", Generation: m.Generation, BundleFormat: contract.BundleFormat, Ready: reason == "", Reason: status, Apps: contract.AppStatus{Reason: reason, Instances: []contract.InstanceStatus{}}}) + _ = reporter.Status(ctx, Report{ObservedAt: time.Now().UTC(), ClockUncertain: reason == "clock_uncertain", NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, Component: "app-reconciler", Generation: m.Generation, BundleFormat: contract.BundleFormat, Ready: reason == "", Reason: status, Apps: contract.AppStatus{Reason: reason, Instances: []contract.InstanceStatus{}}}) } func (r ControlReporter) Status(ctx context.Context, value Report) error { @@ -54,7 +54,7 @@ func (r ControlReporter) Status(ctx context.Context, value Report) error { return err } func (r ControlReporter) Receipt(ctx context.Context, m contract.Metadata, value Receipt) error { - payload := map[string]any{"epoch": m.Epoch, "credential_version": m.CredentialVersion, "generation": value.Generation, "activation_generation": value.ActivationGeneration, "apps_digest": value.AppsDigest, "phase": value.Phase, "reason": value.Reason} + payload := map[string]any{"node_id": m.NodeID, "credential_version": m.CredentialVersion, "generation": value.Generation, "activation_generation": value.ActivationGeneration, "apps_digest": value.AppsDigest, "phase": value.Phase, "reason": value.Reason} _, _, err := r.Client.Request(ctx, "apps/"+value.RevisionID+"/status", payload, 16384) return err } @@ -161,7 +161,7 @@ func (c *Controller) report(ctx context.Context, ready map[string]bool, view Vie status.Instances = append(status.Instances, contract.InstanceStatus{RevisionID: i.Group.RevisionID, Generation: i.Generation, ActivationGeneration: i.Group.ActivationGeneration, InstanceID: id, PodUID: i.PodUID, AppID: i.AppID, Phase: i.Phase, Ready: ready[id] && i.WithdrawalID == "", Registered: registered, Capacity: i.Definition.Instances.CapacityPerInstance, Sessions: sessions, Reason: instanceReason(i, ready[id], now), Deadline: i.Deadline, Forced: i.Forced, RemovalPublishedAt: i.RemovalPublishedAt, TerminatedAt: i.TerminatedAt, RunnerID: s.Identity.RunnerID, WithdrawalID: i.WithdrawalID, DrainExpiredAt: i.DrainExpiredAt, RegistrationGone: i.RegistrationGone, NodeObservedAt: nodeAt, NodeExpiresAt: nodeExpiry, AcceptedSequence: sequencePointer(accepted, !nodeAt.IsZero()), StartupDeadline: i.CreatedAt.Add(timeout), Probe: probe, WorkloadReason: workload}) } status.InstancesOmitted = status.InstancesTotal - len(status.Instances) - report := Report{ReportVersion: 1, ClockUncertain: s.ClockUncertain, Epoch: s.Metadata.Epoch, CredentialVersion: s.Metadata.CredentialVersion, Component: "runner", Generation: s.Metadata.Generation, BundleFormat: contract.BundleFormat, Ready: fault == "", Reason: "ready", Apps: status} + report := Report{ReportVersion: 1, ClockUncertain: s.ClockUncertain, NodeID: s.Metadata.NodeID, CredentialVersion: s.Metadata.CredentialVersion, Component: "runner", Generation: s.Metadata.Generation, BundleFormat: contract.BundleFormat, Ready: fault == "", Reason: "ready", Apps: status} if fault != "" { report.Ready = false report.Reason = "failed" diff --git a/runtime/appreconciler/report_test.go b/runtime/appreconciler/report_test.go index 58c9c65..166754a 100644 --- a/runtime/appreconciler/report_test.go +++ b/runtime/appreconciler/report_test.go @@ -114,11 +114,10 @@ func TestRetainedHeartbeatCountsDoNotBecomeWithdrawalProof(t *testing.T) { c, _, _, _, r, now := fixtureController(t) c.Journal.Update(func(s *State) error { s.Identity = Identity{RunnerID: "owner", Credential: "issued", Confirmed: true} - s.OwnerEpoch = "epoch" s.Instances["retained"] = &Instance{ID: "retained", AppID: "app", PodUID: "uid", WithdrawalID: "withdrawal", Phase: "removed"} return nil }) - obs := Observation{RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, Sequence: 1, Epoch: "epoch", At: *now, TTL: time.Minute, Apps: []AppObservation{{ID: "app", Status: "draining", SessionIDs: []string{"work"}}}} + obs := Observation{RunnerID: "owner", Credential: "issued", PreviousCredential: "issued", Accepted: true, Sequence: 1, At: *now, TTL: time.Minute, Apps: []AppObservation{{ID: "app", Status: "draining", SessionIDs: []string{"work"}}}} if err := c.observe(obs); err != nil { t.Fatal(err) } diff --git a/runtime/appreconciler/rolling.go b/runtime/appreconciler/rolling.go index 0a1bcaa..448ee7b 100644 --- a/runtime/appreconciler/rolling.go +++ b/runtime/appreconciler/rolling.go @@ -47,7 +47,7 @@ func retainRolling(s *State, i *Instance, c *Controller, now time.Time) bool { c.mu.Lock() p, ok := c.proofs[other.ID] c.mu.Unlock() - if other.WithdrawalID != "" || other.Reason == "process_lost" || other.Reason == "unexpected_pod_replacement" || !ok || p.PodUID != other.PodUID || p.Observation.Epoch != s.OwnerEpoch || p.Observation.Credential != s.Identity.Credential || p.Observation.At.After(now.Add(time.Second)) || p.App.Status != "ready" || !now.Before(p.Observation.At.Add(p.Observation.TTL)) || c.Probes == nil || !c.Probes.Ready(other.ID, other.PodUID) { + if other.WithdrawalID != "" || other.Reason == "process_lost" || other.Reason == "unexpected_pod_replacement" || !ok || p.PodUID != other.PodUID || p.Observation.RunnerID != s.Identity.RunnerID || p.Observation.Credential != s.Identity.Credential || p.Observation.At.After(now.Add(time.Second)) || p.App.Status != "ready" || !now.Before(p.Observation.At.Add(p.Observation.TTL)) || c.Probes == nil || !c.Probes.Ready(other.ID, other.PodUID) { blocked = true } } diff --git a/runtime/appreconciler/rolling_test.go b/runtime/appreconciler/rolling_test.go index edcc503..c21b93a 100644 --- a/runtime/appreconciler/rolling_test.go +++ b/runtime/appreconciler/rolling_test.go @@ -154,7 +154,7 @@ func TestRollingUsesCurrentSuccessorStateBeforeWithdrawal(t *testing.T) { } s := c.Journal.View() c.Probes.values[successor.ID] = &health{uid: successor.PodUID, ready: true, started: true, next: now.Add(time.Minute)} - c.proofs[successor.ID] = proof{PodUID: successor.PodUID, Observation: Observation{Epoch: s.OwnerEpoch, Credential: s.Identity.Credential, Accepted: true, At: *now, TTL: time.Minute}, App: AppObservation{ID: successor.AppID, Status: "ready", SessionIDs: []string{}}} + c.proofs[successor.ID] = proof{PodUID: successor.PodUID, Observation: Observation{RunnerID: s.Identity.RunnerID, Credential: s.Identity.Credential, Accepted: true, At: *now, TTL: time.Minute}, App: AppObservation{ID: successor.AppID, Status: "ready", SessionIDs: []string{}}} if failure == "process" { pod := k.view.Pods[successor.Name] pod.Phase = "Failed" diff --git a/runtime/appreconciler/state.go b/runtime/appreconciler/state.go index 72373f2..8e269dc 100644 --- a/runtime/appreconciler/state.go +++ b/runtime/appreconciler/state.go @@ -95,7 +95,6 @@ type State struct { Instances map[string]*Instance `json:"instances"` Heads map[string]string `json:"heads"` Identity Identity `json:"identity"` - OwnerEpoch string `json:"owner_epoch"` ReportSequence uint64 `json:"report_sequence"` MaintenanceID string `json:"maintenance_id,omitempty"` MaintenanceWithdrawal string `json:"maintenance_withdrawal,omitempty"` diff --git a/runtime/appreconciler/state_test.go b/runtime/appreconciler/state_test.go index 4a37578..1002c6b 100644 --- a/runtime/appreconciler/state_test.go +++ b/runtime/appreconciler/state_test.go @@ -20,7 +20,6 @@ func TestJournalRecoversLatestCommittedIdentity(t *testing.T) { } deadline := time.Now().UTC().Truncate(time.Second) if err = j.Update(func(s *State) error { - s.OwnerEpoch = "epoch" s.Identity = Identity{RunnerID: "runner", Credential: "private"} s.Instances["one"] = &Instance{ID: "one", Phase: "draining", Deadline: deadline, WithdrawalID: "withdrawal", RegistrationGone: true} return nil @@ -98,7 +97,7 @@ func TestHistoryCollectionPinsPendingReceiptsAndPublications(t *testing.T) { func TestJournalRecoveryRequiresTheLatestFence(t *testing.T) { dir := t.TempDir() j, _ := OpenJournal(dir) - j.Update(func(s *State) error { s.OwnerEpoch = "ready"; return nil }) + j.Update(func(s *State) error { s.Identity.RunnerID = "ready"; return nil }) old, err := os.ReadFile(filepath.Join(dir, "checkpoint")) if err != nil { t.Fatal(err) diff --git a/runtime/bootstrap-livepeer.sh b/runtime/bootstrap-livepeer.sh index 5cebd39..0ce83b2 100755 --- a/runtime/bootstrap-livepeer.sh +++ b/runtime/bootstrap-livepeer.sh @@ -77,7 +77,7 @@ parse_args() { # Reruns reuse the saved machine credential and never require another JWT. authenticate_node() { local credentials="$INSTALL_DIR/credentials" key fingerprint request response api status - NODE_ID=''; SERVICE_TOKEN=''; CONFIG_URL=''; ENROLLMENT_EPOCH=''; CREDENTIAL_VERSION=0 + NODE_ID=''; SERVICE_TOKEN=''; CONFIG_URL=''; IDENTITY_NODE_ID=''; CREDENTIAL_VERSION=0 if [[ -f "$INSTALL_DIR/state/enrolled" ]] || { managed_installation && [[ -f "$credentials/node-id" && -f "$credentials/service-token" && -f "$credentials/config-url" && -f "$credentials/identity.json" ]]; }; then for key in node-id service-token config-url; do [[ -f "$credentials/$key" && -s "$credentials/$key" ]] || die "saved credential is missing or invalid: $key; restore it from backup" @@ -125,9 +125,10 @@ authenticate_node() { if [[ ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} != 1 ]]; then [[ "$CONFIG_URL" == "$api/v1/nodes/$NODE_ID/config" ]] || die 'enrollment returned invalid HTTPS configuration URL' fi - [[ "$NODE_ID" == "lp-${fingerprint:0:16}" ]] || die 'enrollment returned an unexpected node identity' + printf '%s' "$fingerprint" | atomic_write "$credentials/fingerprint" fi - [[ "$NODE_ID" =~ ^lp-[a-f0-9]{16}$ && "$SERVICE_TOKEN" =~ ^[a-f0-9]{64}$ ]] || die 'invalid enrollment credentials' + [[ "$IDENTITY_NODE_ID" == "$NODE_ID" ]] || die 'saved identity does not match the node' + [[ "$NODE_ID" =~ ^[a-z2-7]{26}$ && "$SERVICE_TOKEN" =~ ^[a-f0-9]{64}$ ]] || die 'invalid enrollment credentials' [[ "$CONFIG_URL" =~ ^https?://[a-zA-Z0-9/_.:-]+$ ]] || die 'invalid configuration URL' [[ "$CONFIG_URL" == https://* || ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} == 1 ]] || die 'saved HTTP credential requires --refresh-credentials over HTTPS' [[ ! "${CONFIG_URL,,}" =~ ^https?://(localhost\.?|127\.[0-9.]+)(:[0-9]+)?(/|$) ]] || diff --git a/runtime/cmd/livepeer-runtime/main.go b/runtime/cmd/livepeer-runtime/main.go index 178c345..88c71bf 100644 --- a/runtime/cmd/livepeer-runtime/main.go +++ b/runtime/cmd/livepeer-runtime/main.go @@ -200,7 +200,7 @@ func appReconciler(ctx context.Context, args []string) error { } if reason != lastDiagnosis || !time.Now().Before(nextDiagnosis) { m := journal.View().Metadata - if m.Epoch != "" { + if m.NodeID != "" { appreconciler.DiagnoseMetadata(ctx, m, controller.Reporter, reason) } else { appreconciler.Diagnose(ctx, controller.Input, controller.Reporter, reason) diff --git a/runtime/connector/integration.go b/runtime/connector/integration.go index b889732..74a96c8 100644 --- a/runtime/connector/integration.go +++ b/runtime/connector/integration.go @@ -37,7 +37,7 @@ type Launch struct { // Association is safe to persist; it contains no connector or machine credential. type Association struct { Launch - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` TunnelID string `json:"tunnel_id"` TokenGeneration int64 `json:"credential_generation"` @@ -72,7 +72,7 @@ type Integration struct { func (i *Integration) Restore() { b, err := os.ReadFile(i.StateFile) var grant Association - if err == nil && len(b) <= 16384 && transport.Decode(b, &grant) == nil && validLaunch(grant.Launch) && grant.Epoch != "" && grant.TokenGeneration > 0 { + if err == nil && len(b) <= 16384 && transport.Decode(b, &grant) == nil && validLaunch(grant.Launch) && grant.NodeID != "" && grant.TokenGeneration > 0 { i.mu.Lock() i.grant = &grant i.observation = nil @@ -136,7 +136,7 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func matches(a Association, m contract.Metadata) bool { - return !m.TerminalCleanup && a.Epoch == m.Epoch && a.CredentialVersion == m.CredentialVersion && a.TunnelID != "" && a.TunnelID == m.TunnelID && a.TokenGeneration > 0 && a.TokenGeneration == m.TokenGeneration + return !m.TerminalCleanup && a.NodeID == m.NodeID && a.CredentialVersion == m.CredentialVersion && a.TunnelID != "" && a.TunnelID == m.TunnelID && a.TokenGeneration > 0 && a.TokenGeneration == m.TokenGeneration } func (i *Integration) fetch(ctx context.Context, launch Launch) (Grant, error) { @@ -175,14 +175,14 @@ func (i *Integration) fetch(ctx context.Context, launch Launch) (Grant, error) { } var response struct { Token string `json:"token"` - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` TunnelID string `json:"tunnel_id"` TokenGeneration int64 `json:"credential_generation"` } - if transport.Decode(b, &response) != nil || !validToken(response.Token) || response.Epoch != m.Epoch || response.TunnelID != m.TunnelID || response.TokenGeneration != m.TokenGeneration { + if transport.Decode(b, &response) != nil || !validToken(response.Token) || response.NodeID != m.NodeID || response.TunnelID != m.TunnelID || response.TokenGeneration != m.TokenGeneration { return Grant{}, errors.New("stale_connector_grant") } - a := Association{Launch: launch, Epoch: m.Epoch, CredentialVersion: m.CredentialVersion, TunnelID: m.TunnelID, TokenGeneration: m.TokenGeneration} + a := Association{Launch: launch, NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, TunnelID: m.TunnelID, TokenGeneration: m.TokenGeneration} if i.checkPod(ctx, launch) != nil { return Grant{}, errors.New("connector_changed_during_fetch") } @@ -271,6 +271,6 @@ func (i *Integration) Report(ctx context.Context) error { if reporter == nil { reporter = i.Control } - _, _, err := reporter.Request(ctx, "status", map[string]any{"epoch": m.Epoch, "credential_version": m.CredentialVersion, "component": "connector", "generation": m.Generation, "token_generation": tokenGeneration, "provider_version": providerVersion, "ready": ready, "https": strings.HasPrefix(i.Control.ConfigURL, "https://"), "reason": reason, "observed_at": time.Now().UTC(), "connector_observed_at": observedAt, "connector_expires_at": observedAt.Add(observationTTL)}, 16384) + _, _, err := reporter.Request(ctx, "status", map[string]any{"node_id": m.NodeID, "credential_version": m.CredentialVersion, "component": "connector", "generation": m.Generation, "token_generation": tokenGeneration, "provider_version": providerVersion, "ready": ready, "https": strings.HasPrefix(i.Control.ConfigURL, "https://"), "reason": reason, "observed_at": time.Now().UTC(), "connector_observed_at": observedAt, "connector_expires_at": observedAt.Add(observationTTL)}, 16384) return err } diff --git a/runtime/connector/integration_test.go b/runtime/connector/integration_test.go index 0e4f5a4..fd669d5 100644 --- a/runtime/connector/integration_test.go +++ b/runtime/connector/integration_test.go @@ -148,7 +148,7 @@ type integrationFixture struct { func fixture(t *testing.T) *integrationFixture { t.Helper() - f := &integrationFixture{pod: &podFixture{container: "containerd://first"}, m: contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "epoch", CredentialVersion: 1, Generation: 7, BundleFormat: contract.BundleFormat, TunnelID: "tunnel", TokenGeneration: 2, ProviderVersion: 10, ConnectorTokenRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/tunnel/connector-token"}} + f := &integrationFixture{pod: &podFixture{container: "containerd://first"}, m: contract.Metadata{NodeID: "vkvkvkvkvkvkuaaaaaaaaaaaaa", CredentialVersion: 1, Generation: 7, BundleFormat: contract.BundleFormat, TunnelID: "tunnel", TokenGeneration: 2, ProviderVersion: 10, ConnectorTokenRef: "/v1/nodes/vkvkvkvkvkvkuaaaaaaaaaaaaa/tunnel/connector-token"}} server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer "+strings.Repeat("b", 64) { t.Error("wrong machine credential") @@ -159,7 +159,7 @@ func fixture(t *testing.T) *integrationFixture { if f.mutate != nil { f.mutate() } - json.NewEncoder(w).Encode(map[string]any{"token": strings.Repeat("x", 63) + string(rune('a'+f.fetched)), "epoch": old.Epoch, "tunnel_id": old.TunnelID, "credential_generation": old.TokenGeneration}) + json.NewEncoder(w).Encode(map[string]any{"token": strings.Repeat("x", 63) + string(rune('a'+f.fetched)), "node_id": old.NodeID, "tunnel_id": old.TunnelID, "credential_generation": old.TokenGeneration}) return } var report map[string]any @@ -266,13 +266,13 @@ func TestGrantAssociationSurvivesAgentRestartButRequiresFreshEvidence(t *testing } func TestGrantFetchFencesConcurrentSecurityAndProcessChanges(t *testing.T) { - for _, change := range []string{"epoch", "generation", "credential", "terminal_cleanup"} { + for _, change := range []string{"node_id", "generation", "credential", "terminal_cleanup"} { t.Run(change, func(t *testing.T) { f := fixture(t) f.mutate = func() { switch change { - case "epoch": - f.m.Epoch = "new-epoch" + case "node_id": + f.m.NodeID = "new-node" case "generation": f.m.TokenGeneration++ case "credential": diff --git a/runtime/contract/contract.go b/runtime/contract/contract.go index 46371ef..49e3ca0 100644 --- a/runtime/contract/contract.go +++ b/runtime/contract/contract.go @@ -13,7 +13,6 @@ type Metadata struct { OnchainCredentialsRef string `json:"onchain_credentials_ref,omitempty"` OnchainActive bool `json:"onchain_active"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` CredentialVersion int64 `json:"credential_version"` Generation int64 `json:"generation"` Terminal bool `json:"terminal"` diff --git a/runtime/httpsource/component.go b/runtime/httpsource/component.go index 2b0e8f9..33c9eb1 100644 --- a/runtime/httpsource/component.go +++ b/runtime/httpsource/component.go @@ -17,18 +17,18 @@ func (s *Source) componentUnchanged(name, previous, current string) bool { if prefix == "" { return false } - read := func(digest string) ([]byte, string, string, error) { + read := func(digest string) ([]byte, string, error) { data, err := s.Store.Get(digest) if err != nil { - return nil, "", "", err + return nil, "", err } files, err := artifact.Read(data) if err != nil { - return nil, "", "", err + return nil, "", err } m, err := transport.ReadMetadata(files["runtime.json"]) if err != nil { - return nil, "", "", err + return nil, "", err } selected := map[string][]byte{} for path, b := range files { @@ -37,12 +37,12 @@ func (s *Source) componentUnchanged(name, previous, current string) bool { } } if len(selected) == 0 { - return nil, "", "", errors.New("component_input_missing") + return nil, "", errors.New("component_input_missing") } b, err := json.Marshal(selected) - return b, m.NodeID, m.Epoch, err + return b, m.NodeID, err } - a, an, ae, errA := read(previous) - b, bn, be, errB := read(current) - return errA == nil && errB == nil && an == bn && ae == be && bytes.Equal(a, b) + a, an, errA := read(previous) + b, bn, errB := read(current) + return errA == nil && errB == nil && an == bn && bytes.Equal(a, b) } diff --git a/runtime/httpsource/source.go b/runtime/httpsource/source.go index 045f7d2..da9c5f1 100644 --- a/runtime/httpsource/source.go +++ b/runtime/httpsource/source.go @@ -63,7 +63,7 @@ func (s *Source) Desired() (contract.Metadata, bool) { func (s *Source) installed(m contract.Metadata) bool { i, err := transport.ReadIdentity(s.IdentityFile) - return err == nil && i.Epoch == m.Epoch && i.CredentialVersion == m.CredentialVersion + return err == nil && i.NodeID == m.NodeID && i.CredentialVersion == m.CredentialVersion } // Report runs independently of downloads, credential requests and consumer observations. @@ -98,14 +98,14 @@ func (s *Source) sync(ctx context.Context) error { if err != nil { return err } - if m.NodeID != s.Control.NodeID || m.Epoch != headers.Get("X-Livepeer-Epoch") || headers.Get("X-Livepeer-Credential-Version") != formatInt(m.CredentialVersion) { + if m.NodeID != s.Control.NodeID || m.NodeID != headers.Get("X-Livepeer-Node-ID") || headers.Get("X-Livepeer-Credential-Version") != formatInt(m.CredentialVersion) { return errors.New("enrollment_mismatch") } i, err := transport.ReadIdentity(s.IdentityFile) if err != nil { return err } - if i.Epoch != m.Epoch || i.CredentialVersion != m.CredentialVersion { + if i.NodeID != m.NodeID || i.CredentialVersion != m.CredentialVersion { return errors.New("installed_identity_mismatch") } if err = os.MkdirAll(s.Store.Directory, 0700); err != nil { @@ -119,7 +119,7 @@ func (s *Source) sync(ctx context.Context) error { return errors.New("cache_identity_corrupt") } previous = &old - if old.Epoch != m.Epoch || (old.Terminal && !m.Terminal) || (!m.Terminal && old.Generation > m.Generation) { + if old.NodeID != m.NodeID || (old.Terminal && !m.Terminal) || (!m.Terminal && old.Generation > m.Generation) { return errors.New("stale_enrollment") } } else if !os.IsNotExist(err) { @@ -141,7 +141,7 @@ func (s *Source) sync(ctx context.Context) error { } } final, e := transport.ReadMetadata(cleanup["runtime.json"]) - if e != nil || !final.Terminal || !final.TerminalCleanup || final.NodeID != m.NodeID || final.Epoch != m.Epoch || final.Generation != m.Generation || final.CredentialVersion != m.CredentialVersion || final.AppsDigest != m.AppsDigest || final.AppsGeneration != m.AppsGeneration { + if e != nil || !final.Terminal || !final.TerminalCleanup || final.NodeID != m.NodeID || final.Generation != m.Generation || final.CredentialVersion != m.CredentialVersion || final.AppsDigest != m.AppsDigest || final.AppsGeneration != m.AppsGeneration { return errors.New("terminal_cleanup_payload") } data, err = artifact.Pack(cleanup) @@ -185,10 +185,10 @@ func (s *Source) sync(ctx context.Context) error { if appErr == nil { d.Downloaded = &contract.StageIdentity{Generation: m.AppsGeneration, AppsDigest: m.AppsDigest, ArtifactDigest: inputDigest} d.DownloadedAt = time.Now().UTC() - if prior := s.reporting.Load(); prior != nil && prior.Metadata.Epoch == m.Epoch && prior.Downloaded != nil && *prior.Downloaded == *d.Downloaded { + if prior := s.reporting.Load(); prior != nil && prior.Metadata.NodeID == m.NodeID && prior.Downloaded != nil && *prior.Downloaded == *d.Downloaded { d.DownloadedAt = prior.DownloadedAt } - } else if prior := s.reporting.Load(); prior != nil && prior.Metadata.Epoch == m.Epoch { + } else if prior := s.reporting.Load(); prior != nil && prior.Metadata.NodeID == m.NodeID { d.Downloaded, d.DownloadedAt = prior.Downloaded, prior.DownloadedAt } s.reporting.Store(d) @@ -278,7 +278,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr if m.TerminalInputDigest != "" { ack = m.TerminalInputDigest } - _, _, err = s.Control.Request(ctx, "removal-ack", map[string]any{"epoch": m.Epoch, "digest": strings.TrimPrefix(ack, "sha256:"), "connector_absent": true}, 16384) + _, _, err = s.Control.Request(ctx, "removal-ack", map[string]any{"node_id": m.NodeID, "digest": strings.TrimPrefix(ack, "sha256:"), "connector_absent": true}, 16384) return err } return nil @@ -394,7 +394,7 @@ func (s *Source) report(ctx context.Context, m contract.Metadata, digest, appErr if reporter == nil { reporter = s.Control } - payload := map[string]any{"epoch": m.Epoch, "credential_version": m.CredentialVersion, "component": "runtime", "generation": m.Generation, + payload := map[string]any{"node_id": m.NodeID, "credential_version": m.CredentialVersion, "component": "runtime", "generation": m.Generation, "bundle_sha256": strings.TrimPrefix(revision, "sha256:"), "config_digest": actual, "k3s_version": k3sVersion, "ready": ready, "https": strings.HasPrefix(s.Control.ConfigURL, "https://"), "reason": reason, "bundle_format": contract.BundleFormat, "apps_error": appErrorReason(appError), "observed_at": time.Now().UTC()} if s.Onchain != nil { payload["onchain"] = s.Onchain(ctx, m, applied && actual == m.ConfigDigest && podUID != "", ready, podUID) diff --git a/runtime/httpsource/source_test.go b/runtime/httpsource/source_test.go index ce9d626..e428e7d 100644 --- a/runtime/httpsource/source_test.go +++ b/runtime/httpsource/source_test.go @@ -201,7 +201,7 @@ type sourceFixture struct { func newFixture(t *testing.T) *sourceFixture { t.Helper() set := testutil.Assignment(t) - f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, Epoch: set.Epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} + f := &sourceFixture{status: 200, kube: &fakeKube{}, meta: contract.Metadata{Onchain: onchain.Offchain(), NodeID: set.NodeID, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat, ConfigDigest: strings.Repeat("a", 64), ServiceURL: "https://machine.example"}} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() @@ -212,7 +212,7 @@ func newFixture(t *testing.T) *sourceFixture { if f.cleanupReady { w.Header().Set("X-Livepeer-App-Cleanup-Ready", "true") } - w.Header().Set("X-Livepeer-Epoch", f.meta.Epoch) + w.Header().Set("X-Livepeer-Node-ID", f.meta.NodeID) w.Header().Set("X-Livepeer-Credential-Version", "1") w.WriteHeader(f.status) w.Write(f.data) @@ -230,7 +230,7 @@ func newFixture(t *testing.T) *sourceFixture { token := filepath.Join(root, "token") os.WriteFile(token, []byte(strings.Repeat("b", 64)), 0600) identity := filepath.Join(root, "identity") - b, _ := json.Marshal(map[string]any{"epoch": set.Epoch, "credential_version": 1}) + b, _ := json.Marshal(map[string]any{"node_id": set.NodeID, "credential_version": 1}) os.WriteFile(identity, b, 0600) control, err := transport.NewControl(server.URL+"/v1/nodes/"+set.NodeID+"/config", token, true) if err != nil { @@ -483,16 +483,16 @@ func TestAppOnlyApplicationReportsActualAppliedArchive(t *testing.T) { func TestComponentComparisonCannotBorrowCrossEnrollmentOrCorruptEvidence(t *testing.T) { s := &Source{Store: artifact.Store{Directory: t.TempDir()}} - cache := func(epoch, node, connector string) string { - m := contract.Metadata{Onchain: onchain.Offchain(), NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: epoch, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} + cache := func(nodeID, node, connector string) string { + m := contract.Metadata{Onchain: onchain.Offchain(), NodeID: nodeID, CredentialVersion: 1, Generation: 1, BundleFormat: contract.BundleFormat} return cacheBundle(t, s.Store, m, map[string][]byte{"system/node/kustomization.yaml": []byte(node), "system/connector/kustomization.yaml": []byte(connector)}) } - old := cache("11111111-1111-4111-8111-111111111111", "same node", "old connector") - current := cache("11111111-1111-4111-8111-111111111111", "same node", "broken connector") + old := cache(strings.Repeat("a", 26), "same node", "old connector") + current := cache(strings.Repeat("a", 26), "same node", "broken connector") if !s.componentUnchanged("livepeer-node", old, current) || s.componentUnchanged("livepeer-connector", old, current) { t.Fatal("component evidence coupled") } - if s.componentUnchanged("livepeer-node", old, cache("22222222-2222-4222-8222-222222222222", "same node", "old connector")) { + if s.componentUnchanged("livepeer-node", old, cache(strings.Repeat("b", 26), "same node", "old connector")) { t.Fatal("borrowed old enrollment proof") } os.WriteFile(filepath.Join(s.Store.Directory, old[7:]+".tar.gz"), []byte("corrupt"), 0600) diff --git a/runtime/internal/testutil/assignment.go b/runtime/internal/testutil/assignment.go index 312c294..20f28b8 100644 --- a/runtime/internal/testutil/assignment.go +++ b/runtime/internal/testutil/assignment.go @@ -27,7 +27,7 @@ func Assignment(t testing.TB) schema.AppAssignmentSetV1 { a.RevisionID = "11111111-1111-4111-8111-111111111111" a.Revision = &schema.ResolvedRevision{RevisionRef: a.RevisionRef, Name: d.Name, AppVersion: d.AppVersion, Revision: 1, SchemaVersion: 1, CanonicalFormat: schema.CanonicalFormat, Definition: d} Refresh(&a) - return schema.AppAssignmentSetV1{SchemaVersion: 1, NodeID: "lp-" + strings.Repeat("a", 16), Epoch: "22222222-2222-4222-8222-222222222222", Generation: 1, Entries: []schema.AppAssignment{a}} + return schema.AppAssignmentSetV1{SchemaVersion: 1, NodeID: strings.Repeat("a", 26), Generation: 1, Entries: []schema.AppAssignment{a}} } func Refresh(a *schema.AppAssignment) { b, err := schema.CanonicalBytes(a.Revision.Definition) diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index c357e45..3f93656 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -30,14 +30,14 @@ verify_retired_apps() { read_identity() { local identity="$1" - ENROLLMENT_EPOCH=$(jq -er '.epoch | select(type == "string")' <<< "$identity") || return 1 + IDENTITY_NODE_ID=$(jq -er '.node_id | select(type == "string")' <<< "$identity") || return 1 CREDENTIAL_VERSION=$(jq -er '.credential_version | select(type == "number" and . >= 1 and . == floor)' <<< "$identity") || return 1 - [[ "$ENROLLMENT_EPOCH" =~ ^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$ && "$CREDENTIAL_VERSION" =~ ^[1-9][0-9]*$ ]] + [[ "$IDENTITY_NODE_ID" =~ ^[a-z2-7]{26}$ && "$CREDENTIAL_VERSION" =~ ^[1-9][0-9]*$ ]] } save_identity() { local identity - identity=$(jq -nc --arg epoch "$ENROLLMENT_EPOCH" --argjson version "$CREDENTIAL_VERSION" '{epoch:$epoch,credential_version:$version}') + identity=$(jq -nc --arg node_id "$IDENTITY_NODE_ID" --argjson version "$CREDENTIAL_VERSION" '{node_id:$node_id,credential_version:$version}') if [[ -f "$INSTALL_DIR/credentials/identity.json" && $(cat "$INSTALL_DIR/credentials/identity.json") == "$identity" ]]; then return; fi printf '%s\n' "$identity" | atomic_write "$INSTALL_DIR/credentials/identity.json" } @@ -85,7 +85,7 @@ stop_credential_consumers() { } transition_credentials() { - local api fingerprint operation expected response status request metadata previous_epoch issued_epoch apps replicas + local api fingerprint operation expected response status request metadata previous_node issued_node apps replicas managed_installation || die 'credential transition requires an initialized installation' [[ -s "$INSTALL_DIR/credentials/runner-bootstrap.secret" ]] || die 'restore the runner bootstrap credential before changing credentials' runtime_image @@ -94,9 +94,9 @@ transition_credentials() { api=${LIVEPEER_API_URL:-}; api=${api%/} [[ "$api" =~ ^https://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'set LIVEPEER_API_URL to the verified HTTPS API' NODE_ID=$(cat "$INSTALL_DIR/credentials/node-id") - [[ "$NODE_ID" =~ ^lp-[a-f0-9]{16}$ ]] || die 'invalid saved machine ID' + [[ "$NODE_ID" =~ ^[a-z2-7]{26}$ ]] || die 'invalid saved machine ID' fingerprint=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum); fingerprint=${fingerprint:0:64} - [[ "$NODE_ID" == "lp-${fingerprint:0:16}" ]] || die 'installation fingerprint changed' + [[ $(cat "$INSTALL_DIR/credentials/fingerprint") == "$fingerprint" ]] || die 'installation fingerprint changed' if [[ -f "$INSTALL_DIR/state/credential-transition.json" ]]; then metadata=$(cat "$INSTALL_DIR/state/credential-transition.json") [[ $(jq -r '.mode' <<< "$metadata") == "$CREDENTIAL_TRANSITION" ]] || die 'resume the existing credential transition mode' @@ -107,13 +107,13 @@ transition_credentials() { [[ -s "$INSTALL_DIR/credentials/identity.json" ]] || die 'restore the enrollment identity before changing credentials' read_identity "$(cat "$INSTALL_DIR/credentials/identity.json")" || die 'invalid saved enrollment identity' expected=$CREDENTIAL_VERSION - previous_epoch=$ENROLLMENT_EPOCH - jq -nc --arg mode "$CREDENTIAL_TRANSITION" --arg api "$api" --arg operation "$operation" --argjson expected "$expected" --arg previous_epoch "$previous_epoch" \ - '{mode:$mode,api:$api,operation:$operation,expected:$expected,previous_epoch:$previous_epoch,cleanup_verified:($mode=="reenroll")}' | atomic_write "$INSTALL_DIR/state/credential-transition.json" + previous_node=$IDENTITY_NODE_ID + jq -nc --arg mode "$CREDENTIAL_TRANSITION" --arg api "$api" --arg operation "$operation" --argjson expected "$expected" --arg previous_node "$previous_node" \ + '{mode:$mode,api:$api,operation:$operation,expected:$expected,previous_node:$previous_node,cleanup_verified:($mode=="reenroll")}' | atomic_write "$INSTALL_DIR/state/credential-transition.json" metadata=$(cat "$INSTALL_DIR/state/credential-transition.json") fi - previous_epoch=$(jq -er '.previous_epoch' <<< "$metadata") - [[ "$previous_epoch" =~ ^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$ ]] || die 'invalid previous enrollment identity' + previous_node=$(jq -er '.previous_node' <<< "$metadata") + [[ "$previous_node" =~ ^[a-z2-7]{26}$ ]] || die 'invalid previous enrollment identity' jq -e '.expected | type == "number" and . >= 1' <<< "$metadata" >/dev/null || die 'invalid credential transition version' stop_credential_consumers install -d -m 0700 "$INSTALL_DIR/volumes/app-reconciler" @@ -127,7 +127,6 @@ transition_credentials() { CONFIG_URL="$api/v1/nodes/$NODE_ID/config" # Publish HTTPS-enforcing source files and settings before releasing credentials. # The Deployment remains scaled to zero until the complete new manifest applies. - stage_manifests if [[ "$CREDENTIAL_TRANSITION" == refresh ]]; then request=$(jq -nc --arg fingerprint "$fingerprint" --arg install_dir "$INSTALL_DIR" \ --arg operation_id "$(jq -r '.operation' <<< "$metadata")" --argjson expected "$(jq -r '.expected' <<< "$metadata")" \ @@ -146,32 +145,41 @@ transition_credentials() { fi status=${response##*$'\n'}; [[ "$status" == 200 ]] || die 'credential transition did not return HTTP 200; resume with the same operation' response=${response%$'\n'*} - [[ $(jq -r '.node_id' <<< "$response") == "$NODE_ID" ]] || die 'credential transition returned a different machine' + if [[ "$CREDENTIAL_TRANSITION" == refresh ]]; then + [[ $(jq -r '.node_id' <<< "$response") == "$NODE_ID" ]] || die 'credential refresh returned a different node' + else + NODE_ID=$(jq -er '.node_id | select(type == "string")' <<< "$response") + [[ "$NODE_ID" =~ ^[a-z2-7]{26}$ && "$NODE_ID" != "$previous_node" ]] || die 're-enrollment did not issue a fresh node' + CONFIG_URL="$api/v1/nodes/$NODE_ID/config" + fi [[ $(jq -r '.config_url' <<< "$response") == "$CONFIG_URL" ]] || die 'credential destination changed' SERVICE_TOKEN=$(jq -er '.token' <<< "$response") read_identity "$response" || die 'invalid refreshed machine identity' [[ "$SERVICE_TOKEN" =~ ^[a-f0-9]{64}$ ]] || die 'invalid refreshed machine credential' if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then - issued_epoch=$(jq -r '.issued_epoch // empty' "$INSTALL_DIR/state/credential-transition.json") - [[ -z "$issued_epoch" || "$issued_epoch" == "$ENROLLMENT_EPOCH" ]] || die 're-enrollment returned a different identity; restore the prior transition' - if [[ -z "$issued_epoch" ]]; then - jq --arg epoch "$ENROLLMENT_EPOCH" '. + {issued_epoch:$epoch}' "$INSTALL_DIR/state/credential-transition.json" | atomic_write "$INSTALL_DIR/state/credential-transition.json" + issued_node=$(jq -r '.issued_node // empty' "$INSTALL_DIR/state/credential-transition.json") + [[ -z "$issued_node" || "$issued_node" == "$IDENTITY_NODE_ID" ]] || die 're-enrollment returned a different identity; restore the prior transition' + if [[ -z "$issued_node" ]]; then + jq --arg node_id "$IDENTITY_NODE_ID" '. + {issued_node:$node_id}' "$INSTALL_DIR/state/credential-transition.json" | atomic_write "$INSTALL_DIR/state/credential-transition.json" fi fi printf '%s' "$SERVICE_TOKEN" | atomic_write "$INSTALL_DIR/credentials/service-token" printf '%s' "$CONFIG_URL" | atomic_write "$INSTALL_DIR/credentials/config-url" + [[ "$IDENTITY_NODE_ID" == "$NODE_ID" ]] || die 'credential identity does not match the node' + printf '%s' "$NODE_ID" | atomic_write "$INSTALL_DIR/credentials/node-id" save_identity + stage_manifests install_machine_secret if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then [[ $(jq -r '.cleanup_verified' <<< "$metadata") == true ]] || die 'prior app cleanup was not verified; restore the prior credential transition before re-enrolling' - if [[ ! -f "$INSTALL_DIR/volumes/app-reconciler/reenrolled-$ENROLLMENT_EPOCH" ]]; then + if [[ ! -f "$INSTALL_DIR/volumes/app-reconciler/reenrolled-$IDENTITY_NODE_ID" ]]; then if [[ -d "$INSTALL_DIR/volumes/app-reconciler/state" ]]; then - mv -- "$INSTALL_DIR/volumes/app-reconciler/state" "$INSTALL_DIR/volumes/app-reconciler/state.$previous_epoch" + mv -- "$INSTALL_DIR/volumes/app-reconciler/state" "$INSTALL_DIR/volumes/app-reconciler/state.$previous_node" sync -- "$INSTALL_DIR/volumes/app-reconciler" fi - printf '1\n' | atomic_write "$INSTALL_DIR/volumes/app-reconciler/reenrolled-$ENROLLMENT_EPOCH" + printf '1\n' | atomic_write "$INSTALL_DIR/volumes/app-reconciler/reenrolled-$IDENTITY_NODE_ID" fi - # Fence the previous epoch's cached artifact and watermark while Flux is suspended. + # Fence the retired node's cached artifact and watermark while Flux is suspended. rm -f -- "$INSTALL_DIR/volumes/http-source/enrollment.json" kube -n flux-system patch externalartifact livepeer-service --subresource=status --type merge -p '{"status":{"artifact":null,"conditions":[]}}' apps=$(kube -n flux-system get externalartifact livepeer-apps --ignore-not-found -o name) diff --git a/runtime/management/relay.go b/runtime/management/relay.go index ac3e299..4f1e210 100644 --- a/runtime/management/relay.go +++ b/runtime/management/relay.go @@ -34,12 +34,12 @@ func (a AppReports) ServeHTTP(w http.ResponseWriter, r *http.Request) { } b, err := io.ReadAll(io.LimitReader(r.Body, limit+1)) var identity struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Component string `json:"component"` } m, ok := a.Desired() - if err != nil || int64(len(b)) > limit || transport.Decode(b, &identity) != nil || !ok || identity.Epoch != m.Epoch || identity.CredentialVersion != m.CredentialVersion || (endpoint == "status" && identity.Component != "runner" && identity.Component != "app-reconciler") { + if err != nil || int64(len(b)) > limit || transport.Decode(b, &identity) != nil || !ok || identity.NodeID != m.NodeID || identity.CredentialVersion != m.CredentialVersion || (endpoint == "status" && identity.Component != "runner" && identity.Component != "app-reconciler") { http.Error(w, "report refused", http.StatusForbidden) return } diff --git a/runtime/management/sockets_test.go b/runtime/management/sockets_test.go index 28f6da8..bce896b 100644 --- a/runtime/management/sockets_test.go +++ b/runtime/management/sockets_test.go @@ -30,7 +30,7 @@ func TestScopedSocketsAndEnrollmentFencedAppReporting(t *testing.T) { if err != nil { t.Fatal(err) } - m := contract.Metadata{Epoch: "epoch", CredentialVersion: 1} + m := contract.Metadata{NodeID: "node_id", CredentialVersion: 1} control := &recorder{} apps := AppReports{Control: control, Desired: func() (contract.Metadata, bool) { return m, true }} connector := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -63,7 +63,7 @@ func TestScopedSocketsAndEnrollmentFencedAppReporting(t *testing.T) { } } client := transport.NewLocal(filepath.Join(root, "apps", "control.sock")) - payload := map[string]any{"epoch": "epoch", "credential_version": 1, "component": "runner", "generation": 1} + payload := map[string]any{"node_id": "node_id", "credential_version": 1, "component": "runner", "generation": 1} if _, _, err = client.Request(t.Context(), "status", payload, 1024); err != nil { t.Fatal(err) } @@ -80,11 +80,11 @@ func TestScopedSocketsAndEnrollmentFencedAppReporting(t *testing.T) { t.Fatal("app consumer impersonated connector") } payload["component"] = "runner" - payload["epoch"] = "old" + payload["node_id"] = "old" if _, _, err = client.Request(t.Context(), "status", payload, 1024); !transport.IsStatus(err, 403) { t.Fatal("cross-enrollment report passed") } - payload["epoch"] = "epoch" + payload["node_id"] = "node_id" payload["padding"] = strings.Repeat("x", contract.MaxStatusBytes) if _, _, err = client.Request(t.Context(), "status", payload, 1024); !transport.IsStatus(err, 403) { t.Fatal("oversized status crossed app socket", err) diff --git a/runtime/nodeproxy/proxy_test.go b/runtime/nodeproxy/proxy_test.go index 18dd77c..b5f3f4c 100644 --- a/runtime/nodeproxy/proxy_test.go +++ b/runtime/nodeproxy/proxy_test.go @@ -17,7 +17,7 @@ import ( "github.com/livepeer/control-center/runtime/contract" ) -const template = "https://{proxy}.lp-aaaaaaaaaaaaaaaa.example.invalid" +const template = "https://{proxy}.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid" func TestAuthorityAndCredentialBoundary(t *testing.T) { var forwarded *http.Request @@ -26,12 +26,12 @@ func TestAuthorityAndCredentialBoundary(t *testing.T) { t.Fatal(err) } for _, host := range []string{ - "app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid", "APP-VALID.lp-aaaaaaaaaaaaaaaa.example.invalid", + "app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "APP-VALID.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", strings.TrimPrefix(contract.PrivateOrchestrator, "http://"), - "api.lp-aaaaaaaaaaaaaaaa.example.invalid", "discovery.lp-aaaaaaaaaaaaaaaa.example.invalid", - "api-wrong.lp-aaaaaaaaaaaaaaaa.example.invalid:443", "discovery-wrong.lp-aaaaaaaaaaaaaaaa.example.invalid", - "app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid:443", "app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid.", - "nested.app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid", "-invalid.lp-aaaaaaaaaaaaaaaa.example.invalid", "foreign.invalid", + "api.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "discovery.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", + "api-wrong.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid:443", "discovery-wrong.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", + "app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid:443", "app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid.", + "nested.app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "-invalid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", "foreign.invalid", } { forwarded = nil req := httptest.NewRequest("GET", "https://"+host+"/apps/app/app/a%2Fb?value=1%202&value=3", nil) @@ -75,7 +75,7 @@ func TestApplicationCookiesRemainVerbatim(t *testing.T) { if err != nil { t.Fatal(err) } - req := httptest.NewRequest("GET", "https://app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid/", nil) + req := httptest.NewRequest("GET", "https://app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid/", nil) req.Header["Cookie"] = check.input handler.ServeHTTP(httptest.NewRecorder(), req) if !reflect.DeepEqual(received, check.want) || !reflect.DeepEqual(req.Header.Values("Cookie"), check.input) { @@ -91,10 +91,10 @@ func TestReverseProxyStreamingAndUpgrade(t *testing.T) { if r.Host != strings.TrimPrefix(contract.PrivateOrchestrator, "http://") { t.Error("identity check used public Host") } - _ = json.NewEncoder(w).Encode([]map[string]string{{"address": "https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid"}}) + _ = json.NewEncoder(w).Encode([]map[string]string{{"address": "https://api-aaaaaaa.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid"}}) return } - if r.Host != "app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid" { + if r.Host != "app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid" { t.Error("proxy Host was not preserved", r.Host) } switch r.URL.Path { @@ -128,7 +128,7 @@ func TestReverseProxyStreamingAndUpgrade(t *testing.T) { } })) defer upstream.Close() - transport := nodeTransport("https://api-aaaaaaa.lp-aaaaaaaaaaaaaaaa.example.invalid", func(ctx context.Context, network, address string) (net.Conn, error) { + transport := nodeTransport("https://api-aaaaaaa.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid", func(ctx context.Context, network, address string) (net.Conn, error) { if address != strings.TrimPrefix(contract.PrivateOrchestrator, "http://") { t.Error("unexpected upstream", address) } @@ -145,7 +145,7 @@ func TestReverseProxyStreamingAndUpgrade(t *testing.T) { request := func(path string) *http.Response { t.Helper() req, _ := http.NewRequest("GET", server.URL+path, nil) - req.Host = "app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid" + req.Host = "app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid" response, err := client.Do(req) if err != nil { t.Fatal(err) @@ -171,7 +171,7 @@ func TestReverseProxyStreamingAndUpgrade(t *testing.T) { } defer conn.Close() _ = conn.SetDeadline(time.Now().Add(3 * time.Second)) - _, _ = io.WriteString(conn, "GET /upgrade HTTP/1.1\r\nHost: app-valid.lp-aaaaaaaaaaaaaaaa.example.invalid\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") + _, _ = io.WriteString(conn, "GET /upgrade HTTP/1.1\r\nHost: app-valid.vkvkvkvkvkvkuaaaaaaaaaaaaa.example.invalid\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") reader := bufio.NewReader(conn) upgraded, err := http.ReadResponse(reader, &http.Request{Method: "GET"}) if err != nil || upgraded.StatusCode != 101 { diff --git a/runtime/orchestrator/integration.go b/runtime/orchestrator/integration.go index 0f02b6c..d1e3d9d 100644 --- a/runtime/orchestrator/integration.go +++ b/runtime/orchestrator/integration.go @@ -23,7 +23,7 @@ import ( type Launch = connector.Launch type Association struct { Launch - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` OnchainGeneration int64 `json:"onchain_generation"` ConfigDigest string `json:"config_digest"` @@ -108,7 +108,7 @@ func (i *Integration) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/onchain/observation" { var o ProcessObservation m, ok := i.Desired() - if transport.Decode(b, &o) != nil || !ok || m.TerminalCleanup || o.Epoch != m.Epoch || o.ConfigDigest != m.ConfigDigest || o.OnchainGeneration != m.Onchain.Generation || time.Since(o.ObservedAt) > 15*time.Second || o.ObservedAt.After(time.Now().Add(5*time.Second)) || i.checkPod(r.Context(), o.Launch, m) != nil { + if transport.Decode(b, &o) != nil || !ok || m.TerminalCleanup || o.NodeID != m.NodeID || o.ConfigDigest != m.ConfigDigest || o.OnchainGeneration != m.Onchain.Generation || time.Since(o.ObservedAt) > 15*time.Second || o.ObservedAt.After(time.Now().Add(5*time.Second)) || i.checkPod(r.Context(), o.Launch, m) != nil { http.Error(w, "observation refused", 409) return } @@ -160,7 +160,7 @@ func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { return Grant{}, bad } var g Grant - if transport.Decode(b, &g) != nil || g.Launch != l || g.Epoch != m.Epoch || g.CredentialVersion != m.CredentialVersion || g.OnchainGeneration != m.Onchain.Generation || g.ConfigDigest != m.ConfigDigest || g.GrantID == "" || g.RPCURL == "" || g.Headers == "" { + if transport.Decode(b, &g) != nil || g.Launch != l || g.NodeID != m.NodeID || g.CredentialVersion != m.CredentialVersion || g.OnchainGeneration != m.Onchain.Generation || g.ConfigDigest != m.ConfigDigest || g.GrantID == "" || g.RPCURL == "" || g.Headers == "" { return Grant{}, bad } if i.checkPod(ctx, l, m) != nil { @@ -169,7 +169,7 @@ func (i *Integration) fetch(ctx context.Context, l Launch) (Grant, error) { authorized := func() bool { after, e := os.ReadFile(i.TokenFile) n, ok := i.Desired() - return ctx.Err() == nil && e == nil && ok && n.Epoch == m.Epoch && n.CredentialVersion == m.CredentialVersion && n.Generation == m.Generation && n.ConfigDigest == m.ConfigDigest && n.Onchain.Generation == m.Onchain.Generation && sha256.Sum256(before) == sha256.Sum256(after) + return ctx.Err() == nil && e == nil && ok && n.NodeID == m.NodeID && n.CredentialVersion == m.CredentialVersion && n.Generation == m.Generation && n.ConfigDigest == m.ConfigDigest && n.Onchain.Generation == m.Onchain.Generation && sha256.Sum256(before) == sha256.Sum256(after) } i.mu.Lock() defer i.mu.Unlock() diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go index 098c476..f90ba1e 100644 --- a/runtime/orchestrator/integration_test.go +++ b/runtime/orchestrator/integration_test.go @@ -36,7 +36,7 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) dir := t.TempDir() token := filepath.Join(dir, "token") os.WriteFile(token, []byte("machine-secret"), 0600) - m := contract.Metadata{NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Onchain: onchain.Config{Mode: "onchain", Generation: 2}, OnchainCredentialsRef: "/v1/nodes/lp-aaaaaaaaaaaaaaaa/onchain/credentials"} + m := contract.Metadata{NodeID: "aaaaaaaaaaaaaaaaaaaaaaaaaa", CredentialVersion: 1, Generation: 5, ConfigDigest: strings.Repeat("a", 64), Onchain: onchain.Config{Mode: "onchain", Generation: 2}, OnchainCredentialsRef: "/v1/nodes/aaaaaaaaaaaaaaaaaaaaaaaaaa/onchain/credentials"} l := Launch{PodName: "orchestrator-test", PodUID: "uid", LaunchID: strings.Repeat("b", 32), ProcessID: strings.Repeat("c", 64)} i := &Integration{TokenFile: token, StateFile: filepath.Join(dir, "grant.json"), Desired: func() (contract.Metadata, bool) { return m, true }} i.Kube = kubeFunc(func(_ context.Context, _, p string, _ any, out any) error { @@ -50,7 +50,7 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) if p != "onchain/credentials" { t.Fatal(p) } - b, _ := json.Marshal(Grant{Association: Association{Launch: l, Epoch: m.Epoch, CredentialVersion: 1, OnchainGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) + b, _ := json.Marshal(Grant{Association: Association{Launch: l, CredentialVersion: 1, OnchainGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) return b, nil, nil }) return i, m, l diff --git a/runtime/orchestrator/observation.go b/runtime/orchestrator/observation.go index cda0470..0cba69f 100644 --- a/runtime/orchestrator/observation.go +++ b/runtime/orchestrator/observation.go @@ -22,7 +22,7 @@ func (i *Integration) Observe(ctx context.Context, m contract.Metadata, applied, a := i.grant proof := i.observation i.mu.Unlock() - if !applied || a == nil || proof == nil || proof.Association != *a || time.Since(proof.ObservedAt) > 30*time.Second || a.PodUID != podUID || a.Epoch != m.Epoch || a.OnchainGeneration != m.Onchain.Generation || a.ConfigDigest != m.ConfigDigest || i.checkPod(ctx, a.Launch, m) != nil { + if !applied || a == nil || proof == nil || proof.Association != *a || time.Since(proof.ObservedAt) > 30*time.Second || a.PodUID != podUID || a.NodeID != m.NodeID || a.OnchainGeneration != m.Onchain.Generation || a.ConfigDigest != m.ConfigDigest || i.checkPod(ctx, a.Launch, m) != nil { o.Applied = false o.Ready = false return o diff --git a/runtime/tests/test_bootstrap.py b/runtime/tests/test_bootstrap.py index 73c7027..9744ef3 100644 --- a/runtime/tests/test_bootstrap.py +++ b/runtime/tests/test_bootstrap.py @@ -144,7 +144,7 @@ def shell(self, commands, *args): curl() { local digest digest=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum) - printf '{"node_id":"lp-%s","token":"%s","config_url":"%s","epoch":"11111111-1111-4111-8111-111111111111","credential_version":1}' "${digest:0:16}" "${MOCK_SERVICE_TOKEN:-$(printf 'b%.0s' {1..64})}" "${MOCK_CONFIG_URL:-http://api.example/v1/nodes/lp-${digest:0:16}/config}" + printf '{"node_id":"aaaaaaaaaaaaaaaaaaaaaaaaaa","token":"%s","config_url":"%s","credential_version":1}' "${MOCK_SERVICE_TOKEN:-$(printf 'b%.0s' {1..64})}" "${MOCK_CONFIG_URL:-http://api.example/v1/nodes/aaaaaaaaaaaaaaaaaaaaaaaaaa/config}" printf '\\n200' } ''' @@ -237,7 +237,7 @@ def test_enrollment_and_prepare_preserve_secrets_without_python(self): for p in (target / 'credentials').iterdir()} result = self.shell(enroll, str(target)) self.assertEqual(result.returncode, 0, result.stderr) - self.assertRegex((target / 'credentials/node-id').read_text(), r'^lp-[a-f0-9]{16}$') + self.assertRegex((target / 'credentials/node-id').read_text(), r'^[a-z2-7]{26}$') self.assertRegex((target / 'credentials/service-token').read_text(), r'^[a-f0-9]{64}$') for path, original in saved.items(): self.assertEqual((path.read_bytes(), path.stat().st_ino, path.stat().st_mtime_ns), original) @@ -332,9 +332,9 @@ def do_POST(self): received['authorization'] = self.headers.get('Authorization') received['body'] = json.loads(self.rfile.read(int(self.headers['Content-Length']))) fingerprint = received['body']['fingerprint'] - response = {'node_id': 'lp-' + fingerprint[:16], 'token': 'c' * 64, - 'config_url': 'https://api.example/v1/nodes/lp-' + fingerprint[:16] + '/config', - 'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': 1} + response = {'node_id': 'a' * 26, 'token': 'c' * 64, + 'config_url': 'https://api.example/v1/nodes/' + 'a' * 26 + '/config', + 'credential_version': 1} self.send_response(200) self.end_headers() self.wfile.write(json.dumps(response).encode()) @@ -390,7 +390,7 @@ def log_message(self, *args): pass def do_POST(self): metadata = json.loads(self.rfile.read(int(self.headers['Content-Length']))) - node_id = 'lp-' + metadata['fingerprint'][:16] + node_id = 'a' * 26 self.send_response(307) self.send_header('Location', destination + '/capture') self.end_headers() diff --git a/runtime/tests/test_credentials.py b/runtime/tests/test_credentials.py index 1ec2165..53b76a6 100644 --- a/runtime/tests/test_credentials.py +++ b/runtime/tests/test_credentials.py @@ -18,14 +18,15 @@ def setUp(self): self.root = Path(self.temp.name) for name in ('credentials', 'state', 'volumes/http-source'): (self.root / name).mkdir(parents=True, exist_ok=True) - (self.root / 'credentials/node-id').write_text('lp-' + 'a' * 16) + (self.root / 'credentials/node-id').write_text('a' * 26) + (self.root / 'credentials/fingerprint').write_text('a' * 64) (self.root / 'credentials/service-token').write_text('b' * 64) (self.root / 'credentials/runner-bootstrap.secret').write_text('runner-bootstrap') - (self.root / 'credentials/config-url').write_text('https://control.example.invalid/v1/nodes/lp-' + 'a' * 16 + '/config') - (self.root / 'credentials/identity.json').write_text(json.dumps({'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': 1})) + (self.root / 'credentials/config-url').write_text('https://control.example.invalid/v1/nodes/' + 'a' * 26 + '/config') + (self.root / 'credentials/identity.json').write_text(json.dumps({'node_id': 'a' * 26, 'credential_version': 1})) (self.root / 'state/k3s-version').write_text('v1.37.10+k3s1') - def transition(self, fail='', mode='refresh', epoch='22222222-2222-4222-8222-222222222222'): + def transition(self, fail='', mode='refresh', node='c' * 26): script = r''' set -Eeuo pipefail source "$1" @@ -76,22 +77,22 @@ def transition(self, fail='', mode='refresh', epoch='22222222-2222-4222-8222-222 previous=$arg done [[ "$FAIL_AT" != request ]] || return 1 - printf '{"node_id":"lp-aaaaaaaaaaaaaaaa","token":"%s","epoch":"%s","credential_version":1,"config_url":"https://control.example.invalid/v1/nodes/lp-aaaaaaaaaaaaaaaa/config"}\n200' \ - cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc "$TEST_EPOCH" + printf '{"node_id":"%s","token":"%s","credential_version":1,"config_url":"%s/v1/nodes/%s/config"}\n200' \ + "$TEST_NODE" cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc https://control.example.invalid "$TEST_NODE" } transition_credentials ''' return subprocess.run(['bash', '-c', script, 'fixture', str(LIBRARY), str(self.root)], - env={**os.environ, 'FAIL_AT': fail, 'TEST_MODE': mode, 'TEST_EPOCH': epoch}, + env={**os.environ, 'FAIL_AT': fail, 'TEST_MODE': mode, 'TEST_NODE': ('a' * 26 if mode == 'refresh' else node)}, text=True, capture_output=True) - def test_identity_requires_uuid_and_positive_numeric_version(self): + def test_identity_requires_base32_node_and_positive_numeric_version(self): for identity, valid in [ - ({'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': 1}, True), - ({'epoch': 'a' * 36, 'credential_version': 1}, False), - ({'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': '1'}, False), - ({'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': 0}, False), - ({'epoch': '11111111-1111-4111-8111-111111111111', 'credential_version': 1.5}, False), + ({'node_id': 'a' * 26, 'credential_version': 1}, True), + ({'node_id': 'a' * 36, 'credential_version': 1}, False), + ({'node_id': 'a' * 26, 'credential_version': '1'}, False), + ({'node_id': 'a' * 26, 'credential_version': 0}, False), + ({'node_id': 'a' * 26, 'credential_version': 1.5}, False), ]: result = subprocess.run(['bash', '-c', 'source "$1"; read_identity "$2"', 'fixture', str(LIBRARY), json.dumps(identity)], capture_output=True) @@ -119,7 +120,7 @@ def test_interrupted_request_resumes_same_operation_after_consumers_stop(self): self.assertLess(writer_stop, writer_gone) self.assertLess(writer_gone, steps.index('refresh')) self.assertGreater(next(i for i, x in enumerate(steps) if 'scale deployment/kustomize-controller --replicas=1' in x), secret) - self.assertLess(steps.index('https-code'), steps.index('refresh')) + self.assertLess(steps.index('refresh'), steps.index('https-code')) self.assertGreater(next(i for i, x in enumerate(steps) if 'rollout status' in x), secret) self.assertTrue(any('create secret generic livepeer-runner-bootstrap' in x for x in steps[:next(i for i,x in enumerate(steps) if 'rollout status' in x)])) @@ -136,19 +137,19 @@ def test_reenrollment_resume_preserves_prior_owner_state(self): (state / 'journal').write_text('previous owner') result = self.transition('artifact', mode='reenroll') self.assertNotEqual(result.returncode, 0) - archived = state.parent / 'state.11111111-1111-4111-8111-111111111111/journal' + archived = state.parent / 'state.aaaaaaaaaaaaaaaaaaaaaaaaaa/journal' self.assertEqual(archived.read_text(), 'previous owner') self.assertTrue((self.root / 'state/credential-transition.json').exists()) result = self.transition(mode='reenroll') self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(archived.read_text(), 'previous owner') self.assertFalse((self.root / 'state/credential-transition.json').exists()) - self.assertTrue((state.parent / 'reenrolled-22222222-2222-4222-8222-222222222222').exists()) + self.assertTrue((state.parent / 'reenrolled-cccccccccccccccccccccccccc').exists()) def test_reenrollment_resume_rejects_a_different_issued_identity(self): self.assertNotEqual(self.transition('artifact', mode='reenroll').returncode, 0) identity = (self.root / 'credentials/identity.json').read_bytes() - result = self.transition(mode='reenroll', epoch='33333333-3333-4333-8333-333333333333') + result = self.transition(mode='reenroll', node='d' * 26) self.assertNotEqual(result.returncode, 0) self.assertIn('different identity', result.stderr) self.assertEqual((self.root / 'credentials/identity.json').read_bytes(), identity) diff --git a/runtime/transport/client.go b/runtime/transport/client.go index cde99e3..ac60b95 100644 --- a/runtime/transport/client.go +++ b/runtime/transport/client.go @@ -25,7 +25,7 @@ import ( "github.com/livepeer/control-center/runtime/contract" ) -var nodePath = regexp.MustCompile(`^(.*)/v1/nodes/(lp-[a-f0-9]{16})/config$`) +var nodePath = regexp.MustCompile(`^(.*)/v1/nodes/([a-z2-7]{26})/config$`) var tokenPattern = regexp.MustCompile(`^[a-f0-9]{64}$`) var appReportPath = regexp.MustCompile(`^apps/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/status$`) @@ -117,11 +117,11 @@ func (c *Control) Request(ctx context.Context, endpoint string, payload any, lim } type Identity struct { - Epoch string + NodeID string CredentialVersion int64 } -var epochPattern = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`) +var nodePattern = regexp.MustCompile(`^[a-z2-7]{26}$`) func ReadIdentity(name string) (Identity, error) { var i Identity @@ -130,18 +130,18 @@ func ReadIdentity(name string) (Identity, error) { return i, errors.New("identity_file") } var raw struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` Version int64 `json:"credential_version"` } - if Decode(b, &raw) != nil || raw.Version < 1 || !epochPattern.MatchString(raw.Epoch) { + if Decode(b, &raw) != nil || raw.Version < 1 || !nodePattern.MatchString(raw.NodeID) { return i, errors.New("identity_json") } - return Identity{raw.Epoch, raw.Version}, nil + return Identity{raw.NodeID, raw.Version}, nil } func ReadMetadata(b []byte) (contract.Metadata, error) { var m contract.Metadata - if len(b) > 16384 || Decode(b, &m) != nil || !regexp.MustCompile(`^lp-[0-9a-f]{16}$`).MatchString(m.NodeID) || m.Generation < 1 || m.CredentialVersion < 1 || !epochPattern.MatchString(m.Epoch) || m.BundleFormat != contract.BundleFormat { + if len(b) > 16384 || Decode(b, &m) != nil || !regexp.MustCompile(`^[a-z2-7]{26}$`).MatchString(m.NodeID) || m.Generation < 1 || m.CredentialVersion < 1 || m.BundleFormat != contract.BundleFormat { return m, errors.New("metadata_invalid") } if m.Onchain.Validate() != nil { diff --git a/runtime/transport/client_test.go b/runtime/transport/client_test.go index 461515c..12feb94 100644 --- a/runtime/transport/client_test.go +++ b/runtime/transport/client_test.go @@ -12,7 +12,7 @@ import ( ) func TestControlOriginsCredentialsAndRedirects(t *testing.T) { - node := "lp-" + strings.Repeat("a", 16) + node := strings.Repeat("a", 26) file := filepath.Join(t.TempDir(), "token") os.WriteFile(file, []byte(strings.Repeat("b", 64)), 0600) for _, origin := range []string{"http://example/v1/nodes/" + node + "/config", "https://user:password@example/v1/nodes/" + node + "/config", "https://example/v1/nodes/" + node + "/config?token=secret", "https://example/v1/nodes/" + node + "/%63onfig"} { @@ -106,12 +106,12 @@ func TestDecodeAndIdentityValidation(t *testing.T) { } file := filepath.Join(t.TempDir(), "identity") for _, version := range []string{`"2"`, `0`, `-1`, `null`} { - os.WriteFile(file, []byte(`{"epoch":"11111111-1111-4111-8111-111111111111","credential_version":`+version+`}`), 0600) + os.WriteFile(file, []byte(`{"node_id":"aaaaaaaaaaaaaaaaaaaaaaaaaa","credential_version":`+version+`}`), 0600) if _, err := ReadIdentity(file); err == nil { t.Fatal("accepted invalid credential version", version) } } - os.WriteFile(file, []byte(`{"epoch":"11111111-1111-4111-8111-111111111111","credential_version":2}`), 0600) + os.WriteFile(file, []byte(`{"node_id":"aaaaaaaaaaaaaaaaaaaaaaaaaa","credential_version":2}`), 0600) if i, err := ReadIdentity(file); err != nil || i.CredentialVersion != 2 { t.Fatal(i, err) } diff --git a/runtime/transport/reports.go b/runtime/transport/reports.go index 6dbcbe0..29eefe5 100644 --- a/runtime/transport/reports.go +++ b/runtime/transport/reports.go @@ -36,7 +36,7 @@ type reportSample struct { } type reportCounter struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Sequence uint64 `json:"sequence"` Blocked bool `json:"blocked,omitempty"` @@ -51,7 +51,7 @@ func (r *Reports) Request(ctx context.Context, endpoint string, payload any, lim return nil, nil, errors.New("report_payload") } var identity struct { - Epoch string `json:"epoch"` + NodeID string `json:"node_id"` CredentialVersion int64 `json:"credential_version"` Component string `json:"component"` } @@ -69,7 +69,7 @@ func (r *Reports) Request(ctx context.Context, endpoint string, payload any, lim if os.MkdirAll(r.Directory, 0700) != nil { return nil, nil, errors.New("report_state_unavailable") } - name := reportCounterPath(r.Directory, identity.Component, identity.Epoch) + name := reportCounterPath(r.Directory, identity.Component, identity.NodeID) lock, err := os.OpenFile(name+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) if err != nil { return nil, nil, errors.New("report_state_unavailable") @@ -87,11 +87,11 @@ func (r *Reports) Request(ctx context.Context, endpoint string, payload any, lim } else if !os.IsNotExist(readErr) { return nil, nil, errors.New("report_state_unavailable") } - if counter.Epoch == identity.Epoch && counter.CredentialVersion > identity.CredentialVersion { + if counter.NodeID == identity.NodeID && counter.CredentialVersion > identity.CredentialVersion { return nil, nil, errors.New("report_credential_regression") } - if counter.Epoch != identity.Epoch || counter.CredentialVersion != identity.CredentialVersion { - counter = reportCounter{Epoch: identity.Epoch, CredentialVersion: identity.CredentialVersion} + if counter.NodeID != identity.NodeID || counter.CredentialVersion != identity.CredentialVersion { + counter = reportCounter{NodeID: identity.NodeID, CredentialVersion: identity.CredentialVersion} } if counter.Blocked || counter.Sequence == ^uint64(0) { return nil, nil, errors.New("report_order_unavailable") @@ -156,8 +156,8 @@ func (r *Reports) send(ctx context.Context, body []byte, limit int64, name strin return result, headers, err } -func reportCounterPath(directory, component, epoch string) string { - return filepath.Join(directory, component+"-"+artifact.Digest([]byte(epoch))[7:]+".json") +func reportCounterPath(directory, component, node string) string { + return filepath.Join(directory, component+"-"+artifact.Digest([]byte(node))[7:]+".json") } // ReportErrorCode permits actionable local failures without remote error text. diff --git a/runtime/transport/reports_test.go b/runtime/transport/reports_test.go index 31474c0..ad4c4d3 100644 --- a/runtime/transport/reports_test.go +++ b/runtime/transport/reports_test.go @@ -25,7 +25,7 @@ func (s *reportSink) Request(_ context.Context, _ string, p any, _ int64) ([]byt return nil, nil, s.Err } func sample(at time.Time) map[string]any { - return map[string]any{"epoch": "epoch", "credential_version": 1, "component": "runtime", "generation": 1, "observed_at": at, "ready": true} + return map[string]any{"node_id": "node_id", "credential_version": 1, "component": "runtime", "generation": 1, "observed_at": at, "ready": true} } func sequence(t *testing.T, b []byte) uint64 { t.Helper() @@ -45,7 +45,7 @@ func TestReportsReserveBeforeSendRetryExactlyAndRecover(t *testing.T) { at := time.Now().UTC() value := sample(at) _, _, _ = r.Request(t.Context(), "status", value, 100) - stored, err := os.ReadFile(reportCounterPath(directory, "runtime", "epoch")) + stored, err := os.ReadFile(reportCounterPath(directory, "runtime", "node_id")) if err != nil { t.Fatal(err) } @@ -85,13 +85,13 @@ func TestReportsReserveBeforeSendRetryExactlyAndRecover(t *testing.T) { if _, _, err := r.Request(t.Context(), "status", old, 100); err == nil { t.Fatal("stale sample rewound a credential counter") } - value["epoch"] = "replacement" + value["node_id"] = "replacement" value["credential_version"] = 1 if _, _, err = r.Request(t.Context(), "status", value, 100); err != nil { t.Fatal(err) } if sequence(t, sink.Bodies[len(sink.Bodies)-1]) != 1 { - t.Fatal("new epoch inherited old ordering") + t.Fatal("new node inherited old ordering") } old["credential_version"] = 2 if _, _, err = r.Request(t.Context(), "status", old, 100); err != nil { @@ -102,7 +102,7 @@ func TestReportsReserveBeforeSendRetryExactlyAndRecover(t *testing.T) { t.Fatal(err) } if sequence(t, sink.Bodies[len(sink.Bodies)-1]) != 2 { - t.Fatal("retained epoch corrupted replacement ordering") + t.Fatal("retained node corrupted replacement ordering") } } @@ -118,7 +118,7 @@ func TestReportsFailClosedAfterOrderingLossOrCorruption(t *testing.T) { if _, _, err := r.Request(t.Context(), "status", sample(time.Now()), 100); ReportErrorCode(err) != "report_order_unavailable" || len(sink.Bodies) != 1 { t.Fatal("counted upward after server rejected ordering") } - if err := os.WriteFile(reportCounterPath(directory, "runtime", "epoch"), []byte("broken"), 0600); err != nil { + if err := os.WriteFile(reportCounterPath(directory, "runtime", "node_id"), []byte("broken"), 0600); err != nil { t.Fatal(err) } if _, _, err := r.Request(t.Context(), "status", sample(time.Now()), 100); ReportErrorCode(err) != "report_state_corrupt" || len(sink.Bodies) != 1 { @@ -174,7 +174,7 @@ func TestReportsRetryOrderingRejectionBlocksNewSamples(t *testing.T) { r := &Reports{Client: sink, Directory: directory} value := sample(time.Now().UTC()) _, _, _ = r.Request(t.Context(), "status", value, 100) - name := reportCounterPath(directory, "runtime", "epoch") + name := reportCounterPath(directory, "runtime", "node_id") stored, err := os.ReadFile(name) if err != nil { t.Fatal(err) diff --git a/schema/assignments.go b/schema/assignments.go index 01bcc94..fcb8711 100644 --- a/schema/assignments.go +++ b/schema/assignments.go @@ -52,12 +52,11 @@ type AppAssignment struct { type AppAssignmentSetV1 struct { SchemaVersion int `json:"schema_version"` NodeID string `json:"node_id"` - Epoch string `json:"epoch"` Generation int64 `json:"apps_generation"` Entries []AppAssignment `json:"entries"` } -var assignmentNodePattern = regexp.MustCompile(`^lp-[0-9a-f]{16}$`) +var assignmentNodePattern = regexp.MustCompile(`^[a-z2-7]{26}$`) func canonicalUUID(s string) bool { id, err := uuid.Parse(s) @@ -79,7 +78,7 @@ func (a AppAssignment) Absent() AppAssignment { } func (s AppAssignmentSetV1) Validate() error { - if s.SchemaVersion != 1 || !assignmentNodePattern.MatchString(s.NodeID) || !canonicalUUID(s.Epoch) || s.Generation < 1 || s.Entries == nil || len(s.Entries) > MaxAppAssignments { + if s.SchemaVersion != 1 || !assignmentNodePattern.MatchString(s.NodeID) || s.Generation < 1 || s.Entries == nil || len(s.Entries) > MaxAppAssignments { return fmt.Errorf("invalid app assignment set envelope") } previous := "" diff --git a/schema/assignments_test.go b/schema/assignments_test.go index 08c5b84..a1f4522 100644 --- a/schema/assignments_test.go +++ b/schema/assignments_test.go @@ -19,7 +19,7 @@ func assignmentFixture(t *testing.T) AppAssignmentSetV1 { } canonical, _ := CanonicalBytes(d) r := ResolvedRevision{RevisionRef: RevisionRef{"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", Digest(canonical)}, Name: d.Name, AppVersion: d.AppVersion, Revision: 1, SchemaVersion: 1, CanonicalFormat: CanonicalFormat, Definition: d} - return AppAssignmentSetV1{SchemaVersion: 1, NodeID: "lp-aaaaaaaaaaaaaaaa", Epoch: "11111111-1111-4111-8111-111111111111", Generation: 1, Entries: []AppAssignment{{RevisionRef: r.RevisionRef, Generation: 2, ActivationGeneration: 1, Desired: "present", Cleanup: CleanupPolicy(d), Revision: &r, Replicas: 3, StartAllowed: true}}} + return AppAssignmentSetV1{SchemaVersion: 1, NodeID: "vkvkvkvkvkvkuaaaaaaaaaaaaa", Generation: 1, Entries: []AppAssignment{{RevisionRef: r.RevisionRef, Generation: 2, ActivationGeneration: 1, Desired: "present", Cleanup: CleanupPolicy(d), Revision: &r, Replicas: 3, StartAllowed: true}}} } func TestAssignmentContractAndCompactRemoval(t *testing.T) { s := assignmentFixture(t) diff --git a/ui/src/administration.tsx b/ui/src/administration.tsx index 9201aa1..6c5659c 100644 --- a/ui/src/administration.tsx +++ b/ui/src/administration.tsx @@ -6,7 +6,7 @@ import { MachineApps } from './machine-apps' import { MachineStatus, machineStatusSummary } from './machine-status' type Grant = { grant_id: string; email: string; user_id: string | null; current_email: string | null; revision: number; state: 'pending' | 'bound' | 'account_missing' } -type FleetMachine = { terminal?: boolean; report_state?: string; lifecycle?: string; node_id: string; epoch: string; hostname: string; owner_id: string; k3s_version: string; created_at: string; last_config_fetch_at: string | null } +type FleetMachine = { terminal?: boolean; report_state?: string; lifecycle?: string; node_id: string; hostname: string; owner_id: string; k3s_version: string; created_at: string; last_config_fetch_at: string | null } type Capability = 'loading' | 'admin' | 'ordinary' | 'unavailable' // Keyed by account in Dashboard. Request versions reject obsolete successes @@ -119,8 +119,8 @@ export function Administration({ session }: { session: Session }) {
{ invalidate(error.status === 503 ? 'unavailable' : 'ordinary'); setAccessProblem(error.message) }} />

Machine fleet {machines.length}

-
{machines.map(machine => )}
MACHINEOWNERK3S VERSIONLAST CONFIG REQUESTAPPSRUNTIME
{machine.hostname}{machine.node_id}{machine.owner_id}{machine.k3s_version}{machine.last_config_fetch_at ? new Date(machine.last_config_fetch_at).toLocaleString() : 'Awaiting first request'}{machine.terminal &&

Retired — cleanup pending

}

{machineStatusSummary(machine)}

{machines.length === 0 &&

No machines enrolled.

}
- {machines.filter(m => `${m.node_id}:${m.epoch}` === selectedMachine).map(machine =>
+
{machines.map(machine => )}
MACHINEOWNERK3S VERSIONLAST CONFIG REQUESTAPPSRUNTIME
{machine.hostname}{machine.node_id}{machine.owner_id}{machine.k3s_version}{machine.last_config_fetch_at ? new Date(machine.last_config_fetch_at).toLocaleString() : 'Awaiting first request'}{machine.terminal &&

Retired — cleanup pending

}

{machineStatusSummary(machine)}

{machines.length === 0 &&

No machines enrolled.

}
+ {machines.filter(m => m.node_id === selectedMachine).map(machine =>
{ invalidate('ordinary'); setAccessProblem(error.message) }} /> {!machine.terminal && { invalidate(error.status === 503 ? 'unavailable' : 'ordinary'); setAccessProblem(error.message) }} />}
)} diff --git a/ui/src/catalog.tsx b/ui/src/catalog.tsx index d54bb67..debaeed 100644 --- a/ui/src/catalog.tsx +++ b/ui/src/catalog.tsx @@ -27,7 +27,7 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho const [message, setMessage] = useState('') const [busy, setBusy] = useState(false) const [conflict, setConflict] = useState(false) - const epoch = useRef(0) + const requestGeneration = useRef(0) const serial = useRef>({}) const controllers = useRef(new Set()) const draft = useRef(0) @@ -35,13 +35,13 @@ export function Catalog({ session, authorityFailure }: { session: Session; autho const failure = useRef(authorityFailure) failure.current = authorityFailure - function cancel() { epoch.current++; controllers.current.forEach(c => c.abort()); controllers.current.clear(); changing.current = false } + function cancel() { requestGeneration.current++; controllers.current.forEach(c => c.abort()); controllers.current.clear(); changing.current = false } // Resource generations are separate from capability polling and draft edits. async function run(key: string, operation: (signal: AbortSignal) => Promise, apply: (value: T) => void) { - const e = epoch.current, ticket = (serial.current[key] || 0) + 1 + const e = requestGeneration.current, ticket = (serial.current[key] || 0) + 1 serial.current[key] = ticket const controller = new AbortController(); controllers.current.add(controller) - const current = () => e === epoch.current && ticket === serial.current[key] && !controller.signal.aborted + const current = () => e === requestGeneration.current && ticket === serial.current[key] && !controller.signal.aborted try { const value = await operation(controller.signal); if (current()) apply(value) } catch (error) { if (!current()) return diff --git a/ui/src/machine-apps.tsx b/ui/src/machine-apps.tsx index 44d2aed..7568388 100644 --- a/ui/src/machine-apps.tsx +++ b/ui/src/machine-apps.tsx @@ -5,10 +5,10 @@ import { api, APIError } from './api' type Revision = { revision_id: string; digest: string; name: string; revision: number; app_version: string; lifecycle: { retired_at: string | null }; definition: { name: string; instances: { replicas: number } } } type Summary = Pick type Assignment = { revision_id: string; digest: string; app_name: string; revision_number: number; generation: number; activation_generation: number; desired: 'present' | 'absent'; replicas?: number; revision?: Revision; start_after?: unknown; replacement?: unknown; start_allowed: boolean; completed_at: string | null; failure?: string; observed_at: string | null; created_at: string; actor_id: string } -type Listing = { epoch: string; assignments: Assignment[]; apps_generation: number; published_generation: number; delivery_error: string | null; next_after_revision_id: string | null; last_config_fetch_at: string | null } +type Listing = { assignments: Assignment[]; apps_generation: number; published_generation: number; delivery_error: string | null; next_after_revision_id: string | null; last_config_fetch_at: string | null } type Detail = { assignment: Assignment; revision: Revision; history: Assignment[]; next_before_generation: number | null } -export function MachineApps({ session, machine, authorityFailure }: { session: Session; machine: { node_id: string; hostname: string; epoch: string }; authorityFailure: (error: APIError) => void }) { +export function MachineApps({ session, machine, authorityFailure }: { session: Session; machine: { node_id: string; hostname: string; }; authorityFailure: (error: APIError) => void }) { const base = `/api/admin/machines/${machine.node_id}/apps` const [listing, setListing] = useState(null) const [apps, setApps] = useState<{ name: string }[]>([]) @@ -23,16 +23,16 @@ export function MachineApps({ session, machine, authorityFailure }: { session: S const [problem, setProblem] = useState('') const [message, setMessage] = useState('') const [busy, setBusy] = useState(false) - const epoch = useRef(0), serial = useRef>({}), changing = useRef(false) + const requestGeneration = useRef(0), serial = useRef>({}), changing = useRef(false) const controllers = useRef(new Set()) const loadedPages = useRef(1), listingRequest = useRef | null>(null) const failure = useRef(authorityFailure); failure.current = authorityFailure - function cancel() { epoch.current++; controllers.current.forEach(c => c.abort()); controllers.current.clear(); changing.current = false; listingRequest.current = null } + function cancel() { requestGeneration.current++; controllers.current.forEach(c => c.abort()); controllers.current.clear(); changing.current = false; listingRequest.current = null } async function run(key: string, operation: (signal: AbortSignal) => Promise, apply: (value: T) => void) { - const e = epoch.current, ticket = (serial.current[key] || 0) + 1; serial.current[key] = ticket + const e = requestGeneration.current, ticket = (serial.current[key] || 0) + 1; serial.current[key] = ticket const controller = new AbortController(); controllers.current.add(controller) - const current = () => e === epoch.current && ticket === serial.current[key] && !controller.signal.aborted + const current = () => e === requestGeneration.current && ticket === serial.current[key] && !controller.signal.aborted try { const value = await operation(controller.signal); if (current()) apply(value) } catch (error) { if (!current()) return @@ -47,13 +47,11 @@ export function MachineApps({ session, machine, authorityFailure }: { session: S let data = await page(after) const assignments = [...data.assignments] for (let i = 1; !after && i < loadedPages.current && data.next_after_revision_id; i++) { - if (data.epoch !== machine.epoch) break data = await page(data.next_after_revision_id) assignments.push(...data.assignments) } return { ...data, assignments } }, data => { - if (data.epoch !== machine.epoch) { cancel(); setListing(null); setProblem('Machine enrollment changed. Select the machine again.'); return } if (after) loadedPages.current++ else setCounts(old => Object.fromEntries(Object.entries(old).filter(([id, draft]) => data.assignments.some(a => a.revision_id === id && a.desired === 'present' && a.activation_generation === draft.activation)))) setListing(old => after && old ? { ...data, assignments: [...old.assignments, ...data.assignments.filter(a => !old.assignments.some(b => a.revision_id === b.revision_id))] } : data) @@ -77,7 +75,7 @@ export function MachineApps({ session, machine, authorityFailure }: { session: S } function inspect(id: string, before?: number) { if (!before) setDetail(null) - void run('detail', signal => api(session, `${base}/${id}?epoch=${machine.epoch}` + (before ? `&before_generation=${before}` : ''), { signal }), data => setDetail(old => before && old ? { ...data, history: [...old.history, ...data.history] } : data)) + void run('detail', signal => api(session, `${base}/${id}` + (before ? `?before_generation=${before}` : ''), { signal }), data => setDetail(old => before && old ? { ...data, history: [...old.history, ...data.history] } : data)) } useEffect(() => { setBusy(false); load(); loadApps() @@ -85,7 +83,7 @@ export function MachineApps({ session, machine, authorityFailure }: { session: S return () => { window.clearInterval(timer); cancel() } // The parent keys this component by account, machine and enrollment. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [session.access_token, machine.node_id, machine.epoch]) + }, [session.access_token, machine.node_id]) function mutate(path: string, method: string, body: unknown) { if (changing.current || !listing) return @@ -118,16 +116,16 @@ export function MachineApps({ session, machine, authorityFailure }: { session: S - + {moreApps && }{moreRevisions && }
{selected &&
Inspect selected revision{selected.digest}
{JSON.stringify(selected.definition, null, 2)}
}
    {listing?.assignments.map(a =>
  • {a.app_name} / revision {a.revision_number}

    {label(a)}

    {a.revision_id}

    Desired {a.generation} · activation {a.activation_generation}{a.observed_at ? ` · last observation ${new Date(a.observed_at).toLocaleString()}` : ''}

    - {present(a) && <> - - } + {present(a) && <> + + }
  • )}
{listing?.assignments.length === 0 &&

No app assignments.

}{listing?.next_after_revision_id && } diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index e2a1480..cc57141 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -10,8 +10,8 @@ type Apps = { desired_generation: number; desired_digest?: string; staged?: Stag type OnchainEvidence = { generation: number; mode: string; applied: boolean; ready: boolean; handoff: string } type Component = { onchain?: OnchainEvidence; observer_id?: string; observer_started_at?: string; component: string; generation: number; observed_at?: string; received_at?: string; expires_at?: string; fresh: boolean; current: boolean; ready: boolean; reason: string; clock_uncertain: boolean; bundle_sha256?: string; downloaded?: Stage; downloaded_at?: string; delivery_reason?: string; apps_error?: string; apps?: Apps; connector_observed_at?: string; connector_expires_at?: string } type Assignment = { revision_id: string; digest: string; name: string; version: string; revision: number; generation: number; activation_generation: number; desired: string; replicas: number; start_allowed: boolean; completed_at: string | null; failure?: string; health: { type: string; interval: string; timeout: string; failure_threshold: number } } -type Membership = { state: string; provenance_current: boolean; queried_at?: string; observed_at?: string; expires_at?: string } -export type MachineObservation = { onchain?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number }; node_id: string; epoch: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } +type Membership = { state: string; queried_at?: string; observed_at?: string; expires_at?: string } +export type MachineObservation = { onchain?: { desired: { mode: string; generation: number; network?: string; chain_id?: number; recipient?: string; controller?: string; wei_per_usd?: string; eth_usd_feed?: string; ticket_face_value?: string; ticket_win_prob?: string }; delivered_generation: number }; node_id: string; hostname: string; lifecycle: string; rollout_generation: number; requested: Stage; delivered?: Stage; delivered_at?: string; delivery_reason?: string; assignments: Assignment[]; assignments_omitted: boolean; components: Component[]; tunnel: { enabled: boolean; ready: boolean; reason: string; verified_at?: string; expires_at?: string; cleanup_complete: boolean }; discovery_enabled: boolean; discovery_initialized: boolean; discovery_selection_stale: boolean; discovery_selection_expires_at?: string; discovery_source?: { state: string; selection_reason: string; stale: boolean; expires_at?: string; failures: number; transport_outcome?: string; last_attempt?: string; last_success?: string; publication_blocked: boolean }; membership: Record; external_reachability: string; server_time: string } export function machineStatusSummary(machine: { terminal?: boolean; report_state?: string; last_config_fetch_at?: string | null }) { const labels: Record = { observed: 'Runtime observed', stale: 'Status stale', clock_uncertain: 'Clock uncertain' } @@ -29,7 +29,7 @@ function Identity({ value, label }: { value?: Stage; label: string }) { return
{label}{value ? `App generation ${value.generation || 'unknown'}` : 'Unobserved'}{value?.apps_digest && {value.apps_digest}}{value?.artifact_digest && {value.artifact_digest}}
} -export function MachineStatus({ session, machine, authorityFailure }: { session: Session; machine: { node_id: string; epoch: string; hostname: string }; authorityFailure?: (error: APIError) => void }) { +export function MachineStatus({ session, machine, authorityFailure }: { session: Session; machine: { node_id: string; hostname: string }; authorityFailure?: (error: APIError) => void }) { const [view, setView] = useState(null) const [problem, setProblem] = useState('') const [now, setNow] = useState(Date.now()) @@ -43,9 +43,9 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: pending = true const started = performance.now() try { - const data = await api(session, `/api/machines/${encodeURIComponent(machine.node_id)}/status?epoch=${encodeURIComponent(machine.epoch)}`, { signal: controller.signal }) + const data = await api(session, `/api/machines/${encodeURIComponent(machine.node_id)}/status`, { signal: controller.signal }) if (!current || controller.signal.aborted) return - if (data.node_id !== machine.node_id || data.epoch !== machine.epoch) { setView(null); setProblem('Machine enrollment changed. Select the machine again.'); return } + if (data.node_id !== machine.node_id) { setView(null); setProblem('Machine enrollment changed. Select the machine again.'); return } const arrived = Date.now() setOffset(Date.parse(data.server_time) + performance.now() - started - arrived) setNow(arrived); setView(data); setProblem('') @@ -61,7 +61,7 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: return () => { current = false; controller.abort(); window.clearInterval(poll); window.clearInterval(tick); document.removeEventListener('visibilitychange', load) } // The caller keys this panel by account and enrollment. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [session.user.id, session.access_token, machine.node_id, machine.epoch]) + }, [session.user.id, session.access_token, machine.node_id]) const clock = now + offset const fresh = (c?: Component) => !!c && c.fresh && alive(c.expires_at, clock) const runner = view?.components.find(c => c.component === 'runner'), apps = runner?.apps @@ -73,13 +73,12 @@ export function MachineStatus({ session, machine, authorityFailure }: { session: if (!view?.discovery_enabled) return 'Disabled' if (!m) return 'Unverified' if (view.discovery_selection_stale || !alive(view.discovery_selection_expires_at, clock)) return 'Source selection stale' - if (m.state === 'unverified_provenance') return reason(m.state) if (m.state === 'present' && alive(m.expires_at, clock)) return 'Present in published inventory' if (m.expires_at && !alive(m.expires_at, clock)) return 'Stale inventory' return m.state === 'absent' ? 'Absent from last successful inventory' : reason(m.state) } return
-

Runtime status on {machine.hostname}

{machine.node_id} · {machine.epoch}
+

Runtime status on {machine.hostname}

{machine.node_id}
{problem &&
{problem}
} {!view && !problem &&

Loading observed state…

} {view && <> diff --git a/ui/src/main.tsx b/ui/src/main.tsx index 4d0b05f..cfd7b65 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -9,7 +9,7 @@ import { Administration } from './administration' import { MachineStatus, machineStatusSummary } from './machine-status' type Config = { supabase_url: string; supabase_publishable_key: string; public_api_url: string } -type Machine = { node_id: string; epoch?: string; terminal?: boolean; lifecycle?: string; report_state?: string; hostname: string; created_at: string; last_config_fetch_at: string | null } +type Machine = { node_id: string; terminal?: boolean; lifecycle?: string; report_state?: string; hostname: string; created_at: string; last_config_fetch_at: string | null } type Enrollment = { token: string; expires_at: string } function Brand({ dark = false }: { dark?: boolean }) { @@ -151,10 +151,10 @@ function Dashboard({ client, session, config }: { client: SupabaseClient; sessio

Your machines{machines?.length ?? '—'}

Every connected machine, in one place.

Updates automatically
{machineProblem && {machineProblem}} -
{machines === null ?

Loading your machines…

: machines.length === 0 ?

Your first machine starts here.

Run the command above. Your machine will appear
here as soon as enrollment succeeds.

Ready when you are
:
{machines.map(machine => )}
MACHINESTATUSENROLLED / RETIREDLAST CONFIG REQUESTRUNTIME
{machine.hostname}{machine.node_id}
{machineStatusSummary(machine)}{new Date(machine.created_at).toLocaleString()}{machine.last_config_fetch_at ? new Date(machine.last_config_fetch_at).toLocaleString() : 'Awaiting first request'}
}
+
{machines === null ?

Loading your machines…

: machines.length === 0 ?

Your first machine starts here.

Run the command above. Your machine will appear
here as soon as enrollment succeeds.

Ready when you are
:
{machines.map(machine => )}
MACHINESTATUSENROLLED / RETIREDLAST CONFIG REQUESTRUNTIME
{machine.hostname}{machine.node_id}
{machineStatusSummary(machine)}{new Date(machine.created_at).toLocaleString()}{machine.last_config_fetch_at ? new Date(machine.last_config_fetch_at).toLocaleString() : 'Awaiting first request'}
}

Enrollment and configuration requests do not establish application health. Open Runtime status for rollout and configured health evidence.

- {machines?.filter(m => `${m.node_id}:${m.epoch}` === selectedMachine && m.epoch).map(m => )} + {machines?.filter(m => m.node_id === selectedMachine).map(m => )}
LIVEPEER / CONTROL CENTERYOUR MACHINES. OPEN POSSIBILITIES.
diff --git a/ui/tests/administration.spec.ts b/ui/tests/administration.spec.ts index c052b72..0713b44 100644 --- a/ui/tests/administration.spec.ts +++ b/ui/tests/administration.spec.ts @@ -5,7 +5,7 @@ const a = '11111111-1111-4111-8111-111111111111' const b = '22222222-2222-4222-8222-222222222222' const grantA = { grant_id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', email: 'a@example.invalid', current_email: 'renamed@example.invalid', user_id: a, state: 'bound', revision: 2 } const grantB = { grant_id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', email: 'b@example.invalid', current_email: null, user_id: b, state: 'bound', revision: 1 } -const fleet = { node_id: 'lp-aaaaaaaaaaaaaaaa', hostname: 'private-fleet-machine', owner_id: b, k3s_version: 'v1.37.2+k3s1', created_at: '2026-11-06T00:00:00Z', last_config_fetch_at: null } +const fleet = { node_id: 'vkvkvkvkvkvkuaaaaaaaaaaaaa', hostname: 'private-fleet-machine', owner_id: b, k3s_version: 'v1.37.2+k3s1', created_at: '2026-11-06T00:00:00Z', last_config_fetch_at: null } const expires = Math.floor(Date.now() / 1000) + 3600 function session(id: string) { diff --git a/ui/tests/machine-apps.spec.ts b/ui/tests/machine-apps.spec.ts index 2f30a13..1c5cc0f 100644 --- a/ui/tests/machine-apps.spec.ts +++ b/ui/tests/machine-apps.spec.ts @@ -1,9 +1,9 @@ import { test, expect } from '@playwright/test' import type { Page, Route } from '@playwright/test' -const owner = '11111111-1111-4111-8111-111111111111', epoch = '22222222-2222-4222-8222-222222222222' +const owner = '11111111-1111-4111-8111-111111111111' const r1 = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', r2 = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -const node = 'lp-aaaaaaaaaaaaaaaa', base = `/api/admin/machines/${node}/apps` +const node = 'vkvkvkvkvkvkuaaaaaaaaaaaaa', base = `/api/admin/machines/${node}/apps` const expires = Math.floor(Date.now() / 1000) + 3600 const saved = { access_token: `${Buffer.from('{}').toString('base64url')}.${Buffer.from(JSON.stringify({ sub: owner, exp: expires })).toString('base64url')}.fixture`, refresh_token: 'fixture', token_type: 'bearer', expires_at: expires, expires_in: 3600, user: { id: owner, email: 'a@example.invalid', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {}, created_at: '2026-11-07T00:00:00Z' } } function revision(id: string, n: number) { return { revision_id: id, digest: 'sha256:' + (n === 1 ? 'a' : 'b').repeat(64), name: 'whoami', revision: n, app_version: String(n), lifecycle: { retired_at: null, version: 1 }, definition: { name: 'whoami', instances: { replicas: 2 } } } } @@ -24,7 +24,7 @@ async function setup(page: Page) { if (path === '/api/me') return route.fulfill({ json: { user_id: owner, is_admin: state.admin } }) if (path === '/api/machines') return route.fulfill({ json: { machines: [] } }) if (path === '/api/admin/administrators') return route.fulfill({ json: { administrators: [] } }) - if (path === '/api/admin/machines') return route.fulfill({ json: { machines: [{ node_id: node, epoch, hostname: 'worker-apps', owner_id: owner, k3s_version: 'v1.37.2+k3s1', created_at: '2026-11-07T00:00:00Z', last_config_fetch_at: null }] } }) + if (path === '/api/admin/machines') return route.fulfill({ json: { machines: [{ node_id: node, hostname: 'worker-apps', owner_id: owner, k3s_version: 'v1.37.2+k3s1', created_at: '2026-11-07T00:00:00Z', last_config_fetch_at: null }] } }) if (path === '/api/admin/apps') return route.fulfill({ json: { apps: [{ name: 'whoami', head: revision(r2, 2), active_revision_count: 2 }], payment_mode: 'offchain', next_after_name: null } }) if (path === '/api/admin/apps/whoami') return route.fulfill({ json: { revisions: [revision(r2, 2), revision(r1, 1)], next_before_revision: null } }) if (path.startsWith('/api/admin/apps/whoami/revisions/')) return route.fulfill({ json: revision(path.endsWith(r1) ? r1 : r2, path.endsWith(r1) ? 1 : 2) }) @@ -34,7 +34,7 @@ async function setup(page: Page) { const after = new URL(route.request().url()).searchParams.get('after_revision_id') || '' const remaining = [...state.assignments].sort((a, b) => a.revision_id.localeCompare(b.revision_id)).filter(a => a.revision_id > after) const assignments = remaining.slice(0, 100) - return route.fulfill({ json: { epoch, assignments, apps_generation: state.gen, published_generation: 0, next_after_revision_id: remaining.length > 100 ? assignments.at(-1)!.revision_id : null, last_config_fetch_at: null } }) + return route.fulfill({ json: { assignments, apps_generation: state.gen, published_generation: 0, next_after_revision_id: remaining.length > 100 ? assignments.at(-1)!.revision_id : null, last_config_fetch_at: null } }) } if (path.startsWith(base + '/') && method !== 'GET') { const body = route.request().postDataJSON(); state.posts.push({ method, path, body }); state.gen++ @@ -47,7 +47,7 @@ async function setup(page: Page) { absent(old); old.generation++ state.assignments.push({ ...assignment(body.target.revision_id, 2), replicas: body.target.replicas, start_allowed: false, start_after: { source_revision_id: id, source_removal_generation: old.generation } }) } - return route.fulfill({ status: 202, json: { changed: true, epoch, assignments: state.assignments.filter(a => a.revision_id === id || a.revision_id === body.target?.revision_id) } }) + return route.fulfill({ status: 202, json: { changed: true, assignments: state.assignments.filter(a => a.revision_id === id || a.revision_id === body.target?.revision_id) } }) } return route.fulfill({ status: 404, json: { error: 'Not found' } }) }) @@ -62,7 +62,7 @@ test('machine apps assign, scale and replace only after cleanup', async ({ page await page.getByLabel('Catalog revision for machine').selectOption(r1) await page.getByRole('button', { name: 'Assign selected revision', exact: true }).click() await expect(page.getByText('Pending Runtime completion', { exact: true })).toBeVisible() - expect(state.posts[0].body).toMatchObject({ epoch, expected_generation: 0, replicas: 2 }) + expect(state.posts[0].body).toMatchObject({ expected_generation: 0, replicas: 2 }) await page.getByLabel(`Replicas for ${r1}`).fill('3') await page.getByRole('button', { name: 'Save replicas', exact: true }).click() await expect.poll(() => state.assignments[0].replicas).toBe(3) @@ -71,7 +71,7 @@ test('machine apps assign, scale and replace only after cleanup', async ({ page await expect(page.getByText('Waiting for previous revision cleanup', { exact: true })).toBeVisible() await expect(page.getByText('Removing — waiting for cleanup', { exact: true })).toBeVisible() await expect(page.getByText('whoami / revision 1', { exact: true })).toBeVisible() - expect(state.posts.at(-1)?.body).toMatchObject({ epoch, expected_generation: 2, target: { revision_id: r2, expected_generation: 0 } }) + expect(state.posts.at(-1)?.body).toMatchObject({ expected_generation: 2, target: { revision_id: r2, expected_generation: 0 } }) await page.getByRole('button', { name: 'Remove revision 2', exact: true }).click() await expect.poll(() => state.assignments[1].desired).toBe('absent') }) @@ -85,7 +85,7 @@ test('revocation unmounts app panel and ignores late assignment responses', asyn state.admin = false await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange'))) await expect(page.getByRole('heading', { name: 'Apps on worker-apps' })).toHaveCount(0) - for (const route of state.held) await route.fulfill({ json: { epoch, assignments: [], apps_generation: 99, published_generation: 99, next_after_revision_id: null } }) + for (const route of state.held) await route.fulfill({ json: { assignments: [], apps_generation: 99, published_generation: 99, next_after_revision_id: null } }) await expect(page.getByRole('heading', { name: 'Apps on worker-apps' })).toHaveCount(0) }) @@ -118,7 +118,7 @@ test('manual assignment refresh supersedes an in-flight poll', async ({ page }) state.assignments = [assignment(r1, 1)]; state.hold = false await page.getByRole('button', { name: 'Refresh assignments', exact: true }).click() await expect(page.getByLabel(`Replicas for ${r1}`)).toHaveValue('2') - await state.held[0].fulfill({ json: { epoch, assignments: [], apps_generation: 0, published_generation: 0, next_after_revision_id: null } }) + await state.held[0].fulfill({ json: { assignments: [], apps_generation: 0, published_generation: 0, next_after_revision_id: null } }) await expect(page.getByLabel(`Replicas for ${r1}`)).toHaveValue('2') }) diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index decada9..07f54c4 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -3,17 +3,16 @@ import type { Page, Route } from '@playwright/test' import type { MachineObservation } from '../src/machine-status' const user = '11111111-1111-4111-8111-111111111111' -const epoch = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' -const node = 'lp-aaaaaaaaaaaaaaaa' +const node = 'vkvkvkvkvkvkuaaaaaaaaaaaaa' const revision = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' const digest = `sha256:${'a'.repeat(64)}` const session = { access_token: `${Buffer.from('{}').toString('base64url')}.${Buffer.from(JSON.stringify({ sub: user, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url')}.fixture`, refresh_token: 'fixture', token_type: 'bearer', expires_at: Math.floor(Date.now() / 1000) + 3600, expires_in: 3600, user: { id: user, email: 'owner@example.invalid', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {}, created_at: '2026-11-09T00:00:00Z' } } -const machine = { node_id: node, epoch, hostname: 'worker-status', k3s_version: 'v1.37.2+k3s1', owner_id: user, created_at: '2026-11-09T00:00:00Z', last_config_fetch_at: null, report_state: 'observed', terminal: false } +const machine = { node_id: node, hostname: 'worker-status', k3s_version: 'v1.37.2+k3s1', owner_id: user, created_at: '2026-11-09T00:00:00Z', last_config_fetch_at: null, report_state: 'observed', terminal: false } function evidence(): MachineObservation { const stamp = new Date().toISOString(), expires = new Date(Date.now() + 120000).toISOString() const stage = { generation: 1, apps_digest: digest, artifact_digest: digest } - return { node_id: node, epoch, hostname: machine.hostname, lifecycle: 'active', rollout_generation: 1, requested: { generation: 2 }, delivered: stage, delivered_at: stamp, assignments_omitted: false, server_time: stamp, + return { node_id: node, hostname: machine.hostname, lifecycle: 'active', rollout_generation: 1, requested: { generation: 2 }, delivered: stage, delivered_at: stamp, assignments_omitted: false, server_time: stamp, components: [ { component: 'runtime', generation: 1, observed_at: stamp, received_at: stamp, expires_at: expires, fresh: true, current: true, ready: true, reason: 'ready', clock_uncertain: false, downloaded: stage, downloaded_at: stamp }, { component: 'runner', generation: 1, observed_at: stamp, received_at: stamp, expires_at: expires, fresh: true, current: true, ready: true, reason: 'ready', clock_uncertain: false, apps: { owner_recreated_at: '0001-01-01T00:00:00Z', desired_generation: 1, desired_digest: digest, staged: stage, published: stage, applied: stage, instances_total: 1, instances_omitted: 0, assignments: [{ revision_id: revision, generation: 1, activation_generation: 1, instances: 1, ready: 1, registered: 1, cleanup_pending: 0, node_expires_at: expires, probe_expires_at: expires }], instances: [{ revision_id: revision, generation: 1, activation_generation: 1, instance_id: 'instance-preserved', pod_uid: 'pod-preserved', runner_id: 'runner-preserved', app_id: 'app-preserved', phase: 'running', ready: true, registered: true, capacity: 4, sessions: 2, node_observed_at: stamp, node_expires_at: expires, startup_deadline: expires, probe: { observed_at: stamp, due_at: expires, expires_at: expires, success: true, failures: 0, started: true } }] } }, @@ -22,17 +21,17 @@ function evidence(): MachineObservation { ], assignments: [{ revision_id: revision, digest, name: 'whoami', version: '1', revision: 1, generation: 1, activation_generation: 1, desired: 'present', replicas: 1, start_allowed: true, completed_at: stamp, health: { type: 'http', interval: '5s', timeout: '2s', failure_threshold: 3 } }], tunnel: { enabled: true, ready: true, reason: 'ready', verified_at: stamp, expires_at: expires, cleanup_complete: false }, discovery_enabled: true, discovery_initialized: true, discovery_selection_stale: false, discovery_selection_expires_at: expires, - discovery_source: { state: 'fresh', selection_reason: 'selected', stale: false, expires_at: expires, failures: 0, last_success: stamp, transport_outcome: 'response_received', publication_blocked: false }, membership: { 'instance-preserved': { state: 'present', provenance_current: true, queried_at: stamp, observed_at: stamp, expires_at: expires } }, external_reachability: 'unverified' } + discovery_source: { state: 'fresh', selection_reason: 'selected', stale: false, expires_at: expires, failures: 0, last_success: stamp, transport_outcome: 'response_received', publication_blocked: false }, membership: { 'instance-preserved': { state: 'present', queried_at: stamp, observed_at: stamp, expires_at: expires } }, external_reachability: 'unverified' } } async function setup(page: Page, admin = false, reportState = 'observed', terminal = false) { const listedMachine = { ...machine, report_state: reportState, terminal } - const state = { view: evidence(), fail: false, hold: false, held: [] as Route[], reads: 0, statusEpochs: [] as string[], admin } + const state = { view: evidence(), fail: false, hold: false, held: [] as Route[], reads: 0, statusNodes: [] as string[], admin } if (terminal) { state.view.lifecycle = 'cleanup_pending'; state.view.assignments[0].desired = 'absent'; state.view.assignments[0].completed_at = null } await page.addInitScript(saved => { localStorage.setItem('sb-auth-auth-token', JSON.stringify(saved)) const fetch = window.fetch.bind(window) - window.fetch = (input, options) => fetch(input, String(input).includes('/status?') ? { ...options, signal: undefined } : options) + window.fetch = (input, options) => fetch(input, String(input).includes('/status') ? { ...options, signal: undefined } : options) }, session) await page.route('http://auth.test/**', route => route.fulfill({ json: session.user, headers: { 'Access-Control-Allow-Origin': '*' } })) await page.route('**/api/**', async route => { @@ -43,14 +42,14 @@ async function setup(page: Page, admin = false, reportState = 'observed', termin if (path === '/api/admin/administrators') return route.fulfill({ json: { administrators: [] } }) if (path === '/api/admin/apps') return route.fulfill({ json: { apps: [], onchain_mode: 'offchain', next_after_name: null } }) if (path === '/api/admin/machines') return route.fulfill({ json: { machines: [listedMachine] } }) - if (path === '/api/machines') return route.fulfill({ json: { machines: admin ? [] : [listedMachine, { ...machine, node_id: 'lp-bbbbbbbbbbbbbbbb', hostname: 'second-worker', epoch: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' }] } }) - if (path.startsWith('/api/admin/machines/') && path.endsWith('/apps')) return route.fulfill({ json: { epoch, assignments: [], apps_generation: 2, published_generation: 1, next_after_revision_id: null, last_config_fetch_at: null } }) + if (path === '/api/machines') return route.fulfill({ json: { machines: admin ? [] : [listedMachine, { ...machine, node_id: 'xo53xo53xo53waaaaaaaaaaaaa', hostname: 'second-worker', }] } }) + if (path.startsWith('/api/admin/machines/') && path.endsWith('/apps')) return route.fulfill({ json: { assignments: [], apps_generation: 2, published_generation: 1, next_after_revision_id: null, last_config_fetch_at: null } }) if (path.endsWith('/status')) { state.reads++ - state.statusEpochs.push(new URL(route.request().url()).searchParams.get('epoch') || '') + state.statusNodes.push(path.split('/').at(-2) || '') if (state.hold) { state.held.push(route); return } if (state.fail) return route.fulfill({ status: 503, json: { error: 'Status refresh unavailable.' } }) - const identity = path.includes('lp-bbbbbbbbbbbbbbbb') ? { node_id: 'lp-bbbbbbbbbbbbbbbb', epoch: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', hostname: 'second-worker' } : {} + const identity = path.includes('xo53xo53xo53waaaaaaaaaaaaa') ? { node_id: 'xo53xo53xo53waaaaaaaaaaaaa', hostname: 'second-worker' } : {} return route.fulfill({ json: { ...state.view, ...identity } }) } return route.fulfill({ status: 404, json: { error: 'Not found' } }) @@ -205,7 +204,7 @@ test('fresh failing probe evidence expires on its configured schedule and recove for (const admin of [false, true]) test(`${admin ? 'administrator' : 'owner'} can inspect the original retired enrollment without app mutations`, async ({ page }) => { const state = await setup(page, admin, 'stale', true) - await expect.poll(() => state.statusEpochs[0]).toBe(epoch) + await expect.poll(() => state.statusNodes[0]).toBe(node) await expect(page.getByText('Desired removal', { exact: false })).toBeVisible() if (admin) await expect(page.getByRole('button', { name: 'Manage apps for worker-status' })).toHaveText('Inspect cleanup') else await expect(page.getByText('Cleanup pending', { exact: true })).toBeVisible() From d91012935676924052ccc499a960c50ffa552ea4 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:20:25 -0800 Subject: [PATCH 11/15] Preserve onchain continuity on the current lifecycle --- .../controlplane/discovery/manager_test.go | 1 + api/internal/controlplane/onchain_credentials.go | 2 +- api/internal/controlplane/onchain_test.go | 15 +++++++++++++-- runtime/orchestrator/integration_test.go | 2 +- ui/src/machine-status.tsx | 2 +- ui/tests/machine-status.spec.ts | 16 ---------------- 6 files changed, 17 insertions(+), 21 deletions(-) diff --git a/api/internal/controlplane/discovery/manager_test.go b/api/internal/controlplane/discovery/manager_test.go index a3e3c3b..1181e19 100644 --- a/api/internal/controlplane/discovery/manager_test.go +++ b/api/internal/controlplane/discovery/manager_test.go @@ -509,6 +509,7 @@ func TestFleetWorkerStartsEmptyAndClosesPendingWork(t *testing.T) { case <-time.After(time.Millisecond): } } + f.collector.Refresh(ctx, false) // Join the initial refresh before starting another. block.Store(true) refreshDone := make(chan struct{}) go func() { f.collector.Refresh(ctx, false); close(refreshDone) }() diff --git a/api/internal/controlplane/onchain_credentials.go b/api/internal/controlplane/onchain_credentials.go index f7e4428..59a3d96 100644 --- a/api/internal/controlplane/onchain_credentials.go +++ b/api/internal/controlplane/onchain_credentials.go @@ -95,7 +95,7 @@ func (s *Server) onchainCredentials(w http.ResponseWriter, r *http.Request) { s.databaseError(w, e) return } - respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, CredentialVersion: m.CredentialVersion, OnchainGeneration: in.OnchainGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) + respond(w, 200, orchestrator.Grant{Association: orchestrator.Association{Launch: in.Launch, NodeID: m.NodeID, CredentialVersion: m.CredentialVersion, OnchainGeneration: in.OnchainGeneration, ConfigDigest: in.ConfigDigest, GrantID: id}, RequireState: initialized, RPCURL: string(rpc), Headers: "Authorization: Bearer " + s.submissionToken(id)}) } func (s *Server) redemptionAuthorize(w http.ResponseWriter, r *http.Request) { diff --git a/api/internal/controlplane/onchain_test.go b/api/internal/controlplane/onchain_test.go index 9f078f6..0b9d6f9 100644 --- a/api/internal/controlplane/onchain_test.go +++ b/api/internal/controlplane/onchain_test.go @@ -143,6 +143,9 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 200 { t.Fatal("refresh revoked retained grant") } + if _, e = s.db.Exec(`UPDATE lpcc.onchain_state SET initialized=true WHERE fingerprint=$1`, strings.Repeat("a", 64)); e != nil { + t.Fatal(e) + } if e = s.RetireMachine(t.Context(), node); e != nil { t.Fatal(e) } @@ -153,6 +156,16 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { if fresh["node_id"] == machine["node_id"] { t.Fatal("enrollment not replaced") } + inherited, err := loadOnchain(t.Context(), s.db, fresh["node_id"]) + inheritedJSON, _ := json.Marshal(inherited) + configJSON, _ := json.Marshal(cfg) + if err != nil || string(inheritedJSON) != string(configJSON) { + t.Fatal("re-enrollment lost onchain configuration", inherited, err) + } + var initialized bool + if err = s.db.QueryRow(`SELECT initialized FROM lpcc.onchain_state WHERE fingerprint=$1`, strings.Repeat("a", 64)).Scan(&initialized); err != nil || !initialized { + t.Fatal("re-enrollment lost storage identity", err) + } c.Recipient = "0x" + strings.Repeat("3", 40) if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}}, 1); e == nil { t.Fatal("re-enrollment reset pinned recipient") @@ -168,7 +181,6 @@ func TestOnchainActivationAndNormalDrain(t *testing.T) { } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) node = c["node_id"] - node = c["node_id"] if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -234,7 +246,6 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { } c := enroll(t, s, ownerA, strings.Repeat("a", 64)) node = c["node_id"] - node = c["node_id"] var b []byte if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { t.Fatal(e) diff --git a/runtime/orchestrator/integration_test.go b/runtime/orchestrator/integration_test.go index f90ba1e..2c9175c 100644 --- a/runtime/orchestrator/integration_test.go +++ b/runtime/orchestrator/integration_test.go @@ -50,7 +50,7 @@ func integrationFixture(t *testing.T) (*Integration, contract.Metadata, Launch) if p != "onchain/credentials" { t.Fatal(p) } - b, _ := json.Marshal(Grant{Association: Association{Launch: l, CredentialVersion: 1, OnchainGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) + b, _ := json.Marshal(Grant{Association: Association{Launch: l, NodeID: m.NodeID, CredentialVersion: 1, OnchainGeneration: 2, ConfigDigest: m.ConfigDigest, GrantID: "grant"}, RPCURL: "https://rpc.example/secret", Headers: "Authorization: Bearer redemption-secret"}) return b, nil, nil }) return i, m, l diff --git a/ui/src/machine-status.tsx b/ui/src/machine-status.tsx index cc57141..76e6d50 100644 --- a/ui/src/machine-status.tsx +++ b/ui/src/machine-status.tsx @@ -20,7 +20,7 @@ export function machineStatusSummary(machine: { terminal?: boolean; report_state const reasons: Record = { onchain_not_ready: 'Onchain Node is not ready; inspect credential delivery, retained onchain state, RPC and rate source', sandbox_pending: 'Sandbox or Pod network setup is pending', invalid_app_payload: 'Downloaded app input is invalid', - onchain_pending: 'Waiting for the target onchain configuration', onchain_incompatible: 'App price is incompatible with the target onchain mode', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', predecessor_cleanup_pending: 'Previous enrollment cleanup is pending', unverified_provenance: 'Retained inventory has no confirmation for the current source version', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', + onchain_pending: 'Waiting for the target onchain configuration', onchain_incompatible: 'App price is incompatible with the target onchain mode', resource_refused: 'Insufficient resources for this assignment', cleanup_prerequisite: 'Waiting for previous revision cleanup', cleanup_pending: 'Waiting for earlier instance cleanup', generation_failed: 'App configuration could not be rendered', invalid_definition: 'App definition is invalid', unsupported_instance_mode: 'Instance lifetime is not supported', unsupported_stop_signal: 'Configured stop signal is not supported', image_pull_failed: 'Container image could not be pulled', container_start_failed: 'Container could not start', startup_failed: 'Startup deadline expired', readiness_failed: 'Configured readiness check failed', memory_limit: 'Container exceeded its memory limit', scheduling_refused: 'Kubernetes refused scheduling', isolation_failed: 'Sandbox isolation could not start', state_recovery_failed: 'App Reconciler state recovery failed; management repair remains available', registration_reset: 'Node registration was lost or expired', node_registration_recreated: 'Node registration was recreated; previous work is unconfirmed', clock_uncertain: 'Observation clock is uncertain', process_lost: 'App process disappeared', process_failed: 'App process failed', observation_pending: 'App state could not be observed', fetch_or_publication_failed: 'Configuration fetch or artifact publication failed', access_denied: 'Discovery Access authentication was denied', credential_unavailable: 'Discovery credential is unavailable', unreported: 'No observation received', input_regression: 'Older app input was refused', registration_failed: 'Node registration failed', registration_pending: 'Node registration is pending', node_unavailable: 'Node registration service is unreachable', node_request_failed: 'Node rejected the registration request', heartbeat_response: 'Node registration response is invalid', heartbeat_ttl: 'Node registration expiry is invalid', registration_auth_failed: 'Node rejected registration credentials', tls_pending: 'Waiting for TLS', drain_pending: 'Drain or cleanup is pending', runtime_offline: 'Runtime has no fresh report', reconcile_failed: 'Flux resource reconciliation failed', cleanup_failed: 'Resource cleanup failed', ownership_conflict: 'Tunnel resource ownership conflicts', provisioning_pending: 'Tunnel provisioning is pending', denied_destination: 'Discovery destination was refused', dns: 'Discovery DNS lookup failed', timeout: 'Discovery collection timed out', http_error: 'Discovery source returned an error', redirect: 'Discovery source redirected the request', transport_error: 'Discovery source could not be reached', unsupported_stop_signal_field: 'Host does not support the requested stop signal', stop_signal_unverified: 'The configured stop signal could not be verified; admission is withheld', process_failed_to_start: 'App process failed to start', registration_cleanup_failed: 'Registration cleanup failed', clock_state_unavailable: 'Clock state is unavailable', app_cleanup_pending: 'App cleanup remains pending', drain_timeout: 'Drain deadline expired', input_unavailable: 'App input is unavailable', publication_failed: 'App artifact publication failed', serving_failed: 'App artifact serving failed', failed: 'Component reported failure', offline: 'Component has no ready observation', connector_observation_stale: 'No fresh connector readiness observation', applying: 'Resource reconciliation is pending', ready: 'Ready', removed: 'Removed', rollout_pending: 'Waiting for the new configuration to apply', cleanup_unconfirmed: 'Cleanup is unconfirmed', } function reason(code?: string) { return code ? reasons[code] || code.replaceAll('_', ' ') : '' } function date(value?: string | null) { return value && Date.parse(value) > 0 ? new Date(value).toLocaleString() : 'Unobserved' } diff --git a/ui/tests/machine-status.spec.ts b/ui/tests/machine-status.spec.ts index 07f54c4..d132232 100644 --- a/ui/tests/machine-status.spec.ts +++ b/ui/tests/machine-status.spec.ts @@ -211,22 +211,6 @@ for (const admin of [false, true]) test(`${admin ? 'administrator' : 'owner'} ca await expect(page.getByRole('button', { name: 'Assign selected revision', exact: true })).toHaveCount(0) }) -test('expired inventory preserves its unverified source-version explanation', async ({ page }) => { - await page.clock.install() - const state = await setup(page) - const membership = state.view.membership['instance-preserved'] - membership.state = 'unverified_provenance'; membership.provenance_current = false - membership.expires_at = new Date(Date.parse(state.view.server_time) + 1000).toISOString() - await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange'))) - await page.getByText('Instance evidence and correlation (1)').click() - await expect(page.getByText('Retained inventory has no confirmation for the current source version', { exact: false })).toBeVisible() - state.fail = true - await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange'))) - await expect(page.getByText('Status refresh unavailable.', { exact: true })).toBeVisible() - await page.clock.fastForward(2000) - await expect(page.getByText('Retained inventory has no confirmation for the current source version', { exact: false })).toBeVisible() -}) - test('onchain readiness stays separate from remote handoff', async ({ page }) => { await page.clock.install() const state = await setup(page, false) From 37edb5220206d026eaea0805bbd4528de6f79a3c Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:26:54 -0800 Subject: [PATCH 12/15] Fix enrollment bootstrap and retained cleanup fallbacks --- .../controlplane/machineconfig/apps.go | 4 +--- .../controlplane/machineconfig/apps_test.go | 24 +++++++++++++++++++ .../controlplane/machineconfig/bundle_test.go | 11 +++++++++ .../machineconfig/onchain_test.go | 2 +- .../templates/system/node/orchestrator.yaml | 5 ++-- runtime/bootstrap-livepeer.sh | 16 +++++++------ runtime/lib/credentials.sh | 10 +++++++- runtime/tests/test_credentials.py | 20 ++++++++++++---- 8 files changed, 73 insertions(+), 19 deletions(-) diff --git a/api/internal/controlplane/machineconfig/apps.go b/api/internal/controlplane/machineconfig/apps.go index 964726f..e86e34f 100644 --- a/api/internal/controlplane/machineconfig/apps.go +++ b/api/internal/controlplane/machineconfig/apps.go @@ -50,12 +50,10 @@ func (s *Manager) prepareApps(ctx context.Context, m *Desired, lookupErr error) } var prior []byte query := `SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1` - args := []any{m.NodeID} if m.Terminal { query = `SELECT retained_bundle FROM lpcc.enrollments WHERE node_id=$1` - args = append(args, m.NodeID) } - if s.store.DB.QueryRowContext(ctx, query, args...).Scan(&prior) == nil { + if s.store.DB.QueryRowContext(ctx, query, m.NodeID).Scan(&prior) == nil { if files, e := artifact.Read(prior); e == nil { if metadata, e := transport.ReadMetadata(files["runtime.json"]); e == nil && metadata.NodeID == m.NodeID { if old, e := appbundle.Read(files, metadata); e == nil { diff --git a/api/internal/controlplane/machineconfig/apps_test.go b/api/internal/controlplane/machineconfig/apps_test.go index 6b889d5..90334a4 100644 --- a/api/internal/controlplane/machineconfig/apps_test.go +++ b/api/internal/controlplane/machineconfig/apps_test.go @@ -2,6 +2,9 @@ package machineconfig import ( "encoding/json" + "errors" + "github.com/livepeer/control-center/api/internal/testdb" + "github.com/livepeer/control-center/schema" "strings" "testing" "time" @@ -87,3 +90,24 @@ func TestDrainProofDoesNotGainFreshnessFromDeliveryRetry(t *testing.T) { t.Fatal("wrong target accepted") } } + +func TestTerminalAppFallbackRetainsAvailableIntent(t *testing.T) { + db := testdb.Open(t) + if _, err := db.Exec(`CREATE SCHEMA lpcc; CREATE TABLE lpcc.enrollments(node_id TEXT PRIMARY KEY, retained_bundle BYTEA)`); err != nil { + t.Fatal(err) + } + intent := schema.AppAssignmentSetV1{SchemaVersion: 1, NodeID: strings.Repeat("a", 26), Generation: 3, Entries: []schema.AppAssignment{}} + m := Desired{Machine: Machine{NodeID: intent.NodeID, CredentialVersion: 1, InstallDir: "/opt/livepeer", K3sVersion: "v1.37.2+k3s1"}, Apps: &intent, RuntimeImage: "registry.invalid/runtime@sha256:" + strings.Repeat("a", 64)} + bundle, _, err := Build(m) + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec(`INSERT INTO lpcc.enrollments VALUES($1,$2)`, m.NodeID, bundle); err != nil { + t.Fatal(err) + } + m.Terminal = true + New(Config{}, Dependencies{DB: db}).prepareApps(t.Context(), &m, errors.New("lookup unavailable")) + if m.AppsError != "generation_failed" || !m.AppPayload.Index.Available || m.Apps == nil || m.Apps.Generation != intent.Generation { + t.Fatal("lost retained cleanup intent", m.AppsError, m.AppPayload) + } +} diff --git a/api/internal/controlplane/machineconfig/bundle_test.go b/api/internal/controlplane/machineconfig/bundle_test.go index cd09c8d..4aa8713 100644 --- a/api/internal/controlplane/machineconfig/bundle_test.go +++ b/api/internal/controlplane/machineconfig/bundle_test.go @@ -40,6 +40,17 @@ func TestConfigurationBundle(t *testing.T) { if strings.Contains(files["system/node/orchestrator.yaml"], "@INSTALL_DIR@") || strings.Contains(files["system/node/orchestrator.yaml"], "@NODE_ID@") || !strings.Contains(files["system/node/orchestrator.yaml"], "/srv/livepeer/volumes/orchestrator") { t.Fatal("incorrect machine rendering") } + reenrolled := m + reenrolled.NodeID = strings.Repeat("b", 26) + fresh, _, err := Build(reenrolled) + if err != nil { + t.Fatal(err) + } + oldPV := strings.Split(files["system/node/orchestrator.yaml"], "---")[1] + newPV := strings.Split(archiveFiles(t, fresh)["system/node/orchestrator.yaml"], "---")[1] + if oldPV != newPV { + t.Fatal("re-enrollment changed the retained local volume") + } if !strings.Contains(files["upgrade-plan/plan.yaml"], m.K3sVersion) { t.Fatal("upgrade plan version missing") } diff --git a/api/internal/controlplane/machineconfig/onchain_test.go b/api/internal/controlplane/machineconfig/onchain_test.go index ea43b07..2e69187 100644 --- a/api/internal/controlplane/machineconfig/onchain_test.go +++ b/api/internal/controlplane/machineconfig/onchain_test.go @@ -82,7 +82,7 @@ func TestOnchainBundleDeterminismCredentialRotationAndHeldIdentity(t *testing.T) t.Fatal("management refresh did not schedule Node drain and replacement") } refreshed = m - refreshed.NodeID = "22222222-2222-4222-8222-222222222222" + refreshed.NodeID = strings.Repeat("b", 26) if Digest(refreshed) == original { t.Fatal("re-enrollment reused a previous lifetime's Node workload") } diff --git a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml index ca225f2..8fb1fde 100644 --- a/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml +++ b/api/internal/controlplane/machineconfig/templates/system/node/orchestrator.yaml @@ -29,9 +29,7 @@ spec: nodeSelectorTerms: - matchExpressions: - key: livepeer.io/node-id - operator: In - values: - - '@NODE_ID@' + operator: Exists --- apiVersion: v1 kind: PersistentVolumeClaim @@ -92,6 +90,7 @@ spec: labels: app: orchestrator spec: + nodeSelector: {livepeer.io/node-id: '@NODE_ID@'} automountServiceAccountToken: false securityContext: runAsNonRoot: true diff --git a/runtime/bootstrap-livepeer.sh b/runtime/bootstrap-livepeer.sh index 0ce83b2..96e3a76 100755 --- a/runtime/bootstrap-livepeer.sh +++ b/runtime/bootstrap-livepeer.sh @@ -76,16 +76,17 @@ parse_args() { # Enrollment credentials are separate from the short-lived bootstrap JWT. # Reruns reuse the saved machine credential and never require another JWT. authenticate_node() { - local credentials="$INSTALL_DIR/credentials" key fingerprint request response api status - NODE_ID=''; SERVICE_TOKEN=''; CONFIG_URL=''; IDENTITY_NODE_ID=''; CREDENTIAL_VERSION=0 + local credentials="$INSTALL_DIR/credentials" key request response api status + NODE_ID=''; SERVICE_TOKEN=''; CONFIG_URL=''; IDENTITY_NODE_ID=''; INSTALLATION_FINGERPRINT=''; CREDENTIAL_VERSION=0 if [[ -f "$INSTALL_DIR/state/enrolled" ]] || { managed_installation && [[ -f "$credentials/node-id" && -f "$credentials/service-token" && -f "$credentials/config-url" && -f "$credentials/identity.json" ]]; }; then - for key in node-id service-token config-url; do + for key in node-id service-token config-url fingerprint; do [[ -f "$credentials/$key" && -s "$credentials/$key" ]] || die "saved credential is missing or invalid: $key; restore it from backup" done if [[ -f "$INSTALL_DIR/state/enrolled" || -e "$credentials/runner-bootstrap.secret" ]]; then [[ -f "$credentials/runner-bootstrap.secret" && -s "$credentials/runner-bootstrap.secret" ]] || die 'runner bootstrap credential is missing or invalid; restore it from backup' fi NODE_ID=$(cat "$credentials/node-id") + INSTALLATION_FINGERPRINT=$(cat "$credentials/fingerprint") SERVICE_TOKEN=$(cat "$credentials/service-token") CONFIG_URL=$(cat "$credentials/config-url") if [[ ! -s "$credentials/identity.json" ]] || ! read_identity "$(cat "$credentials/identity.json")"; then @@ -99,9 +100,9 @@ authenticate_node() { [[ "$api" =~ ^https?://[a-zA-Z0-9_.:-]+(/[a-zA-Z0-9_.-]+)*$ ]] || die 'set LIVEPEER_API_URL to the enrollment API base URL' [[ "$api" == https://* || ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} == 1 ]] || die 'enrollment requires HTTPS; development HTTP must be explicit' [[ -s /etc/machine-id ]] || die '/etc/machine-id must be initialized' - fingerprint=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum) - fingerprint=${fingerprint:0:64} - request=$(jq -nc --arg fingerprint "$fingerprint" --arg hostname "$(hostname)" \ + INSTALLATION_FINGERPRINT=$(printf '%s' "$(cat /etc/machine-id)" | sha256sum) + INSTALLATION_FINGERPRINT=${INSTALLATION_FINGERPRINT:0:64} + request=$(jq -nc --arg fingerprint "$INSTALLATION_FINGERPRINT" --arg hostname "$(hostname)" \ --arg install_dir "$INSTALL_DIR" --arg k3s_version "$K3S_VERSION" --argjson development_http "${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0}" \ '{fingerprint:$fingerprint,hostname:$hostname,install_dir:$install_dir,k3s_version:$k3s_version,development_http:($development_http==1)}') log 'Registering machine with the Livepeer API.' @@ -125,8 +126,8 @@ authenticate_node() { if [[ ${LIVEPEER_ALLOW_DEVELOPMENT_HTTP:-0} != 1 ]]; then [[ "$CONFIG_URL" == "$api/v1/nodes/$NODE_ID/config" ]] || die 'enrollment returned invalid HTTPS configuration URL' fi - printf '%s' "$fingerprint" | atomic_write "$credentials/fingerprint" fi + [[ "$INSTALLATION_FINGERPRINT" =~ ^[a-f0-9]{64}$ ]] || die 'invalid installation fingerprint' [[ "$IDENTITY_NODE_ID" == "$NODE_ID" ]] || die 'saved identity does not match the node' [[ "$NODE_ID" =~ ^[a-z2-7]{26}$ && "$SERVICE_TOKEN" =~ ^[a-f0-9]{64}$ ]] || die 'invalid enrollment credentials' [[ "$CONFIG_URL" =~ ^https?://[a-zA-Z0-9/_.:-]+$ ]] || die 'invalid configuration URL' @@ -178,6 +179,7 @@ prepare_installation() { "$INSTALL_DIR/volumes/management-sockets/connector" "$INSTALL_DIR/volumes/management-sockets/apps" "$INSTALL_DIR/volumes/management-sockets/orchestrator" printf '%s\n' "$RUNTIME_IMAGE" | atomic_write "$INSTALL_DIR/state/runtime-image" chmod 0700 "$INSTALL_DIR/k3s" "$INSTALL_DIR/kubelet" + write_once "$INSTALL_DIR/credentials/fingerprint" "$INSTALLATION_FINGERPRINT" write_once "$INSTALL_DIR/credentials/node-id" "$NODE_ID" write_once "$INSTALL_DIR/credentials/service-token" "$SERVICE_TOKEN" write_once "$INSTALL_DIR/credentials/config-url" "$CONFIG_URL" diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index 3f93656..b19be34 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -85,7 +85,7 @@ stop_credential_consumers() { } transition_credentials() { - local api fingerprint operation expected response status request metadata previous_node issued_node apps replicas + local api fingerprint operation expected response status request metadata previous_node issued_node apps replicas cluster_node managed_installation || die 'credential transition requires an initialized installation' [[ -s "$INSTALL_DIR/credentials/runner-bootstrap.secret" ]] || die 'restore the runner bootstrap credential before changing credentials' runtime_image @@ -115,6 +115,10 @@ transition_credentials() { previous_node=$(jq -er '.previous_node' <<< "$metadata") [[ "$previous_node" =~ ^[a-z2-7]{26}$ ]] || die 'invalid previous enrollment identity' jq -e '.expected | type == "number" and . >= 1' <<< "$metadata" >/dev/null || die 'invalid credential transition version' + if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then + cluster_node=$(kube get nodes -o name) + [[ "$cluster_node" == node/* && "$cluster_node" != *$'\n'* ]] || die 're-enrollment requires exactly one Kubernetes node' + fi stop_credential_consumers install -d -m 0700 "$INSTALL_DIR/volumes/app-reconciler" chown 65532:65532 "$INSTALL_DIR/volumes/app-reconciler" @@ -168,6 +172,10 @@ transition_credentials() { [[ "$IDENTITY_NODE_ID" == "$NODE_ID" ]] || die 'credential identity does not match the node' printf '%s' "$NODE_ID" | atomic_write "$INSTALL_DIR/credentials/node-id" save_identity + if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then + render_template "$SCRIPT_DIR/config/k3s.yaml" "$INSTALL_DIR/config/k3s.yaml" + kube label "$cluster_node" "livepeer.io/node-id=$NODE_ID" --overwrite + fi stage_manifests install_machine_secret if [[ "$CREDENTIAL_TRANSITION" == reenroll ]]; then diff --git a/runtime/tests/test_credentials.py b/runtime/tests/test_credentials.py index 53b76a6..78ae4a2 100644 --- a/runtime/tests/test_credentials.py +++ b/runtime/tests/test_credentials.py @@ -16,7 +16,7 @@ def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) - for name in ('credentials', 'state', 'volumes/http-source'): + for name in ('credentials', 'state', 'config', 'volumes/http-source'): (self.root / name).mkdir(parents=True, exist_ok=True) (self.root / 'credentials/node-id').write_text('a' * 26) (self.root / 'credentials/fingerprint').write_text('a' * 64) @@ -26,7 +26,7 @@ def setUp(self): (self.root / 'credentials/identity.json').write_text(json.dumps({'node_id': 'a' * 26, 'credential_version': 1})) (self.root / 'state/k3s-version').write_text('v1.37.10+k3s1') - def transition(self, fail='', mode='refresh', node='c' * 26): + def transition(self, fail='', mode='refresh', node='c' * 26, nodes='node/worker'): script = r''' set -Eeuo pipefail source "$1" @@ -49,6 +49,7 @@ def transition(self, fail='', mode='refresh', node='c' * 26): sha256sum() { command cat >/dev/null; printf '%s\n' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; } kube() { printf 'kube %s\n' "$*" >> "$INSTALL_DIR/steps" + if [[ "$*" == 'get nodes -o name' ]]; then printf '%s' "$TEST_NODES"; fi if [[ "$*" == *'get deployment/kustomize-controller'* ]]; then printf '1'; fi if [[ "$FAIL_AT" == stop && "$*" == *'wait pod'* ]]; then return 1; fi if [[ "$FAIL_AT" == artifact && "$*" == *'wait externalartifact/livepeer-service'* ]]; then return 1; fi @@ -82,8 +83,8 @@ def transition(self, fail='', mode='refresh', node='c' * 26): } transition_credentials ''' - return subprocess.run(['bash', '-c', script, 'fixture', str(LIBRARY), str(self.root)], - env={**os.environ, 'FAIL_AT': fail, 'TEST_MODE': mode, 'TEST_NODE': ('a' * 26 if mode == 'refresh' else node)}, + return subprocess.run(['bash', '-c', script, 'fixture', str(LIBRARY.parent.parent / 'bootstrap-livepeer.sh'), str(self.root)], + env={**os.environ, 'FAIL_AT': fail, 'TEST_MODE': mode, 'TEST_NODE': ('a' * 26 if mode == 'refresh' else node), 'TEST_NODES': nodes}, text=True, capture_output=True) def test_identity_requires_base32_node_and_positive_numeric_version(self): @@ -159,9 +160,20 @@ def test_reenrollment_stops_prior_node_before_issuing_credentials(self): result = self.transition(mode='reenroll') self.assertEqual(result.returncode, 0, result.stderr) steps = (self.root / 'steps').read_text().splitlines() + self.assertIn('livepeer.io/node-id=' + 'c' * 26, (self.root / 'config/k3s.yaml').read_text()) + relabel = steps.index('kube label node/worker livepeer.io/node-id=' + 'c' * 26 + ' --overwrite') + self.assertLess(relabel, steps.index('https-code')) stopped = next(i for i, x in enumerate(steps) if 'wait pod -l app=orchestrator' in x) self.assertLess(stopped, steps.index('refresh')) + def test_reenrollment_rejects_empty_or_multinode_clusters_before_issuance(self): + for nodes in ('', 'node/one\nnode/two'): + result = self.transition(mode='reenroll', nodes=nodes) + self.assertNotEqual(result.returncode, 0) + self.assertIn('exactly one', result.stderr) + self.assertFalse((self.root / 'requests').exists()) + self.assertEqual((self.root / 'credentials/node-id').read_text(), 'a' * 26) + def test_refresh_keeps_node_for_authoritative_managed_drain(self): result = self.transition() self.assertEqual(result.returncode, 0, result.stderr) From 0629f87315c781e90dd76eab0e2ec2225ef32418 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:28:24 -0800 Subject: [PATCH 13/15] Use base32 identities in remaining bundle fixture --- runtime/appbundle/bundle_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/appbundle/bundle_test.go b/runtime/appbundle/bundle_test.go index 16be0c2..0623eb8 100644 --- a/runtime/appbundle/bundle_test.go +++ b/runtime/appbundle/bundle_test.go @@ -76,7 +76,7 @@ func TestPayloadValidationAndUnsupportedSettings(t *testing.T) { t.Fatal("accepted changed resource") } p, _ = Render(set, Options{}) - m.NodeID = "33333333-3333-4333-8333-333333333333" + m.NodeID = strings.Repeat("c", 26) if _, err := Read(p.Files, m); err == nil { t.Fatal("accepted foreign enrollment") } From 5d27bab24e27f482d557f17f3fb6acf82af6519b Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:37:06 -0800 Subject: [PATCH 14/15] Remove outdated documentation references --- docs/fleet-discovery.md | 14 +++++--------- docs/machine-tunnels.md | 11 ++++------- docs/operations.md | 4 ++-- runtime/README.md | 4 ---- 4 files changed, 11 insertions(+), 22 deletions(-) diff --git a/docs/fleet-discovery.md b/docs/fleet-discovery.md index c72f6d5..7986da4 100644 --- a/docs/fleet-discovery.md +++ b/docs/fleet-discovery.md @@ -41,9 +41,8 @@ withdraws the source immediately. An empty selection is valid. Unverified provisioning generations are excluded; previously approved offline generations continue polling, including after restart. Draining sources remain selected to observe withdrawals. Removed enrollments and blocked ingress are -excluded. Re-enrollment has a fresh node ID and endpoint. Removing the old -source removes its cached inventory; an unverified replacement stays excluded. Follow the tunnel runbook's drain, acknowledgement and -provider cleanup order before retiring resources. +excluded. Removing a source removes its cached inventory. Follow the tunnel +runbook's drain, acknowledgement and provider cleanup order before retirement. Credentials are immutable, AES-GCM encrypted PostgreSQL versions; only the keyring is mounted as a protected file. Reconciliation loads a source-scoped @@ -55,16 +54,13 @@ there is no plaintext credential export or unauthenticated fallback. Requests use verified TLS, a three-second timeout, no environment proxy, cookies or redirects, and Node's destination policy and 1 MiB source-body limit. The Collector ignores advertised peer metadata and never collects its own origin. -Credential changes apply to the next scheduled poll. Existing snapshots retain -their original times across credential rotation. HTTP reads never poll sources. +Credential changes apply to the next scheduled poll. HTTP reads never poll sources. For ordinary Access rotation, publish the new credential with provider overlap as described in the tunnel runbook. Confirm discovery acknowledgement and subsequent provider retirement before finishing. Acknowledgement requires a new, -successfully decoded response using the current source credential with the -expected owning address. The transport validates bounded response bytes using -Node's shared codec; the Collector independently owns cached observations. An old in-flight response, login HTML -or eviction cannot acknowledge it; an unsafe app URL alone does not block +successfully decoded response using the current credential and expected owning +address. An old in-flight response, login HTML or eviction cannot acknowledge it; an unsafe app URL alone does not block retirement. Use the runbook's compromise path for immediate revocation and its controlled restart/re-encryption procedure for keyring rotation. diff --git a/docs/machine-tunnels.md b/docs/machine-tunnels.md index e780ef4..f710c66 100644 --- a/docs/machine-tunnels.md +++ b/docs/machine-tunnels.md @@ -83,11 +83,8 @@ Cloudflare. See ## Enrollment, refresh and status -Node IDs are lowercase, unpadded base32 encodings of 128 random bits. Active -registration retries retain the node ID; credential refresh changes only its -credential version. Re-enrollment creates a fresh node ID and tunnel UUID. -The full installation fingerprint associates persistent payment infrastructure -with the installation; cleanup and credentials remain scoped to the node ID. +Active registration retries and credential refresh retain the node ID. +Re-enrollment creates a fresh node ID and tunnel UUID. Cloudflare Tunnel must be the HTTPS front door, with the API origin reachable only through the trusted connector. The API does not infer transport security from arbitrary forwarded headers. HTTPS enrollment is eligible even when @@ -184,8 +181,8 @@ start a fresh drain with `drain/retry`, or deliberately remove with `force:true` Deletion denies token delivery, installs deny-only ingress, revokes connector authentication before disconnecting, deletes DNS/tunnel resources before Access protection, and revokes source tokens. -Cleanup proceeds even with the machine offline. Each enrollment has its own hostname namespace, so late cleanup of a retired -node cannot delete a replacement node's routes or certificates. +Cleanup proceeds even with the machine offline. Retired-node cleanup cannot +delete a replacement node's routes or certificates. The terminal artifact prunes the connector and orchestrator and delivers app-removal intents; Runtime cleans up assigned apps. diff --git a/docs/operations.md b/docs/operations.md index 35c0deb..ee531b8 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -72,8 +72,8 @@ cleanup contract. ## Onchain operation Configure the redeemer and secret mounts using [deployment setup](../deploy/README.md#onchain-setup). -Edit [onchain.example.json](../deploy/onchain.example.json) and apply it from the -API deployment environment: +Key [onchain.example.json](../deploy/onchain.example.json) with `credentials/fingerprint`. +Apply from the API deployment: ```sh controlcenter onchain apply --config /etc/controlcenter/config.toml \ diff --git a/runtime/README.md b/runtime/README.md index 92f578c..027b441 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -122,10 +122,6 @@ environment variable as shown in Quick start. Backend `PUBLIC_API_URL` must use the same reachable base URL. The installer rejects literal loopback configuration URLs because pods cannot use host loopback. -Each enrollment receives a fresh random base32 node ID. Registration retries -and credential refresh preserve that ID. Re-enrollment keeps payment continuity -through the full installation fingerprint and gives cleanup a separate node ID. - The one-hour bootstrap JWT can enroll multiple machines. The installer saves long-lived service credentials in owner-only files and reuses them on reruns, even after the JWT expires. A fresh registration retry requires the original From d1d269e23199e59a51effefe9ff93b46ac7b991a Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Thu, 12 Nov 2026 09:48:17 -0800 Subject: [PATCH 15/15] Remove duplicate enrollment identity bookkeeping --- api/internal/controlplane/assignments.go | 2 +- .../controlplane/controlplane_test.go | 2 +- .../controlplane/machineconfig/apps.go | 2 +- api/internal/controlplane/onchain_test.go | 67 ++++++++----------- runtime/appreconciler/owner_test.go | 2 +- runtime/lib/credentials.sh | 2 - 6 files changed, 32 insertions(+), 45 deletions(-) diff --git a/api/internal/controlplane/assignments.go b/api/internal/controlplane/assignments.go index 2694c7a..950a36e 100644 --- a/api/internal/controlplane/assignments.go +++ b/api/internal/controlplane/assignments.go @@ -333,7 +333,7 @@ func (s *Server) prepareAssignment(r *http.Request, _ UserIdentity) (AdminApply, if changed { status = 202 } - return AdminChange{Target: AdminTarget{Kind: "machine_app", ID: node + ":" + node + ":" + id, Revision: auditRevision}, Changed: changed, Status: status, Body: map[string]any{"changed": changed, "node_id": node, "assignments": versions}}, nil + return AdminChange{Target: AdminTarget{Kind: "machine_app", ID: node + ":" + id, Revision: auditRevision}, Changed: changed, Status: status, Body: map[string]any{"changed": changed, "node_id": node, "assignments": versions}}, nil }, nil } diff --git a/api/internal/controlplane/controlplane_test.go b/api/internal/controlplane/controlplane_test.go index 72542eb..381f87c 100644 --- a/api/internal/controlplane/controlplane_test.go +++ b/api/internal/controlplane/controlplane_test.go @@ -184,7 +184,7 @@ func credentials(t *testing.T, data []byte) map[string]string { } result := map[string]string{} var resultValue string - for _, key := range []string{"node_id", "node_id", "token", "config_url"} { + for _, key := range []string{"node_id", "token", "config_url"} { if err := json.Unmarshal(raw[key], &resultValue); err != nil { t.Fatal(err) } diff --git a/api/internal/controlplane/machineconfig/apps.go b/api/internal/controlplane/machineconfig/apps.go index e86e34f..b30f2f6 100644 --- a/api/internal/controlplane/machineconfig/apps.go +++ b/api/internal/controlplane/machineconfig/apps.go @@ -12,7 +12,7 @@ import ( ) func DrainTarget(node string, state State) string { - return artifact.Digest([]byte(fmt.Sprintf("%s/%s/%d/%s/%s", node, node, state.Generation, state.PendingConfigDigest, state.Target))) + return artifact.Digest([]byte(fmt.Sprintf("%s/%d/%s/%s", node, state.Generation, state.PendingConfigDigest, state.Target))) } func (s *Manager) connectorSettings(m Machine, record *Record) { if m.Terminal { diff --git a/api/internal/controlplane/onchain_test.go b/api/internal/controlplane/onchain_test.go index 0b9d6f9..69a58c0 100644 --- a/api/internal/controlplane/onchain_test.go +++ b/api/internal/controlplane/onchain_test.go @@ -28,8 +28,8 @@ func onchainSettings(t *testing.T, s *Server) onchain.Config { func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) - node := strings.Repeat("a", 64) - in := onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}} + fingerprint := strings.Repeat("a", 64) + in := onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: c}} if rev, e := s.applyOnchain(t.Context(), in, 0); e != nil || rev != 1 { t.Fatal(rev, e) } @@ -41,7 +41,7 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { } stale := c stale.CredentialRevision++ - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): stale}}, 0); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: stale}}, 0); e == nil { t.Fatal("stale edit accepted") } var n int @@ -56,7 +56,7 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { for _, mutate := range []func(*onchain.Config){func(c *onchain.Config) { c.Recipient = "0x" + strings.Repeat("3", 40) }, func(c *onchain.Config) { c.ChainID++ }, func(c *onchain.Config) { c.TicketWinProb = "0" }} { next := c mutate(&next) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): next}}, 1); e == nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: next}}, 1); e == nil { t.Fatal("invalid change accepted") } } @@ -73,9 +73,10 @@ func TestOnchainApplyAtomicBindingAndSecretVersions(t *testing.T) { func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) - machine := enroll(t, s, ownerA, strings.Repeat("a", 64)) + fingerprint := strings.Repeat("a", 64) + machine := enroll(t, s, ownerA, fingerprint) node := machine["node_id"] - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}}, 0); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: c}}, 0); e != nil { t.Fatal(e) } cfg, e := loadOnchain(t.Context(), s.db, node) @@ -143,7 +144,7 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 200 { t.Fatal("refresh revoked retained grant") } - if _, e = s.db.Exec(`UPDATE lpcc.onchain_state SET initialized=true WHERE fingerprint=$1`, strings.Repeat("a", 64)); e != nil { + if _, e = s.db.Exec(`UPDATE lpcc.onchain_state SET initialized=true WHERE fingerprint=$1`, fingerprint); e != nil { t.Fatal(e) } if e = s.RetireMachine(t.Context(), node); e != nil { @@ -152,7 +153,7 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { if webhook(c.Recipient, h, s.params.OnchainWebhookSecret) != 403 { t.Fatal("forced retirement did not revoke") } - fresh := enroll(t, s, ownerA, strings.Repeat("a", 64)) + fresh := enroll(t, s, ownerA, fingerprint) if fresh["node_id"] == machine["node_id"] { t.Fatal("enrollment not replaced") } @@ -163,11 +164,11 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { t.Fatal("re-enrollment lost onchain configuration", inherited, err) } var initialized bool - if err = s.db.QueryRow(`SELECT initialized FROM lpcc.onchain_state WHERE fingerprint=$1`, strings.Repeat("a", 64)).Scan(&initialized); err != nil || !initialized { + if err = s.db.QueryRow(`SELECT initialized FROM lpcc.onchain_state WHERE fingerprint=$1`, fingerprint).Scan(&initialized); err != nil || !initialized { t.Fatal("re-enrollment lost storage identity", err) } c.Recipient = "0x" + strings.Repeat("3", 40) - if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): c}}, 1); e == nil { + if _, e = s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: c}}, 1); e == nil { t.Fatal("re-enrollment reset pinned recipient") } } @@ -175,12 +176,12 @@ func TestOnchainCredentialsWebhookAndRevocation(t *testing.T) { func TestOnchainActivationAndNormalDrain(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := strings.Repeat("a", 64) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { + fingerprint := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: cfg}}, 0); e != nil { t.Fatal(e) } - c := enroll(t, s, ownerA, strings.Repeat("a", 64)) - node = c["node_id"] + c := enroll(t, s, ownerA, fingerprint) + node := c["node_id"] if e := s.reconcile(t.Context()); e != nil { t.Fatal(e) } @@ -240,12 +241,12 @@ func TestOnchainActivationAndNormalDrain(t *testing.T) { func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := strings.Repeat("a", 64) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { + fingerprint := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: cfg}}, 0); e != nil { t.Fatal(e) } - c := enroll(t, s, ownerA, strings.Repeat("a", 64)) - node = c["node_id"] + c := enroll(t, s, ownerA, fingerprint) + node := c["node_id"] var b []byte if e := s.db.QueryRow(`SELECT bundle FROM lpcc.machine_configs WHERE node_id=$1`, node).Scan(&b); e != nil { t.Fatal(e) @@ -321,11 +322,11 @@ func TestObservedGrantCannotRevokeANewerProcessGrant(t *testing.T) { func TestOnchainIsolationAndGenericCatalogCompatibility(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - onchainNode := strings.Repeat("a", 64) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{onchainNode: cfg}}, 0); e != nil { + fingerprint := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: cfg}}, 0); e != nil { t.Fatal(e) } - a := enroll(t, s, ownerA, strings.Repeat("a", 64)) + a := enroll(t, s, ownerA, fingerprint) b := enroll(t, s, ownerB, strings.Repeat("b", 64)) adminA(t, s) freeSource := strings.Replace(registryFixture(t), `amount = "0.001"`, `amount = "0"`, 1) @@ -354,13 +355,13 @@ func TestOnchainIsolationAndGenericCatalogCompatibility(t *testing.T) { func TestConcurrentOnchainApplyCannotCommitTwoDifferentTargets(t *testing.T) { s := newTestServer(t) c := onchainSettings(t, s) - node := strings.Repeat("a", 64) + fingerprint := strings.Repeat("a", 64) errors := make(chan error, 2) for n := range 2 { copy := c copy.CredentialRevision = uint64(n + 1) go func() { - _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): copy}}, 0) + _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: copy}}, 0) errors <- e }() } @@ -381,11 +382,11 @@ func TestConcurrentOnchainApplyCannotCommitTwoDifferentTargets(t *testing.T) { func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) { s := newTestServer(t) cfg := onchainSettings(t, s) - node := strings.Repeat("a", 64) - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): cfg}}, 0); e != nil { + fingerprint := strings.Repeat("a", 64) + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: cfg}}, 0); e != nil { t.Fatal(e) } - node = enroll(t, s, ownerA, strings.Repeat("a", 64))["node_id"] + node := enroll(t, s, ownerA, fingerprint)["node_id"] read := func() contract.Metadata { t.Helper() var b []byte @@ -409,7 +410,7 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) if after.ConfigDigest == before.ConfigDigest || !after.Onchain.Onchain() || after.OnchainActive || after.Onchain.Generation != before.Onchain.Generation { t.Fatal("unapproved onchain target could not repair its image under the same onchain binding", after) } - if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{installationFingerprint(t, s, node): onchain.Offchain()}}, 1); e != nil { + if _, e := s.applyOnchain(t.Context(), onchainInput{Version: 1, Machines: map[string]onchain.Config{fingerprint: onchain.Offchain()}}, 1); e != nil { t.Fatal(e) } if e := s.reconcile(t.Context()); e != nil { @@ -419,15 +420,3 @@ func TestUnapprovedOnchainStartupCanRepairItsImageButCannotDisable(t *testing.T) t.Fatal("failed onchain startup bypassed normal drain to offchain") } } - -func installationFingerprint(t *testing.T, s *Server, node string) string { - t.Helper() - if fingerprintPattern.MatchString(node) { - return node - } - var fingerprint string - if err := s.db.QueryRow(`SELECT fingerprint FROM lpcc.enrollments WHERE node_id=$1`, node).Scan(&fingerprint); err != nil { - t.Fatal(err) - } - return fingerprint -} diff --git a/runtime/appreconciler/owner_test.go b/runtime/appreconciler/owner_test.go index 9e3e944..4b84eec 100644 --- a/runtime/appreconciler/owner_test.go +++ b/runtime/appreconciler/owner_test.go @@ -446,7 +446,7 @@ func TestNativeRestoredMembershipRejectionPreservesSibling(t *testing.T) { controller, _, _, _, _, _ := fixtureController(t) controller.Now = nil if err := controller.Journal.Update(func(s *State) error { - s.Identity.RunnerID, s.Identity = r.Identity.RunnerID, r.Identity + s.Identity = r.Identity s.Instances["one"] = &Instance{ID: "one", PodUID: "pod"} return nil }); err != nil { diff --git a/runtime/lib/credentials.sh b/runtime/lib/credentials.sh index b19be34..973393a 100644 --- a/runtime/lib/credentials.sh +++ b/runtime/lib/credentials.sh @@ -129,8 +129,6 @@ transition_credentials() { printf '%s\n' "$RUNTIME_IMAGE" | atomic_write "$INSTALL_DIR/state/runtime-image" LIVEPEER_ALLOW_DEVELOPMENT_HTTP=0 CONFIG_URL="$api/v1/nodes/$NODE_ID/config" - # Publish HTTPS-enforcing source files and settings before releasing credentials. - # The Deployment remains scaled to zero until the complete new manifest applies. if [[ "$CREDENTIAL_TRANSITION" == refresh ]]; then request=$(jq -nc --arg fingerprint "$fingerprint" --arg install_dir "$INSTALL_DIR" \ --arg operation_id "$(jq -r '.operation' <<< "$metadata")" --argjson expected "$(jq -r '.expected' <<< "$metadata")" \