diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fdeb97..f5f1d3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## vX.X.X (YYYY-MM-DD) +### Fixed +- One invalid `challenge.yml` no longer takes every challenge down: it stopped Galvanize from starting, or made `/admin/reload-challs` fail. Files that cannot be parsed (including a bad compose file), unreadable directories and challenges declaring an already indexed `category/name` are now skipped and logged, and the other challenges are indexed +- A missing or unreadable challenge directory makes `BuildIndex` return an error instead of panicking; a failed reload keeps the current index + +### Changed +- `/admin/reload-challs` returns `{"indexed": , "skipped": [{"path", "reason"}]}` instead of an empty body + ## v0.7.1 (2026-06-02) ### Added diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 5fac798..c817ee7 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -263,13 +263,17 @@ paths: /admin/reload-challs: post: summary: Reload challenges index - description: Reload challenges index from disk and update the inmemory index + description: Reload challenges index from disk and update the inmemory index. Challenge files that cannot be parsed, or that duplicate another challenge's category/name, are skipped and listed in the response; the other challenges are indexed. If the challenge directory cannot be read, the current index is kept and 500 is returned. operationId: reloadChallenges security: - bearerAuth: [ ] responses: '200': description: Reload successful + content: + application/json: + schema: + $ref: '#/components/schemas/ReloadChallengesResponse' '401': description: Unauthorized '403': @@ -550,6 +554,34 @@ components: - created_at - updated_at + ReloadChallengesResponse: + type: object + properties: + indexed: + type: integer + description: Number of challenges in the index after the reload. + skipped: + type: array + description: Challenge files left out of the index. + items: + $ref: '#/components/schemas/SkippedChallenge' + required: + - indexed + - skipped + + SkippedChallenge: + type: object + properties: + path: + type: string + description: Path of the challenge file. + reason: + type: string + description: Why it was skipped. + required: + - path + - reason + RetryDeploymentRequest: type: object required: diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 2b138a1..5ea7d2f 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -146,6 +146,9 @@ var serveCmd = &cobra.Command{ if err != nil { zap.S().Fatalf("Failed to initialize challenge index: %v", err) } + if skipped := challIdx.Skipped(); len(skipped) > 0 { + zap.S().Warnf("%d challenge file(s) skipped (see the errors above); the other challenges are available", len(skipped)) + } // Seed the challenge index gauge with the initial count. { challs := challIdx.GetAll() diff --git a/galvanize-instancer/internal/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index 2ed8c74..273da03 100644 --- a/galvanize-instancer/internal/challenge/challenge.go +++ b/galvanize-instancer/internal/challenge/challenge.go @@ -112,14 +112,23 @@ type ChallengeIndexer interface { GetAllUnique() []*Challenge GetAll() []*Challenge BuildIndex(baseDir string) error + // Skipped lists the challenge files the last BuildIndex left out. + Skipped() []SkippedChallenge +} + +// SkippedChallenge is a challenge file left out of the index, and why. +type SkippedChallenge struct { + Path string + Reason string } // Compile-time check that ChallengeIndex implements ChallengeIndexer. var _ ChallengeIndexer = (*ChallengeIndex)(nil) type ChallengeIndex struct { - mu sync.RWMutex - challs map[string]*Challenge + mu sync.RWMutex + challs map[string]*Challenge + skipped []SkippedChallenge } type Challenge struct { @@ -144,32 +153,79 @@ func NewChallengeIndex(baseDir string) (*ChallengeIndex, error) { return idx, nil } +// BuildIndex (re)builds the index from the challenge files under baseDir. +// +// A challenge file that cannot be read or parsed, or that declares the same +// category/name as one already indexed, is skipped and reported (Skipped and +// the logs) instead of failing the whole index: one bad challenge.yml would +// otherwise stop Galvanize from starting, or make every reload fail. +// baseDir itself must be readable; otherwise an error is returned and the +// current index is kept as it is. func (idx *ChallengeIndex) BuildIndex(baseDir string) error { - idx.mu.Lock() - defer idx.mu.Unlock() - idx.challs = make(map[string]*Challenge) + challs := make(map[string]*Challenge) + paths := make(map[string]string) + var skipped []SkippedChallenge + skip := func(path, reason string) { + skipped = append(skipped, SkippedChallenge{Path: path, Reason: reason}) + zap.S().Errorf("Skipping challenge %s: %s", path, reason) + } + err := filepath.WalkDir(baseDir, func(path string, d fs.DirEntry, err error) error { - if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "example") { - return filepath.SkipDir + if err != nil { + if path == baseDir { + return err + } + skip(path, err.Error()) + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + if d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "example" { + return filepath.SkipDir + } + return nil } - if err != nil || d.IsDir() || (d.Name() != "challenge.yml" && d.Name() != "challenge.yaml") { - return err + if d.Name() != "challenge.yml" && d.Name() != "challenge.yaml" { + return nil } // Parse challenge.yml to get category and name chall, err := parseChallenge(path) if err != nil { - return fmt.Errorf("parse %s: %w", path, err) + skip(path, err.Error()) + return filepath.SkipDir } if chall.Type != "zync" { return filepath.SkipDir } key := chall.Category + "/" + chall.Name - idx.challs[key] = chall + if first, ok := paths[key]; ok { + skip(path, fmt.Sprintf("duplicate of %s (both declare %s)", first, key)) + return filepath.SkipDir + } + challs[key] = chall + paths[key] = path zap.S().Infof("Registered challenge: %s", key) return filepath.SkipDir }) - return err + if err != nil { + return fmt.Errorf("index %s: %w", baseDir, err) + } + + idx.mu.Lock() + idx.challs = challs + idx.skipped = skipped + idx.mu.Unlock() + return nil +} + +// Skipped returns the challenge files the last successful BuildIndex left out. +func (idx *ChallengeIndex) Skipped() []SkippedChallenge { + idx.mu.RLock() + defer idx.mu.RUnlock() + return append([]SkippedChallenge(nil), idx.skipped...) } func (idx *ChallengeIndex) Get(category, name string) (*Challenge, error) { diff --git a/galvanize-instancer/internal/challenge/challenge_test.go b/galvanize-instancer/internal/challenge/challenge_test.go index bba072d..1c28b78 100644 --- a/galvanize-instancer/internal/challenge/challenge_test.go +++ b/galvanize-instancer/internal/challenge/challenge_test.go @@ -1,6 +1,7 @@ package challenge import ( + "fmt" "os" "path/filepath" "testing" @@ -152,11 +153,113 @@ deploy_parameters: } func TestBuildIndex_InvalidDir(t *testing.T) { - // WalkDir passes a nil DirEntry when the root path doesn't exist, - // which causes a panic in BuildIndex before the error can be returned. - assert.Panics(t, func() { - _, _ = NewChallengeIndex("/nonexistent/path/that/does/not/exist") - }) + _, err := NewChallengeIndex("/nonexistent/path/that/does/not/exist") + assert.Error(t, err) +} + +const validChall = ` +name: %s +category: %s +playbook_name: http +type: zync +deploy_parameters: + unique: false +` + +func TestBuildIndex_SkipsInvalidFile(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web/ok", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "web/broken", "name: [unterminated\n") + writeChallenge(t, dir, "pwn/ok", fmt.Sprintf(validChall, "ok", "pwn")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + assert.Len(t, idx.GetAll(), 2) + _, err = idx.Get("web", "ok") + assert.NoError(t, err) + _, err = idx.Get("pwn", "ok") + assert.NoError(t, err) + + skipped := idx.Skipped() + require.Len(t, skipped, 1) + assert.Equal(t, filepath.Join(dir, "web/broken/challenge.yml"), skipped[0].Path) + assert.NotEmpty(t, skipped[0].Reason) +} + +func TestBuildIndex_SkipsDuplicate(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "a", fmt.Sprintf(validChall, "login", "web")) + writeChallenge(t, dir, "b", fmt.Sprintf(validChall, "login", "web")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + // WalkDir is lexical: a is indexed, b is the duplicate + assert.Len(t, idx.GetAll(), 1) + skipped := idx.Skipped() + require.Len(t, skipped, 1) + assert.Equal(t, filepath.Join(dir, "b/challenge.yml"), skipped[0].Path) + assert.Contains(t, skipped[0].Reason, filepath.Join(dir, "a/challenge.yml")) + assert.Contains(t, skipped[0].Reason, "web/login") +} + +func TestBuildIndex_SameNameDifferentCategories(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "login", "web")) + writeChallenge(t, dir, "pwn", fmt.Sprintf(validChall, "login", "pwn")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 2) + assert.Empty(t, idx.Skipped()) +} + +func TestBuildIndex_UnreadableSubdirSkipped(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + locked := filepath.Join(dir, "locked") + require.NoError(t, os.MkdirAll(locked, 0o755)) + require.NoError(t, os.Chmod(locked, 0)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 1) + require.Len(t, idx.Skipped(), 1) + assert.Equal(t, locked, idx.Skipped()[0].Path) +} + +func TestBuildIndex_FailedRebuildKeepsIndex(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.GetAll(), 1) + + assert.Error(t, idx.BuildIndex("/nonexistent/path/that/does/not/exist")) + assert.Len(t, idx.GetAll(), 1, "the previous index is kept") + assert.Len(t, idx.Skipped(), 1, "and so is its skipped list") +} + +func TestBuildIndex_RebuildClearsSkipped(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.Skipped(), 1) + + writeChallenge(t, dir, "broken", fmt.Sprintf(validChall, "fixed", "web")) + require.NoError(t, idx.BuildIndex(dir)) + assert.Len(t, idx.GetAll(), 2) + assert.Empty(t, idx.Skipped()) } func TestGet_ExistingChallenge(t *testing.T) { @@ -373,9 +476,12 @@ deploy_parameters: compose_file: nope.yaml `) - _, err := NewChallengeIndex(dir) - require.Error(t, err) - assert.Contains(t, err.Error(), "compose_file") + // The challenge is skipped, with the reason, instead of failing the index + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Empty(t, idx.GetAll()) + require.Len(t, idx.Skipped(), 1) + assert.Contains(t, idx.Skipped()[0].Reason, "compose_file") } func TestLoadComposeDefinition_NoServicesSectionErrors(t *testing.T) { @@ -390,9 +496,12 @@ deploy_parameters: `) writeFile(t, dir, "web", "docker-compose.yml", "version: \"3\"\nnetworks:\n default: {}\n") - _, err := NewChallengeIndex(dir) - require.Error(t, err) - assert.Contains(t, err.Error(), "services") + // The challenge is skipped, with the reason, instead of failing the index + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Empty(t, idx.GetAll()) + require.Len(t, idx.Skipped(), 1) + assert.Contains(t, idx.Skipped()[0].Reason, "services") } func TestLoadComposeDefinition_NoComposeFileLeavesHTTPUntouched(t *testing.T) { diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index 1837052..36d16a8 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -132,6 +132,15 @@ type ErrorDeploymentInfo struct { // ErrorDeploymentInfoPreviousStatus The status before the deployment transitioned to error. Indicates whether a deploy or terminate action was in progress. type ErrorDeploymentInfoPreviousStatus string +// ReloadChallengesResponse defines model for ReloadChallengesResponse. +type ReloadChallengesResponse struct { + // Indexed Number of challenges in the index after the reload. + Indexed int `json:"indexed"` + + // Skipped Challenge files left out of the index. + Skipped []SkippedChallenge `json:"skipped"` +} + // RetryDeploymentRequest defines model for RetryDeploymentRequest. type RetryDeploymentRequest struct { // Action The action to perform - 'deploy' to retry deployment, 'terminate' to terminate the failed deployment, 'delete' to remove the deployment from the database. If not provided, the action will be inferred from the previous status (deploy or terminate only). @@ -144,6 +153,15 @@ type RetryDeploymentRequest struct { // RetryDeploymentRequestAction The action to perform - 'deploy' to retry deployment, 'terminate' to terminate the failed deployment, 'delete' to remove the deployment from the database. If not provided, the action will be inferred from the previous status (deploy or terminate only). type RetryDeploymentRequestAction string +// SkippedChallenge defines model for SkippedChallenge. +type SkippedChallenge struct { + // Path Path of the challenge file. + Path string `json:"path"` + + // Reason Why it was skipped. + Reason string `json:"reason"` +} + // StatusResponse defines model for StatusResponse. type StatusResponse struct { ConnectionInfo *string `json:"connection_info,omitempty"` @@ -452,41 +470,44 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xabW/bOBL+KwPdAW0Bx0m3PRzO37pJ2/PhsHdoUixwbWHQ4sjiliJVknKrLfzfDyQl", - "i5Iox+km2Wax3xRrRM4888wLh/mapLIopUBhdLL4mug0x4K4xxe0YOICSy7rN/ipQm3sr6WSJSrD0Mmk", - "xOBGqto+U9SpYqVhUiSL5CpHaN+CzMDYv3PCOYoNgpFA3crzZJaYusRkkWijmNgku1myl1sJUmB8bfvm", - "ZuvuZonCTxVTSJPFu0710X4f9p/K9S+YGqvSjxX/+J8SFbEqvEFdSqExgke7kvuLGSzcw18VZski+ctp", - "B/Zpg/TpefvJeaPQfvXdXg+iFKl7yOhVKivhPNLIMGFwg8pKFag12WDwcgKDVjCycPhTFJFpvQ+y5Ahn", - "36bf/uRviEOBwixFJm/bRbMklUJgau1bsWaDkYy3DOmKVj6OVhpTKageI3TRSAAT0AiBZiLFBh5rCGhD", - "lEEaQBXEwH4z91ncB4YV6BwQLPqZaEgVkmbhTKqCmGSRUGLwxH4Qczh+KZlCvSJmvNHPOYrhJo38HH6q", - "OIdMKqgE+1SFMvr43bUhpnIgoqgKyw2HjH07S1QlhH/SRpalffzw7dTabzYC+JB7Y4R8qZRUYx4eTF3x", - "Re6c2p4NRzv32xhkLVkF1o/Z6kSgEYFMycLtnBHGkQYKRFMSo/FFA72XF/FIKhVumaz0quPZeB3/DtaY", - "STWKKaOI0MxKI7Upzlkyh6WgzDpHw+ccTY4KSPMVSAUGVcEEMQjE5RWHKxNQKrlRqF18RPh+gOWzxCAp", - "VlNQ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VQncaLc", - "Ckjx0V4ENCsYmT884MTS+pDzkRf1pBvdPieDmr3BSCv0Go1bO5D1eavpiN1KM2Ai5RW1had3xLVO75Pj", - "30ybwZFfT1SHo5lxVLMRmzOMOo4xYay+rhF0ZoWI3Rtlvvs04jAakoSJBrP26DRBRc60OfHMPXHMDbk4", - "5s5bJ3nezbXvgzs3mO9PM2gUnQ846ew9HjGqc61CLgkNvNrWi74+b5xYmLaYoPjFn8Ip0x+BCNqMVNwR", - "mIkCC6lqLzdKMX69aykSVeIP0WtOANp3jVF1UAAOeceoej/V83OHnBh7vByE+BwuS0xZVrdzFaK7yY9U", - "4ZxnHnFab/R0Ry3txIDrW9taj82BjvauU7fvkFsFegXKjbsGHrqXZvn53Rt+0bcyk5V4UAWzjanRcHOy", - "Shokxa30a+18aQbN+AkcO/z8aQYbJasSKaxrP15xnwb6tTO4aF83GBbdS2meGlDdoDCHUJWonOF/dneH", - "u7shT6Z5207AJ4+LV63I9zzTiBTqVm9b6e61bWhS7GBkLXsXIIOMeOukuOpu9o4fHuzJcHh+0BHi+hHC", - "2e80QjCh8x/8DCHw5pFjhOOmlHcczH+g2eRxE8bg6tzh4W4UH+K8scsVrKWIo5W7bqPTtHrp3vdodUfp", - "YHAdGmtC99eRTikMD4+8nqTOORG2Z/Uf9Vo/IyUgUbyeQUG+hFePCkmaI50BmnT+5Aa0uq5Q3GVS8b7y", - "d9YtVDLrnSS903Mk3N+URac+r9H800v8Rnf3Lyy7+9hr/0lp7PtLVFuWoj0Ee+3rITY9KLz+4O/LnM3d", - "7lM2tyS/bP+x43ekupdw/2zAcHujUncDBn736cuerfp3B+5Mbf15kz73+6uKt9/d3kffGS0iu93/AwAA", - "//+18jdZDy8AAA==", + "H4sIAAAAAAAC/+xabW/cNvL/KgP9/0ASQF47TYrD+V6lcZLbw6FXJA4CXBIsuOJoxVoiFZJysg32ux84", + "1LOo9Tq13bjoO2k1JIczv3ngj/s1SlRRKonSmuj0a2SSDAtGj894IeQZlrnavsZPF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NsnRSEQtcGEugEleE241AVRg", + "4W58PBMEY8LIZsxCwqRU1nEVJdPG0Rh0dGMWeOUBgcCkovNSu/QD014nHUtWYAxMY3PKJjUcXJE3fFcD", + "vX/Q22gyQ4NrOololeHBnwuNiXX76HTVyGrCJam0RmlrWwgDF1haUuHHkxP3rtFWWvrj5jBOxiTf742R", + "faExSygGIqF29J+in58B7RD+Vm97RXZfBDiijw0IK4dUMUmjC3hTYiLSbUPIMdNRhkr3CcIQLgac5S0d", + "G2aY0W89Onjb7Dk13HZ59KeQRoFBE0A86chDd3IgeXr7Gz8b7jJVlbxXTUkTUxNWfLYTsciKG+mJGw4v", + "hpriA0KH5/hi2GhVuXKy3noKi4b29Gt4zmDvPCLk7qT9mSMBr9H89E1VoqaN/9VB7++gxziZx21zdTJ7", + "JD9vRL5n3ihQqBu9XaW707ahTrGjawE1uDkbZcQbB8V5d7d+OEHTgmE/R9MB4mqa5uQPomls3/n3nqfp", + "efNAquYwJviWg/lPxP8exuL2/rxC9qCr6PvI6Xa5QjQQIVjRlSafh9UL+j6A1S2lg9GVc6gJba98SSns", + "Hx7z7Sx0nvvztB80aP2sUoBM59sYCvalf72r3a2yownQJotH14DVVYXiNpOK95X/s0NjKpUOTpLe6Rmy", + "3Ga9jnbo81do/+klfqe7h5fC3Z33lX8TnPr+DepLkaA7BHvtt2PbDEzh9Qd/J0l77laf23MD8jfNX6v+", + "QKh7CfqXisBL5LeDwO8+fbmz1fB+hs7Uzp/X6XO/v6p4893tXfSdwSKy2/1vAGfMsqmRMgAA", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 9fd871d..1b51088 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -28,13 +28,26 @@ func (s *Server) ReloadChallenges(ctx echo.Context) error { conf := s.confProv.GetConfig() if err := s.challIdx.BuildIndex(conf.Instancer.ChallengeDir); err != nil { - zap.S().Errorf("Failed to reload challenges: %v", err) + // BuildIndex keeps the current index when it fails + zap.S().Errorf("Failed to reload challenges, keeping the current index: %v", err) return ctx.JSON(500, api.Error{Message: utils.HTTP500Debug(fmt.Sprintf("Failed to reload challenges: %v", err))}) } updateChallengeIndexMetrics(s.challIdx) - zap.S().Infof("Challenges reloaded successfully") - return ctx.NoContent(200) + + response := api.ReloadChallengesResponse{ + Indexed: len(s.challIdx.GetAll()), + Skipped: make([]api.SkippedChallenge, 0), + } + for _, sk := range s.challIdx.Skipped() { + response.Skipped = append(response.Skipped, api.SkippedChallenge{Path: sk.Path, Reason: sk.Reason}) + } + if len(response.Skipped) > 0 { + zap.S().Warnf("Challenges reloaded: %d indexed, %d skipped (see the errors above)", response.Indexed, len(response.Skipped)) + } else { + zap.S().Infof("Challenges reloaded: %d indexed", response.Indexed) + } + return ctx.JSON(200, response) } func (s *Server) ConfigCheck(ctx echo.Context) error { diff --git a/galvanize-instancer/pkg/restserver_admin_test.go b/galvanize-instancer/pkg/restserver_admin_test.go index a8885ea..145f3f5 100644 --- a/galvanize-instancer/pkg/restserver_admin_test.go +++ b/galvanize-instancer/pkg/restserver_admin_test.go @@ -1,6 +1,7 @@ package pkg import ( + "encoding/json" "net/http" "net/http/httptest" "os" @@ -9,6 +10,7 @@ import ( "github.com/28Pollux28/galvanize/internal/auth" "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/api" "github.com/28Pollux28/galvanize/pkg/config" "github.com/golang-jwt/jwt/v5" "github.com/labstack/echo/v4" @@ -100,6 +102,7 @@ deploy_parameters: err := srv.ReloadChallenges(ctx) require.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `{"indexed":1,"skipped":[]}`, rec.Body.String()) } func TestReloadChallenges_Unauthorized(t *testing.T) { @@ -162,13 +165,43 @@ deploy_parameters: cfg.Instancer.ChallengeDir = "/nonexistent/path/that/does/not/exist" claims := &auth.Claims{Role: "admin"} - ctx, _ := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) + ctx, rec := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) - // BuildIndex panics on a non-existent root dir because WalkDir passes - // a nil DirEntry when it can't stat the root path. - assert.Panics(t, func() { - _ = srv.ReloadChallenges(ctx) - }) + err := srv.ReloadChallenges(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusInternalServerError, rec.Code) + + // The index built at startup is kept + _, err = srv.challIdx.Get("web", "http") + assert.NoError(t, err) +} + +func TestReloadChallenges_ReportsSkipped(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", ` +name: http +category: web +playbook_name: http +type: zync +deploy_parameters: + unique: false +`) + srv, _ := newTestServer(t, dir) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + claims := &auth.Claims{Role: "admin"} + ctx, rec := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) + + err := srv.ReloadChallenges(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusOK, rec.Code) + + var resp api.ReloadChallengesResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + assert.Equal(t, 1, resp.Indexed) + require.Len(t, resp.Skipped, 1) + assert.Equal(t, filepath.Join(dir, "broken/challenge.yml"), resp.Skipped[0].Path) + assert.NotEmpty(t, resp.Skipped[0].Reason) } func TestReloadChallenges_RefreshesIndex(t *testing.T) { diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index 5466c6d..a23dbf5 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -113,7 +113,8 @@ func (m *mockChallengeIndexer) GetAll() []*challenge.Challenge { return challs } -func (m *mockChallengeIndexer) BuildIndex(_ string) error { return nil } +func (m *mockChallengeIndexer) BuildIndex(_ string) error { return nil } +func (m *mockChallengeIndexer) Skipped() []challenge.SkippedChallenge { return nil } var _ challenge.ChallengeIndexer = (*mockChallengeIndexer)(nil)