package server import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" "git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer" "git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea" "git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest" "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" ) type fakeGitea struct { files map[string][]byte dirs map[string][]gitea.DirEntry } func (f *fakeGitea) GetFile(_ context.Context, owner, repo, path, _ string) ([]byte, error) { key := owner + "/" + repo + ":" + path b, ok := f.files[key] if !ok { return nil, gitea.ErrNotFound } return b, nil } func (f *fakeGitea) ListDir(_ context.Context, owner, repo, path, _ string) ([]gitea.DirEntry, error) { key := owner + "/" + repo + ":" + path d, ok := f.dirs[key] if !ok { return nil, gitea.ErrNotFound } return d, nil } type fakeApplier struct { applied []manifest.K8sObject } func (f *fakeApplier) Apply(_ context.Context, obj manifest.K8sObject) error { f.applied = append(f.applied, obj) return nil } func (f *fakeApplier) Mode() string { return "mock" } func signPayload(secret string, body []byte) string { mac := hmac.New(sha256.New, []byte(secret)) mac.Write(body) return hex.EncodeToString(mac.Sum(nil)) } func TestWebhookAndAPIFlow(t *testing.T) { cfg := config.Config{ GiteaURL: "https://git.site.latha.org", GiteaWebhookSecret: "super-secret", AllowedOwners: []string{"experiments"}, DefaultImagePullSecret: "gitea-registry-secret", } st, err := store.New(filepath.Join(t.TempDir(), "state.json")) if err != nil { t.Fatalf("store.New: %v", err) } fg := &fakeGitea{ files: map[string][]byte{ "experiments/hello-app:.latha-deploy.yaml": []byte("name: hello-app\nnamespace: apps\nhost: hello.site.latha.org\nport: 8080\nhealthPath: /healthz\n"), "experiments/k8s-app:k8s/deploy.yaml": []byte("apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: k8s-app\nspec:\n replicas: 1\n"), }, dirs: map[string][]gitea.DirEntry{ "experiments/k8s-app:k8s": { {Name: "deploy.yaml", Path: "k8s/deploy.yaml", Type: "file"}, }, }, } fa := &fakeApplier{} svc := deployer.NewService(cfg, st, fg, fa) srv := New(cfg, st, svc, fa) ts := httptest.NewServer(srv.Handler()) defer ts.Close() // 1. Invalid signature -> 401 req, _ := http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", strings.NewReader(`{}`)) req.Header.Set("X-Gitea-Event", "push") req.Header.Set("X-Gitea-Signature", "bad") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("post bad sig: %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusUnauthorized { t.Fatalf("expected 401, got %d", resp.StatusCode) } // 2. Ping event -> 200 pingBody := []byte(`{"zen":"keep it simple"}`) req, _ = http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", bytes.NewReader(pingBody)) req.Header.Set("X-Gitea-Event", "ping") req.Header.Set("X-Gitea-Signature", signPayload(cfg.GiteaWebhookSecret, pingBody)) resp, err = http.DefaultClient.Do(req) if err != nil { t.Fatalf("post ping: %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("expected 200 for ping, got %d", resp.StatusCode) } // 3. Push event -> deploys .latha-deploy.yaml pushBody := []byte(`{ "ref": "refs/heads/main", "after": "deadbeef12345678", "repository": {"full_name": "experiments/hello-app", "name": "hello-app", "default_branch": "main"}, "pusher": {"username": "nandi"} }`) req, _ = http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", bytes.NewReader(pushBody)) req.Header.Set("X-Gitea-Event", "push") req.Header.Set("X-Gitea-Signature", signPayload(cfg.GiteaWebhookSecret, pushBody)) resp, err = http.DefaultClient.Do(req) if err != nil { t.Fatalf("post push: %v", err) } var pushOut map[string]any _ = json.NewDecoder(resp.Body).Decode(&pushOut) resp.Body.Close() if resp.StatusCode != http.StatusOK || pushOut["status"] != "deployed" { t.Fatalf("expected deployed, got %d %v", resp.StatusCode, pushOut) } if len(fa.applied) != 4 { t.Fatalf("expected 4 applied k8s objects, got %d", len(fa.applied)) } depID := pushOut["deployment_id"].(string) // 4. Manual deploy for k8s/ directory repo manualBody := []byte(`{"repo":"experiments/k8s-app","ref":"main"}`) resp, err = http.Post(ts.URL+"/api/deploy", "application/json", bytes.NewReader(manualBody)) if err != nil { t.Fatalf("post manual deploy: %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("expected 200 manual deploy, got %d", resp.StatusCode) } // 5. Rollback first deployment resp, err = http.Post(ts.URL+"/api/deployments/"+depID+"/rollback", "application/json", nil) if err != nil { t.Fatalf("post rollback: %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("expected 200 rollback, got %d", resp.StatusCode) } // 6. Verify dashboard & metrics resp, err = http.Get(ts.URL + "/") if err != nil || resp.StatusCode != http.StatusOK { t.Fatalf("GET / failed: %v %d", err, resp.StatusCode) } resp.Body.Close() resp, err = http.Get(ts.URL + "/metrics") if err != nil || resp.StatusCode != http.StatusOK { t.Fatalf("GET /metrics failed: %v %d", err, resp.StatusCode) } resp.Body.Close() }