Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ trokky create my-site
| `login <url>` | Authenticate via OAuth2 device flow |
| `logout [name]` | Remove stored credentials |
| `status` | Show instance health and collections |
| `doctor` | Check a site for problems that fail silently (Trokky 3.6+, admin) |
| `config add\|remove\|list\|use\|path` | Manage instance configurations |
| `documents list\|get\|create\|update\|delete` | CRUD operations on documents |
| `backup --output <file>` | Create a zip backup with manifest |
Expand Down
158 changes: 158 additions & 0 deletions cmd/doctor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package cmd

import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"

"github.com/spf13/cobra"
"github.com/trokky/cli/internal/client"
)

// doctorReport is GET /system/doctor (Trokky 3.6 and later).
type doctorReport struct {
Environment string `json:"environment"`
Status string `json:"status"`
CheckedAt string `json:"checkedAt"`
Checks []doctorCheck `json:"checks"`
}

type doctorCheck struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
Details []string `json:"details"`
}

var doctorCmd = &cobra.Command{
Use: "doctor",
Short: "Check a site for problems that fail silently",
Long: `Ask the site to check itself and print what it finds:

- Signing key: whether a real JWT secret is set
- Schemas: keys and field types the server silently ignores
- Storage persistence: filesystem storage that a redeploy would wipe
- Stored content: documents that fail the current schema rules (they cannot be
saved until fixed) and documents with no draft/published status

Run it before an upgrade, after changing schemas, and after a restore. It needs
Trokky 3.6 or later on the server, and the settings:read permission (held by
admins): sign in as an admin (a sign-in from an older CLI lacks the system:read
scope, so run 'trokky login' again), or use an API token with settings:read.
The site reuses a report for up to a minute.

Exits non-zero when a check fails; with --strict, also on a warning.

Example:
trokky doctor
trokky doctor --json`,
SilenceUsage: true,
// Findings exit non-zero routinely: print the error once (Execute does), not twice
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
out := cmd.OutOrStdout()
c, err := client.FromContext(cmd)
if err != nil {
return err
}
asJSON, _ := cmd.Flags().GetBool("json")
strict, _ := cmd.Flags().GetBool("strict")

data, err := c.Get("/system/doctor")
if err != nil {
return explainDoctorError(c, err)
}
var report doctorReport
if err := json.Unmarshal(data, &report); err != nil || len(report.Checks) == 0 {
return fmt.Errorf("the site's diagnostics response could not be read: %s", strings.TrimSpace(string(data)))
}

if asJSON {
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
return err
}
} else {
printDoctorReport(out, c.BaseURL, report)
}

switch {
case report.Status == "fail":
return fmt.Errorf("doctor found problems that need fixing")
case strict && report.Status == "warn":
return fmt.Errorf("doctor found warnings (--strict)")
}
return nil
},
}

func explainDoctorError(c *client.Client, err error) error {
msg := err.Error()
switch {
case strings.Contains(msg, "HTTP 404"):
// A wrong --url is a 404 too: only blame the server's version when a Trokky API answers
// there.
if !answersHealth(c) {
return fmt.Errorf("no Trokky API answered at %s: check the URL (it usually ends in /api)", c.BaseURL)
}
return fmt.Errorf("this site has no diagnostics endpoint: trokky doctor needs Trokky 3.6 or later on the server")
case strings.Contains(msg, "HTTP 403"):
return fmt.Errorf("trokky doctor needs the settings:read permission (held by admins): sign in again as an admin with 'trokky login' and allow \"Read site diagnostics\", or use an API token that has settings:read")
}
return err
}

// answersHealth reports whether a Trokky health endpoint answers 200, under the API path
// (where Trokky serves it) or at the site root (where some setups expose it).
func answersHealth(c *client.Client) bool {
urls := []string{c.BaseURL + "/health"}
if root := strings.TrimSuffix(c.BaseURL, "/api"); root != c.BaseURL {
urls = append(urls, root+"/health")
}
for _, u := range urls {
resp, err := c.HTTPClient.Get(u)
if err != nil {
continue
}
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return true
}
}
return false
}

