diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 3b71f73..713a97b 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -56,6 +56,14 @@ func main() { if err != nil { log.Fatal(err) } + address := strings.TrimSpace(os.Getenv("DOBOTAI_LISTEN_ADDR")) + if address == "" { + address = "127.0.0.1:8090" + } + if strings.TrimSpace(settingsRuntime.clientID) == "" || strings.TrimSpace(settingsRuntime.secret) == "" { + runSetupOnly(ctx, cancel, settingsRuntime, address, os.Getenv("DOBOTAI_TENANT_KEY"), &restartRequested) + return + } client, err := weknora.NewClient(os.Getenv("WEKNORA_BASE_URL"), os.Getenv("WEKNORA_API_KEY"), 120*time.Second) if err != nil { log.Fatal(err) @@ -87,10 +95,6 @@ func main() { if err != nil { log.Fatal(err) } - address := strings.TrimSpace(os.Getenv("DOBOTAI_LISTEN_ADDR")) - if address == "" { - address = "127.0.0.1:8090" - } auditOptions, err := buildAuditOptions(store, os.Getenv("DOBOTAI_TENANT_KEY"), os.Getenv("DOBOTAI_ADMIN_TOKEN"), address) if err != nil { log.Fatal(err) diff --git a/cmd/dobotai/setup_only.go b/cmd/dobotai/setup_only.go new file mode 100644 index 0000000..0be6344 --- /dev/null +++ b/cmd/dobotai/setup_only.go @@ -0,0 +1,65 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "log" + "net/http" + "os" + "strings" + "sync/atomic" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +func newSetupOnlyHandler(runtime *settingsRuntime, token string) (http.Handler, error) { + if runtime == nil || runtime.admin == nil { + return nil, errors.New("setup runtime unavailable") + } + if strings.TrimSpace(token) == "" { + return nil, errors.New("DOBOTAI_ADMIN_TOKEN is required in setup-only mode") + } + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "mode": "setup_required"}) + }) + mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(runtimeBuildInfo()) + }) + mux.Handle("/admin/", adminweb.New(runtime.admin, token)) + return mux, nil +} + +func runSetupOnly(ctx context.Context, cancel context.CancelFunc, runtime *settingsRuntime, address, tenant string, restartRequested *atomic.Bool) { + runtime.admin.SetCandidateActivator(&dingTalkCandidateActivator{ + tenant: tenant, repo: runtime.repository, secrets: runtime.secrets, verifier: runtime.verifier, + bindings: map[string]settings.ResourceBinding{}, + restart: func() { restartRequested.Store(true); cancel() }, + }) + handler, err := newSetupOnlyHandler(runtime, os.Getenv("DOBOTAI_ADMIN_TOKEN")) + if err != nil { + log.Fatal(err) + } + server := &http.Server{Addr: address, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, IdleTimeout: 60 * time.Second} + go func() { + log.Printf("DobotAI setup-only listener on %s", address) + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Printf("setup HTTP server failed: %v", err) + cancel() + } + }() + <-ctx.Done() + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + if err := server.Shutdown(shutdownCtx); err != nil { + log.Printf("setup HTTP shutdown: %v", err) + } + if restartRequested.Load() { + os.Exit(75) + } +} diff --git a/cmd/dobotai/setup_only_test.go b/cmd/dobotai/setup_only_test.go new file mode 100644 index 0000000..51db859 --- /dev/null +++ b/cmd/dobotai/setup_only_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type setupRepoStub struct{} + +func (setupRepoStub) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) { + return "", "", false, nil +} +func (setupRepoStub) CandidateDingTalkConfig(context.Context, string) (string, string, error) { + return "", "", nil +} +func (setupRepoStub) SaveDingTalkConfig(context.Context, string, string, string, bool) error { + return nil +} +func (setupRepoStub) MarkDingTalkCandidateFailed(context.Context, string, string, string) error { + return nil +} +func (setupRepoStub) AdministratorCount(context.Context, string) (int, error) { return 0, nil } +func (setupRepoStub) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) { + return map[string]settings.ResourceBinding{}, nil +} +func (setupRepoStub) CreateBootstrapChallenge(context.Context, string, string, time.Time) error { + return nil +} +func (setupRepoStub) ConfirmBootstrap(context.Context, string) error { return nil } + +type setupVerifierStub struct{} + +func (setupVerifierStub) Verify(context.Context, string, string) dingtalkconfig.Result { + return dingtalkconfig.Result{} +} + +func setupControl(t *testing.T) *adminweb.ControlService { + t.Helper() + secrets, err := secretstore.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + control, err := adminweb.NewControlService("tenant", setupRepoStub{}, secrets, setupVerifierStub{}) + if err != nil { + t.Fatal(err) + } + return control +} + +func TestSetupOnlyHandlerExposesHealthVersionAndProtectedAdmin(t *testing.T) { + runtime := &settingsRuntime{admin: setupControl(t)} + h, err := newSetupOnlyHandler(runtime, "admin-token") + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodGet, "/healthz", nil) + resp := httptest.NewRecorder() + h.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Fatalf("health status=%d", resp.Code) + } + var health map[string]string + if err = json.Unmarshal(resp.Body.Bytes(), &health); err != nil { + t.Fatal(err) + } + if health["status"] != "ok" || health["mode"] != "setup_required" { + t.Fatalf("health=%v", health) + } + resp = httptest.NewRecorder() + h.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/version", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("version status=%d", resp.Code) + } + resp = httptest.NewRecorder() + h.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/admin/settings", nil)) + if resp.Code != http.StatusUnauthorized { + t.Fatalf("unauth status=%d", resp.Code) + } + req = httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + resp = httptest.NewRecorder() + h.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Fatalf("auth status=%d body=%s", resp.Code, resp.Body.String()) + } +} + +func TestSetupOnlyHandlerRequiresAdminToken(t *testing.T) { + _, err := newSetupOnlyHandler(&settingsRuntime{admin: setupControl(t)}, "") + if err == nil { + t.Fatal("expected token error") + } +} diff --git a/internal/store/postgres/settings.go b/internal/store/postgres/settings.go index ec00ef3..4a60a3e 100644 --- a/internal/store/postgres/settings.go +++ b/internal/store/postgres/settings.go @@ -237,14 +237,17 @@ func (r *SettingsRepository) PrepareDingTalkRuntimeStart(ctx context.Context, te return true, tx.Commit(ctx) case "runtime_starting": var oldID string - if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID); err != nil { + err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { return false, err } if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code='runtime_start_failed' WHERE id=$1`, activeID); err != nil { return false, err } - if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil { - return false, err + if oldID != "" { + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil { + return false, err + } } return false, tx.Commit(ctx) default: