From 519088b9bad13989736d76606e6ef93f61c26c63 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:28:52 +1100 Subject: [PATCH] Add restore-from-testing endpoint using a recorded previous environment --- README.md | 6 +- internal/cli/cli.go | 1 + internal/cli/cli_test.go | 25 ++++++ internal/cli/resources.go | 13 ++- internal/database/database_test.go | 70 +++++++++++++++ internal/database/migrate_test.go | 10 ++- internal/database/nodes.go | 107 ++++++++++++++++------- internal/server/auth_test.go | 43 +++++++++ internal/server/handlers.go | 14 +++ internal/server/server.go | 2 + internal/server/server_test.go | 20 +++++ migrations/0002_previous_environment.sql | 2 + pkg/client/client.go | 6 ++ pkg/client/client_test.go | 14 +++ pkg/models/models.go | 3 + 15 files changed, 296 insertions(+), 40 deletions(-) create mode 100644 migrations/0002_previous_environment.sql diff --git a/README.md b/README.md index 3eb0878..24038d1 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,9 @@ token is either the static `ENCAPI_WRITE_TOKEN` or a Vault identity JWT from - aud `encapi` (`ENCAPI_OIDC_AUDIENCE`): full write access, like the static token. - aud `encapi-testing` (`ENCAPI_OIDC_TESTING_AUDIENCE`): only - `PUT /api/v1/nodes/{certname}/environment` with `{"environment":"testing"}`; - any other environment or write route returns 403. + `PUT /api/v1/nodes/{certname}/environment` with `{"environment":"testing"}` + and `DELETE /api/v1/nodes/{certname}/environment/testing`; any other + environment or write route returns 403. An unreachable issuer returns 503 for JWTs; the static token keeps working. @@ -80,6 +81,7 @@ GET /api/v1/nodes list nodes GET /api/v1/nodes/{certname} get node PUT /api/v1/nodes/{certname} upsert node (token) PUT /api/v1/nodes/{certname}/environment set only the environment, {"environment":"…"}; 404 if unknown (token, or testing JWT for "testing") +DELETE /api/v1/nodes/{certname}/environment/testing restore the environment held before testing; 409 if not in testing or none recorded (token or testing JWT) DELETE /api/v1/nodes/{certname} delete node (token) GET /api/v1/nodes/{certname}/enc reshaped ENC (YAML) GET /cblr/svc/op/puppet/hostname/{h} cobbler-wire ENC (YAML) diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 1986fe9..0f80a4e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -38,6 +38,7 @@ Usage: encapi-cli node get encapi-cli node set --role --env [--param k=v ...] encapi-cli node set-env + encapi-cli node restore-env move a testing node back to its previous environment encapi-cli node delete encapi-cli role list encapi-cli role get diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 4f7835a..a924f29 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -95,10 +95,25 @@ func (m *memStore) SetNodeEnvironment(_ context.Context, c, env string) (*models if !ok { return nil, database.ErrNotFound } + if n.Environment != "testing" && env == "testing" { + n.PreviousEnvironment = n.Environment + } n.Environment = env m.nodes[c] = n return &n, nil } +func (m *memStore) RestoreFromTesting(_ context.Context, c string) (*models.Node, error) { + n, ok := m.nodes[c] + if !ok { + return nil, database.ErrNotFound + } + if n.Environment != "testing" { + return nil, database.ErrNotInTesting + } + n.Environment, n.PreviousEnvironment = n.PreviousEnvironment, "" + m.nodes[c] = n + return &n, nil +} func (m *memStore) ListNodes(context.Context) ([]models.Node, error) { out := []models.Node{} for _, n := range m.nodes { @@ -181,6 +196,16 @@ func TestNodeSetEnvKeepsRole(t *testing.T) { if code, _, _ := run(t, env, "node", "set-env", "ghost", "testing"); code == 0 { t.Error("set-env on unknown node should fail") } + + if code, _, errb := run(t, env, "node", "restore-env", "web1.example"); code != 0 { + t.Fatalf("restore-env exit %d: %s", code, errb) + } + if n := store.nodes["web1.example"]; n.Environment != "production" { + t.Errorf("after restore-env node = %+v", n) + } + if code, _, errb := run(t, env, "node", "restore-env", "web1.example"); code == 0 || !strings.Contains(errb, "not in testing") { + t.Errorf("restore-env on non-testing node: exit %d, stderr %q", code, errb) + } } func TestNodeSetRequiresFlags(t *testing.T) { diff --git a/internal/cli/resources.go b/internal/cli/resources.go index cdcbbb6..31d4b1c 100644 --- a/internal/cli/resources.go +++ b/internal/cli/resources.go @@ -12,7 +12,7 @@ import ( func nodeCmd(ctx context.Context, c *client.Client, args []string, stdout, stderr io.Writer) int { if len(args) < 1 { - fmt.Fprintln(stderr, "usage: encapi-cli node ...") + fmt.Fprintln(stderr, "usage: encapi-cli node ...") return 2 } switch args[0] { @@ -47,6 +47,17 @@ func nodeCmd(ctx context.Context, c *client.Client, args []string, stdout, stder } printYAML(stdout, n) return 0 + case "restore-env": + if len(args) != 2 { + fmt.Fprintln(stderr, "usage: encapi-cli node restore-env ") + return 2 + } + n, err := c.RestoreFromTesting(ctx, args[1]) + if err != nil { + return fail(stderr, err) + } + printYAML(stdout, n) + return 0 case "delete": if len(args) != 2 { fmt.Fprintln(stderr, "usage: encapi-cli node delete ") diff --git a/internal/database/database_test.go b/internal/database/database_test.go index 07074e6..9e852eb 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -198,3 +198,73 @@ func TestSetNodeEnvironment(t *testing.T) { t.Errorf("unknown node = %v, want ErrNotFound", err) } } + +func TestRestoreFromTesting(t *testing.T) { + requireDB(t) + clean(t) + seed(t) + ctx := context.Background() + for _, s := range []string{"production", "develop"} { + if err := testDB.UpsertStatus(ctx, &models.Status{Name: s}); err != nil { + t.Fatal(err) + } + } + if err := testDB.UpsertNode(ctx, &models.Node{Certname: "h1", Role: "roles::base", Environment: "production"}); err != nil { + t.Fatal(err) + } + + if _, err := testDB.RestoreFromTesting(ctx, "h1"); !errors.Is(err, ErrNotInTesting) { + t.Errorf("restore non-testing = %v, want ErrNotInTesting", err) + } + if got, err := testDB.SetNodeEnvironment(ctx, "h1", "testing"); err != nil || got.PreviousEnvironment != "production" { + t.Fatalf("set testing = %+v, %v", got, err) + } + // re-entering testing must not overwrite the remembered environment + if got, _ := testDB.SetNodeEnvironment(ctx, "h1", "testing"); got.PreviousEnvironment != "production" { + t.Errorf("repeat set testing previous = %q, want production", got.PreviousEnvironment) + } + got, err := testDB.RestoreFromTesting(ctx, "h1") + if err != nil || got.Environment != "production" || got.PreviousEnvironment != "" || got.Role != "roles::base" { + t.Fatalf("restore = %+v, %v", got, err) + } + if stored, _ := testDB.GetNode(ctx, "h1"); stored.Environment != "production" || stored.PreviousEnvironment != "" { + t.Errorf("stored after restore = %+v", stored) + } + + // leaving testing by any other route clears the remembered environment + _, _ = testDB.SetNodeEnvironment(ctx, "h1", "testing") + if got, _ := testDB.SetNodeEnvironment(ctx, "h1", "develop"); got.PreviousEnvironment != "" { + t.Errorf("leave testing previous = %q, want empty", got.PreviousEnvironment) + } + + // PutNode follows the same rules + n := &models.Node{Certname: "h1", Role: "roles::base", Environment: "testing"} + if err := testDB.UpsertNode(ctx, n); err != nil || n.PreviousEnvironment != "develop" { + t.Fatalf("upsert testing = %+v, %v", n, err) + } + n = &models.Node{Certname: "h1", Role: "roles::base", Environment: "production"} + if err := testDB.UpsertNode(ctx, n); err != nil || n.PreviousEnvironment != "" { + t.Fatalf("upsert production = %+v, %v", n, err) + } + + // a node created straight into testing has nothing to restore + if err := testDB.UpsertNode(ctx, &models.Node{Certname: "h2", Role: "roles::base", Environment: "testing"}); err != nil { + t.Fatal(err) + } + if _, err := testDB.RestoreFromTesting(ctx, "h2"); !errors.Is(err, ErrNoPreviousEnvironment) { + t.Errorf("restore without previous = %v, want ErrNoPreviousEnvironment", err) + } + if _, err := testDB.RestoreFromTesting(ctx, "missing"); !errors.Is(err, ErrNotFound) { + t.Errorf("restore unknown = %v, want ErrNotFound", err) + } + + // deleting the remembered status drops the reference rather than blocking + _, _ = testDB.SetNodeEnvironment(ctx, "h1", "develop") + _, _ = testDB.SetNodeEnvironment(ctx, "h1", "testing") + if err := testDB.DeleteStatus(ctx, "develop"); err != nil { + t.Fatalf("delete remembered status: %v", err) + } + if _, err := testDB.RestoreFromTesting(ctx, "h1"); !errors.Is(err, ErrNoPreviousEnvironment) { + t.Errorf("restore after status delete = %v, want ErrNoPreviousEnvironment", err) + } +} diff --git a/internal/database/migrate_test.go b/internal/database/migrate_test.go index 0cbed17..1913226 100644 --- a/internal/database/migrate_test.go +++ b/internal/database/migrate_test.go @@ -2,13 +2,16 @@ package database import ( "context" + "io/fs" "testing" + + "git.unkin.net/unkin/encapi/migrations" ) // encapi's schema predates schema_migrations, so the first start after this // change re-applies 0001_init against a database that already has the tables. // The file is IF NOT EXISTS-guarded for exactly that: the run must succeed and -// leave only the tracking row behind. +// leave only the tracking rows behind. func TestMigrateAdoptsAnExistingSchema(t *testing.T) { requireDB(t) ctx := context.Background() @@ -27,7 +30,8 @@ func TestMigrateAdoptsAnExistingSchema(t *testing.T) { if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM schema_migrations`).Scan(&n); err != nil { t.Fatalf("count schema_migrations: %v", err) } - if n != 1 { - t.Fatalf("schema_migrations rows = %d, want 1", n) + files, _ := fs.Glob(migrations.FS, "*.sql") + if n != len(files) { + t.Fatalf("schema_migrations rows = %d, want %d", n, len(files)) } } diff --git a/internal/database/nodes.go b/internal/database/nodes.go index 1583737..39068e1 100644 --- a/internal/database/nodes.go +++ b/internal/database/nodes.go @@ -15,6 +15,38 @@ import ( // does not exist. var ErrInvalidReference = errors.New("unknown role or environment") +// ErrNotInTesting is returned when restoring a node that is not in testing. +var ErrNotInTesting = errors.New("node is not in testing") + +// ErrNoPreviousEnvironment is returned when restoring a testing node that has +// no recorded environment to return to. +var ErrNoPreviousEnvironment = errors.New("node has no previous environment to restore") + +const nodeCols = `certname, role, environment, params, COALESCE(previous_environment, '')` + +// prevEnv computes previous_environment for a move to newEnv: entering testing +// remembers the current environment, staying keeps it, leaving clears it. +func prevEnv(newEnv string) string { + return `CASE WHEN ` + newEnv + ` <> 'testing' THEN NULL + WHEN nodes.environment = 'testing' THEN nodes.previous_environment + ELSE nodes.environment END` +} + +func scanNode(row pgx.Row) (*models.Node, error) { + var ( + n models.Node + params []byte + ) + if err := row.Scan(&n.Certname, &n.Role, &n.Environment, ¶ms, &n.PreviousEnvironment); err != nil { + return nil, err + } + var err error + if n.Params, err = unmarshalParams(params); err != nil { + return nil, fmt.Errorf("decode params for node %q: %w", n.Certname, err) + } + return &n, nil +} + // fkErr maps a foreign-key violation to ErrInvalidReference. func fkErr(err error) error { var pgErr *pgconn.PgError @@ -31,15 +63,17 @@ func (db *DB) UpsertNode(ctx context.Context, n *models.Node) error { if err != nil { return fmt.Errorf("marshal params for node %q: %w", n.Certname, err) } - _, err = db.Pool.Exec(ctx, ` + err = db.Pool.QueryRow(ctx, ` INSERT INTO nodes (certname, role, environment, params) VALUES ($1, $2, $3, $4) ON CONFLICT (certname) DO UPDATE SET role = EXCLUDED.role, environment = EXCLUDED.environment, params = EXCLUDED.params, + previous_environment = `+prevEnv("EXCLUDED.environment")+`, updated_at = NOW() - `, n.Certname, n.Role, n.Environment, params) + RETURNING COALESCE(previous_environment, '') + `, n.Certname, n.Role, n.Environment, params).Scan(&n.PreviousEnvironment) if err != nil { return fmt.Errorf("upsert node %q: %w", n.Certname, fkErr(err)) } @@ -49,51 +83,62 @@ func (db *DB) UpsertNode(ctx context.Context, n *models.Node) error { // SetNodeEnvironment changes only a node's environment in a single statement and // returns the updated node, ErrNotFound, or ErrInvalidReference. func (db *DB) SetNodeEnvironment(ctx context.Context, certname, environment string) (*models.Node, error) { - var ( - n models.Node - params []byte - ) - err := db.Pool.QueryRow(ctx, ` - UPDATE nodes SET environment = $2, updated_at = NOW() + n, err := scanNode(db.Pool.QueryRow(ctx, ` + UPDATE nodes SET environment = $2, + previous_environment = `+prevEnv("$2::text")+`, + updated_at = NOW() WHERE certname = $1 - RETURNING certname, role, environment, params - `, certname, environment).Scan(&n.Certname, &n.Role, &n.Environment, ¶ms) + RETURNING `+nodeCols, certname, environment)) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, fmt.Errorf("set environment for node %q: %w", certname, fkErr(err)) } - if n.Params, err = unmarshalParams(params); err != nil { - return nil, fmt.Errorf("decode params for node %q: %w", certname, err) + return n, nil +} + +// RestoreFromTesting moves a testing node back to its previous environment and +// returns it, or ErrNotFound, ErrNotInTesting or ErrNoPreviousEnvironment. +func (db *DB) RestoreFromTesting(ctx context.Context, certname string) (*models.Node, error) { + n, err := scanNode(db.Pool.QueryRow(ctx, ` + UPDATE nodes SET environment = previous_environment, + previous_environment = NULL, + updated_at = NOW() + WHERE certname = $1 AND environment = 'testing' AND previous_environment IS NOT NULL + RETURNING `+nodeCols, certname)) + if errors.Is(err, pgx.ErrNoRows) { + cur, gerr := db.GetNode(ctx, certname) + switch { + case gerr != nil: + return nil, gerr + case cur.Environment != "testing": + return nil, ErrNotInTesting + default: + return nil, ErrNoPreviousEnvironment + } } - return &n, nil + if err != nil { + return nil, fmt.Errorf("restore environment for node %q: %w", certname, err) + } + return n, nil } // GetNode returns a single node or ErrNotFound. func (db *DB) GetNode(ctx context.Context, certname string) (*models.Node, error) { - var ( - n models.Node - params []byte - ) - err := db.Pool.QueryRow(ctx, - `SELECT certname, role, environment, params FROM nodes WHERE certname = $1`, certname, - ).Scan(&n.Certname, &n.Role, &n.Environment, ¶ms) + n, err := scanNode(db.Pool.QueryRow(ctx, `SELECT `+nodeCols+` FROM nodes WHERE certname = $1`, certname)) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, fmt.Errorf("get node %q: %w", certname, err) } - if n.Params, err = unmarshalParams(params); err != nil { - return nil, fmt.Errorf("decode params for node %q: %w", certname, err) - } - return &n, nil + return n, nil } // ListNodes returns all nodes ordered by certname. func (db *DB) ListNodes(ctx context.Context) ([]models.Node, error) { - rows, err := db.Pool.Query(ctx, `SELECT certname, role, environment, params FROM nodes ORDER BY certname`) + rows, err := db.Pool.Query(ctx, `SELECT `+nodeCols+` FROM nodes ORDER BY certname`) if err != nil { return nil, fmt.Errorf("list nodes: %w", err) } @@ -101,17 +146,11 @@ func (db *DB) ListNodes(ctx context.Context) ([]models.Node, error) { out := []models.Node{} for rows.Next() { - var ( - n models.Node - params []byte - ) - if err := rows.Scan(&n.Certname, &n.Role, &n.Environment, ¶ms); err != nil { + n, err := scanNode(rows) + if err != nil { return nil, fmt.Errorf("scan node: %w", err) } - if n.Params, err = unmarshalParams(params); err != nil { - return nil, fmt.Errorf("decode params: %w", err) - } - out = append(out, n) + out = append(out, *n) } return out, rows.Err() } diff --git a/internal/server/auth_test.go b/internal/server/auth_test.go index 249607c..2604395 100644 --- a/internal/server/auth_test.go +++ b/internal/server/auth_test.go @@ -138,3 +138,46 @@ func TestUnknownReferenceIs422(t *testing.T) { } } } + +func TestRestoreFromTestingScopes(t *testing.T) { + ts, f, iss := oidcServer(t) + testingTok := iss.Token(nil, "encapi-testing", "agent", time.Hour) + envURL := ts.URL + "/api/v1/nodes/h1.example/environment" + restore := func(certname, token string) (int, string) { + req, _ := http.NewRequest(http.MethodDelete, ts.URL+"/api/v1/nodes/"+certname+"/environment/testing", nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(body) + } + + if code, body := restore("h1.example", testingTok); code != http.StatusConflict || !strings.Contains(body, "not in testing") { + t.Errorf("restore non-testing: %d %s", code, body) + } + if got := put(t, envURL, testingTok, `{"environment":"testing"}`); got != http.StatusOK { + t.Fatalf("set testing: %d", got) + } + if code, _ := restore("h1.example", ""); code != http.StatusUnauthorized { + t.Errorf("restore without token: %d, want 401", code) + } + if code, body := restore("h1.example", testingTok); code != http.StatusOK || !strings.Contains(body, `"environment":"production"`) { + t.Errorf("testing token restore: %d %s", code, body) + } + if n := f.nodes["h1.example"]; n.Environment != "production" || n.PreviousEnvironment != "" || n.Params["k"] != "v" { + t.Errorf("node after restore = %+v", n) + } + + f.nodes["h2.example"] = models.Node{Certname: "h2.example", Role: "roles::base", Environment: "testing"} + if code, body := restore("h2.example", testingTok); code != http.StatusConflict || !strings.Contains(body, "no previous environment") { + t.Errorf("restore without previous: %d %s", code, body) + } + if code, _ := restore("ghost", "s3cret"); code != http.StatusNotFound { + t.Errorf("restore unknown node: %d, want 404", code) + } +} diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 04d772f..72be289 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -38,6 +38,10 @@ func mapErr(w http.ResponseWriter, err error) { writeError(w, http.StatusUnprocessableEntity, database.ErrInvalidReference.Error()) return } + if errors.Is(err, database.ErrNotInTesting) || errors.Is(err, database.ErrNoPreviousEnvironment) { + writeError(w, http.StatusConflict, err.Error()) + return + } writeError(w, http.StatusInternalServerError, err.Error()) } @@ -244,6 +248,16 @@ func (s *Server) putNodeEnvironment(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, node) } +// restoreFromTesting returns a testing node to the environment it had before. +func (s *Server) restoreFromTesting(w http.ResponseWriter, r *http.Request) { + node, err := s.store.RestoreFromTesting(r.Context(), chi.URLParam(r, "certname")) + if err != nil { + mapErr(w, err) + return + } + writeJSON(w, http.StatusOK, node) +} + func (s *Server) deleteNode(w http.ResponseWriter, r *http.Request) { if err := s.store.DeleteNode(r.Context(), chi.URLParam(r, "certname")); err != nil { mapErr(w, err) diff --git a/internal/server/server.go b/internal/server/server.go index f5eb476..862ccb9 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -32,6 +32,7 @@ type Store interface { UpsertNode(ctx context.Context, n *models.Node) error GetNode(ctx context.Context, certname string) (*models.Node, error) SetNodeEnvironment(ctx context.Context, certname, environment string) (*models.Node, error) + RestoreFromTesting(ctx context.Context, certname string) (*models.Node, error) ListNodes(ctx context.Context) ([]models.Node, error) DeleteNode(ctx context.Context, certname string) error } @@ -86,6 +87,7 @@ func (s *Server) Router() http.Handler { // --- writes (token-guarded) --- r.With(s.requireWrite(true)).Put("/api/v1/nodes/{certname}/environment", s.putNodeEnvironment) + r.With(s.requireWrite(true)).Delete("/api/v1/nodes/{certname}/environment/testing", s.restoreFromTesting) r.Group(func(r chi.Router) { r.Use(s.requireWrite(false)) r.Put("/api/v1/roles/{name}", s.putRole) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 0d5a702..504572f 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -95,10 +95,30 @@ func (f *fakeStore) SetNodeEnvironment(_ context.Context, certname, env string) if !ok { return nil, database.ErrNotFound } + switch { + case env != "testing": + n.PreviousEnvironment = "" + case n.Environment != "testing": + n.PreviousEnvironment = n.Environment + } n.Environment = env f.nodes[certname] = n return &n, nil } +func (f *fakeStore) RestoreFromTesting(_ context.Context, certname string) (*models.Node, error) { + n, ok := f.nodes[certname] + switch { + case !ok: + return nil, database.ErrNotFound + case n.Environment != "testing": + return nil, database.ErrNotInTesting + case n.PreviousEnvironment == "": + return nil, database.ErrNoPreviousEnvironment + } + n.Environment, n.PreviousEnvironment = n.PreviousEnvironment, "" + f.nodes[certname] = n + return &n, nil +} func (f *fakeStore) GetNode(_ context.Context, certname string) (*models.Node, error) { n, ok := f.nodes[certname] if !ok { diff --git a/migrations/0002_previous_environment.sql b/migrations/0002_previous_environment.sql new file mode 100644 index 0000000..4cb0dc4 --- /dev/null +++ b/migrations/0002_previous_environment.sql @@ -0,0 +1,2 @@ +ALTER TABLE nodes ADD COLUMN IF NOT EXISTS previous_environment TEXT + REFERENCES statuses(name) ON UPDATE CASCADE ON DELETE SET NULL; diff --git a/pkg/client/client.go b/pkg/client/client.go index 374fd51..8ee8adc 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -174,6 +174,12 @@ func (c *Client) SetNodeEnvironment(ctx context.Context, certname, environment s body := map[string]string{"environment": environment} return &out, c.do(ctx, http.MethodPut, "/api/v1/nodes/"+url.PathEscape(certname)+"/environment", body, &out) } + +// RestoreFromTesting returns a testing node to its previous environment. +func (c *Client) RestoreFromTesting(ctx context.Context, certname string) (*models.Node, error) { + var out models.Node + return &out, c.do(ctx, http.MethodDelete, "/api/v1/nodes/"+url.PathEscape(certname)+"/environment/testing", nil, &out) +} func (c *Client) DeleteNode(ctx context.Context, certname string) error { return c.do(ctx, http.MethodDelete, "/api/v1/nodes/"+url.PathEscape(certname), nil, nil) } diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index c0e1b9b..6c83075 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -75,3 +75,17 @@ func TestENCReturnsRawYAML(t *testing.T) { t.Errorf("enc = %q", b) } } + +func TestRestoreFromTesting(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete || r.URL.Path != "/api/v1/nodes/h1/environment/testing" { + t.Errorf("got %s %s", r.Method, r.URL.Path) + } + _, _ = w.Write([]byte(`{"certname":"h1","role":"r","environment":"production"}`)) + })) + defer srv.Close() + n, err := New(srv.URL, "t").RestoreFromTesting(context.Background(), "h1") + if err != nil || n.Environment != "production" { + t.Fatalf("RestoreFromTesting = %+v, %v", n, err) + } +} diff --git a/pkg/models/models.go b/pkg/models/models.go index d969db5..322df99 100644 --- a/pkg/models/models.go +++ b/pkg/models/models.go @@ -26,4 +26,7 @@ type Node struct { Role string `json:"role"` Environment string `json:"environment"` Params map[string]any `json:"params,omitempty"` + // PreviousEnvironment is server-managed: the environment to restore when + // the node leaves testing. + PreviousEnvironment string `json:"previous_environment,omitempty"` } -- 2.47.3