func printDoctorReport(out io.Writer, site string, report doctorReport) {
fmt.Fprintf(out, "Site: %s (%s), checked at %s\n", site, report.Environment, report.CheckedAt)
fmt.Fprintln(out, "(The site reuses a report for up to a minute.)")
fmt.Fprintln(out)
labels := map[string]string{"ok": "ok ", "warn": "WARN", "fail": "FAIL"}
for _, check := range report.Checks {
label, known := labels[check.Status]
if !known {
label = strings.ToUpper(check.Status)
}
fmt.Fprintf(out, "[%s] %s\n", label, check.Title)
for _, detail := range check.Details {
fmt.Fprintf(out, " %s\n", detail)
}
}
fmt.Fprintln(out)
switch report.Status {
case "fail":
fmt.Fprintln(out, "Some checks failed.")
case "warn":
fmt.Fprintln(out, "No failures, some warnings.")
default:
fmt.Fprintln(out, "All checks passed.")
}
}

func init() {
doctorCmd.Flags().Bool("json", false, "print the report as JSON")
doctorCmd.Flags().Bool("strict", false, "exit non-zero on warnings too")
rootCmd.AddCommand(doctorCmd)
}
175 changes: 175 additions & 0 deletions cmd/doctor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
package cmd

import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func runDoctor(t *testing.T, args ...string) (string, string, error) {
t.Helper()
t.Setenv("HOME", t.TempDir())
t.Setenv("TROKKY_URL", "")
t.Setenv("TROKKY_TOKEN", "")
t.Setenv("TROKKY_INSTANCE", "")
for name, def := range map[string]string{"json": "false", "strict": "false"} {
if err := doctorCmd.Flags().Set(name, def); err != nil {
t.Fatal(err)
}
}
var stdout, stderr bytes.Buffer
rootCmd.SetOut(&stdout)
rootCmd.SetErr(&stderr)
defer func() {
rootCmd.SetOut(nil)
rootCmd.SetErr(nil)
}()
rootCmd.SetArgs(append([]string{"doctor"}, args...))
var err error
rawOut, rawErr := captureProcessOutput(t, func() {
err = rootCmd.Execute()
})
return stdout.String() + rawOut, stderr.String() + rawErr, err
}

func doctorServer(t *testing.T, status int, body string) *httptest.Server {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if apiPath(r) != "/system/doctor" {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
io.WriteString(w, body)
}))
t.Cleanup(server.Close)
return server
}

func reportJSON(t *testing.T, status string, checks ...doctorCheck) string {
t.Helper()
data, err := json.Marshal(map[string]interface{}{
"success": true,
"data": doctorReport{Environment: "production", Status: status, Checks: checks},
})
if err != nil {
t.Fatal(err)
}
return string(data)
}

func TestDoctorPrintsEachCheckAndFailsOnAFailure(t *testing.T) {
server := doctorServer(t, http.StatusOK, reportJSON(t, "fail",
doctorCheck{ID: "signing-key", Title: "Signing key (JWT secret)", Status: "ok", Details: []string{"Set, 48 characters."}},
doctorCheck{ID: "content", Title: "Stored content", Status: "fail", Details: []string{"posts: 2 document(s) fail validation, by field: body (2)."}},
))

stdout, _, err := runDoctor(t, "--url", server.URL+"/api", "--token", "t")
if err == nil {
t.Fatal("a failed check must exit non-zero")
}
for _, want := range []string{
"(production)",
"[ok ] Signing key (JWT secret)",
"[FAIL] Stored content",
"posts: 2 document(s) fail validation",
"Some checks failed.",
} {
if !strings.Contains(stdout, want) {
t.Errorf("output is missing %q:\n%s", want, stdout)
}
}
}

func TestDoctorWarningsPassUnlessStrict(t *testing.T) {
server := doctorServer(t, http.StatusOK, reportJSON(t, "warn",
doctorCheck{ID: "schemas", Title: "Schemas", Status: "warn", Details: []string{`page: unknown key "isSingleton"`}},
))

stdout, _, err := runDoctor(t, "--url", server.URL+"/api", "--token", "t")
if err != nil {
t.Fatalf("a warning alone must not fail: %v", err)
}
if !strings.Contains(stdout, "[WARN] Schemas") || !strings.Contains(stdout, "No failures, some warnings.") {
t.Errorf("unexpected output:\n%s", stdout)
}

if _, _, err := runDoctor(t, "--url", server.URL+"/api", "--token", "t", "--strict"); err == nil {
t.Error("--strict must fail on a warning")
}
}

func TestDoctorJSON(t *testing.T) {
server := doctorServer(t, http.StatusOK, reportJSON(t, "ok",
doctorCheck{ID: "storage", Title: "Storage persistence", Status: "ok", Details: []string{"fine"}},
))
stdout, _, err := runDoctor(t, "--url", server.URL+"/api", "--token", "t", "--json")
if err != nil {
t.Fatal(err)
}
var report doctorReport
if err := json.Unmarshal([]byte(stdout), &report); err != nil {
t.Fatalf("--json output is not the report: %v\n%s", err, stdout)
}
if report.Status != "ok" || report.Checks[0].ID != "storage" {
t.Errorf("unexpected report: %+v", report)
}
}

func TestDoctorExplainsAnOldServerAWrongURLAndAMissingPermission(t *testing.T) {
// An older server: the API answers /api/health but has no doctor endpoint
old := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/api/health" {
io.WriteString(w, `{"success":true,"data":{"status":"healthy"}}`)
return
}
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, `<!DOCTYPE html><html><body>Cannot GET /api/system/doctor</body></html>`)
}))
defer old.Close()
_, _, err := runDoctor(t, "--url", old.URL+"/api", "--token", "t")
if err == nil || !strings.Contains(err.Error(), "needs Trokky 3.6 or later") || strings.Contains(err.Error(), "<html>") {
t.Errorf("older server: error = %v", err)
}

// A server that only answers health at the root
rootOnly := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/health" {
io.WriteString(w, `{"status":"healthy"}`)
return
}
w.WriteHeader(http.StatusNotFound)
}))
defer rootOnly.Close()
_, _, err = runDoctor(t, "--url", rootOnly.URL+"/api", "--token", "t")
if err == nil || !strings.Contains(err.Error(), "needs Trokky 3.6 or later") {
t.Errorf("root health: error = %v", err)
}

// A wrong URL: nothing answers at all
wrong := doctorServer(t, http.StatusNotFound, `<html>nope</html>`)
_, _, err = runDoctor(t, "--url", wrong.URL+"/not-the-api", "--token", "t")
if err == nil || !strings.Contains(err.Error(), "no Trokky API answered") {
t.Errorf("wrong URL: error = %v", err)
}

forbidden := doctorServer(t, http.StatusForbidden, `{"success":false,"error":{"message":"nope"}}`)
_, _, err = runDoctor(t, "--url", forbidden.URL+"/api", "--token", "t")
if err == nil || !strings.Contains(err.Error(), "settings:read") || !strings.Contains(err.Error(), "API token") {
t.Errorf("forbidden: error = %v", err)
}
}

func TestDoctorRejectsAnUnreadableResponse(t *testing.T) {
server := doctorServer(t, http.StatusOK, `{"success":true,"data":{"something":"else"}}`)
if _, _, err := runDoctor(t, "--url", server.URL+"/api", "--token", "t"); err == nil || !strings.Contains(err.Error(), "could not be read") {
t.Errorf("error = %v", err)
}
}
5 changes: 3 additions & 2 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ import (
const (
ClientID = "trokky-cli"
// content:publish and media:delete are needed by restore (published documents) and by
// clean; servers before 3.5.2 ignore scopes they do not know
DefaultScopes = "openid profile content:read content:write content:delete content:publish media:read media:write media:delete offline_access"
// clean, system:read by doctor (granted to admins only); servers before 3.5.2 ignore
// scopes they do not know
DefaultScopes = "openid profile content:read content:write content:delete content:publish media:read media:write media:delete system:read offline_access"

deviceAuthPath = "/auth/device"
tokenPath = "/auth/token"
Expand Down
Loading