diff --git a/docs/adr/0018-fix-text-comes-from-the-rules.md b/docs/adr/0018-fix-text-comes-from-the-rules.md new file mode 100644 index 0000000..98505d4 --- /dev/null +++ b/docs/adr/0018-fix-text-comes-from-the-rules.md @@ -0,0 +1,57 @@ +# 0018. Fix text comes from the rules, not from a host; no shell commands in rules + +- Status: Accepted +- Date: 2026-11-24 + +## Context + +The remediation page (v0.47) shows how to fix a failing control next to the hosts that fail it. The next step proposed was +per-distribution fix commands: an optional `fix:` map in a check (`debian`, `rhel`) of shell commands, shown in `explain`, +the reports, the dashboard and the result document, proven by an e2e run that applies them to a stock container of each +supported distribution and scans it again. + +A review against the proposal found it unsafe as written: + +- **The trust path.** A result carries its fix text (`remediation`, `remediationKo`), the server stores it after checking + only its length and that it is text, and the dashboard's evidence view shows it as it came. A host that is compromised, + or anyone with its ingest token, can therefore put any text there, and the dashboard presents it as the project's + guidance. Prose that misleads does little harm; a command that an administrator copies and runs as root on many hosts + turns a compromised host into a compromised fleet, through a person. That is the outcome VISION principle 3 rules out. + Policy packs are trusted like `vmsctl.yaml` (ADR 0012), not reviewed by the project. +- **The proof proves too little.** In a container, sysctl, service and kernel checks are NOT_APPLICABLE, so their commands + pass untested. One run does not show that a command is idempotent (`sed -i '1i …'` adds a line every time), that it + works alone, or that the host stays usable (`PasswordAuthentication no` without keys, a PAM stack rewritten by + `authselect --force`, which drops sssd or MFA on a real host). `e2e/harden.sh` says it is not a hardening guide. +- **A family is not a platform.** CentOS 7, EL 9 and 10, and Amazon Linux 2023 already need different PAM steps; commands + would grow shell conditions inside rules, which every rule reviewer would then have to review as code. +- **Parameters.** Checks with `params` take values from the profile and `vmsctl.yaml`; a command with a fixed value + contradicts the policy the user set. +- **The non-goal.** VISION allows fix hints and rules out remediation. Commands grouped per family are a script in all but + name; "copy all", "export" and "let the agent run it" follow. + +## Decision + +1. **No shell commands in rules.** The fix stays prose (`remediation`, `remediation_ko`), which names the setting, the file + and the value, with short commands in backticks where one is exact (`chmod go-w`), as today. +2. **The dashboard shows the fix text of a built-in check from the server's own rules, never from the result.** The + evidence view asks the server for the control's rules (`GET /api/v1/controls/PROFILE/ID/info`) and shows their fix + text. When the server knows the control, only its rules speak: a check the rule does not list (one a host slipped in) + shows no fix at all. Only a control the server has no rules for (a policy pack's: 404) shows the text of the scan, + labelled as what the scan reported; any other failure to get the rules shows no fix. The CSV of a scan that the + dashboard offers is made the same way. The stored result itself (`GET /api/v1/scans/ID`) stays as the host sent it: + it is the host's document, the evidence. +3. If structured fixes come later, they must be: declarative (a target state such as a drop-in file, a key and a value, + a file mode) that vmsctl turns into text, so that parameters are respected and rules hold no shell; shown only from + the renderer's own rules, never carried in or read from a result; not allowed in policy packs; labelled with the + distributions they were tested on; each proven in a fresh container, applied twice, with only PASS counting; shown one + at a time under the prose, with no bulk copy, no script export and no execution by the agent. That needs a new ADR. + +## Consequences + +- A host cannot put words in the project's mouth on the dashboard: for built-in checks the fix text is the server's. +- The evidence view makes one more request the first time a control is opened (the control's rules, small; the page keeps + them while it is open, since they do not change while the server runs). +- The reports (`vmsctl report`, Markdown and HTML) still render the fix text of the results they are given; they are made + by the person who holds the results. Taking the built-in text there too is a follow-up. +- Per-distribution commands are not built. Configuration management (ComplianceAsCode, ansible-lockdown) remains the + answer for applying a baseline in bulk. diff --git a/docs/adr/README.md b/docs/adr/README.md index 5ff9916..ffe9f3b 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -22,3 +22,4 @@ Consequences. Don't edit an accepted ADR to change a decision — add a new ADR | [0015](0015-dashboard-sign-in.md) | Signing in to the dashboard: roles with the first writing feature, an authenticating proxy for OIDC (accepted) | | [0016](0016-images-and-packs-in-the-fleet-server.md) | Images and policy-pack results in the fleet server (accepted) | | [0017](0017-rename-to-vmsctl.md) | The project is renamed from hostlint to vmsctl: what changes, what keeps the old name, what is accepted both ways (accepted) | +| [0018](0018-fix-text-comes-from-the-rules.md) | Fix text comes from the rules, not from a host; no shell commands in rules (accepted) | diff --git a/docs/fleet.ko.md b/docs/fleet.ko.md index dd5ff5a..e09c322 100644 --- a/docs/fleet.ko.md +++ b/docs/fleet.ko.md @@ -1,4 +1,4 @@ - + # 서버로 모아 보기 > 설계는 [ADR 0010](adr/0010-fleet-server-and-dashboard.md)에 있습니다. 호스트가 결과를 보내고, 서버가 저장해 두었다가 조회 @@ -303,7 +303,7 @@ curl --cacert tls.crt -H "Authorization: Bearer hlt_api_..." https://vmsctl.exam | `GET /api/v1/trend` | 전체 호스트의 최근 추이를 하루에 한 점씩, 오래된 날부터: 호스트 수, 실패한 점검 항목이 있는 호스트 수, 그날 기준의 상태별 개수와 통과율, 그리고 그날 받은 스캔에서 각 호스트의 직전 스캔보다 악화된 항목 수(`worse`)와 해결된 항목 수(`fixed`)(`?days=30`, 1~90). 저장된 스캔으로 계산하므로 `server prune`을 하면 볼 수 있는 날짜가 달라지고, 같은 답을 30초 동안 재사용합니다 | | `GET /api/v1/overview` | 호스트 수, 실패한 점검 항목이 있는 호스트 수, 오래 보고하지 않은 호스트 수, 상태별 개수, 심각도와 호스트 수로 정렬한 실패 점검 항목(각각 고치면 오르는 통과율 `gain`, %p 단위), 최근 악화와 최근 해결(`?staleDays=7`) | | `GET /api/v1/hosts` | 호스트 목록과 각 호스트의 최신 스캔 개수·통과율(`?q=`, `?status=failing\|stale`, `?sort=name\|score\|last`, `?limit=`, `?offset=`, `?format=csv`, 이미지를 보려면 `?kind=image`, 레이블이 있는 호스트만 보려면 `?label=env%3Dprod`. 대시보드에서는 레이블을 눌러 거릅니다). 호스트마다 `os`, `labels`(최신 결과가 알려 준 값이고 개수에 상한이 있습니다), `agentOnline`, 최근 스캔의 통과율 `trend`도 들어 있습니다 | -| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | 점검 항목 전체와 최신 스캔의 상태별 개수(기본 제공 프로파일이면 `area`도). 점검 항목 하나의 경우 해당 호스트(호스트마다 최신 스캔 `scanId`, 실패한 호스트는 실패가 이어지기 시작한 스캔 시각 `failingSince`), 무엇을 점검하는지, 어떻게 고치는지 | +| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | 점검 항목 전체와 최신 스캔의 상태별 개수(기본 제공 프로파일이면 `area`도). 점검 항목 하나의 경우 해당 호스트(호스트마다 최신 스캔 `scanId`, 실패한 호스트는 실패가 이어지기 시작한 스캔 시각 `failingSince`), 무엇을 점검하는지, 어떻게 고치는지. `GET /api/v1/controls/PROFILE/ID/info`는 마지막 부분만 줍니다(서버에 규칙이 없는 점검 항목은 404). 대시보드는 기본 제공 점검의 조치 방법을 호스트가 보낸 결과가 아니라 여기서 가져오므로, 호스트가 대시보드의 조치 안내를 바꿀 수 없습니다([ADR 0018](adr/0018-fix-text-comes-from-the-rules.md)) | | `GET /api/v1/matrix` | 모든 호스트의 모든 점검 항목의 최신 상태. 가장 많이 실패한 호스트가 먼저 나옵니다. `?format=csv`를 붙이면 스프레드시트용 표(호스트마다 한 행, 점검 항목마다 한 열, `?lang=ko`로 열 제목을 한국어로)로 받으며, 대시보드의 매트릭스 화면에서 내려받을 수 있습니다 | | `GET /api/v1/hosts/ID` | 호스트 하나의 최신 점검 항목과 이력 | | `GET /api/v1/scans/ID` | 저장된 결과를 받은 그대로. `?format=csv`를 붙이면 `vmsctl scan --format csv`와 같은 스프레드시트용 CSV 보고서(대시보드의 호스트 이력 화면에서 내려받을 수 있습니다) | diff --git a/docs/fleet.md b/docs/fleet.md index f09cda5..dd5eb7c 100644 --- a/docs/fleet.md +++ b/docs/fleet.md @@ -267,7 +267,7 @@ curl --cacert tls.crt -H "Authorization: Bearer hlt_api_..." https://vmsctl.exam | `GET /api/v1/trend` | The fleet over the last days, one point a day, oldest first: hosts, hosts with a failing control, counts and pass rate as of that day, and `worse` and `fixed`: the controls that got worse or were fixed in the scans received that day, each against its host's previous scan (`?days=30`, 1 to 90). It is computed from the scans that are stored, so `server prune` changes the days it covers, and is served again for 30 seconds | | `GET /api/v1/overview` | Hosts, hosts with a failing control, stale hosts, counts, the failing controls ranked by severity times hosts with the `gain` in pass rate (percentage points) of fixing each, recent regressions and recent fixes (`?staleDays=7`) | | `GET /api/v1/hosts` | The hosts with the counts and score of their latest scan (`?q=`, `?status=failing\|stale`, `?sort=name\|score\|last`, `?limit=`, `?offset=`, `?format=csv`, `?kind=image` for the images, `?label=env%3Dprod` for the hosts with a label; the dashboard filters by a clicked label); each host also has its `os`, `labels` (what its latest result says, bounded), `agentOnline` and a `trend` of the pass rate of its latest scans | -| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | Every control with the status counts of the latest scans (and its `area`, for a built-in profile); one control with its hosts (each with its latest scan, `scanId`, and for a failing host `failingSince`, the first scan of the run of scans that fail it), and what it checks and how to fix it | +| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | Every control with the status counts of the latest scans (and its `area`, for a built-in profile); one control with its hosts (each with its latest scan, `scanId`, and for a failing host `failingSince`, the first scan of the run of scans that fail it), and what it checks and how to fix it; `GET /api/v1/controls/PROFILE/ID/info` is the last part alone (404 for a control the server has no rules for). The dashboard shows the fix of a built-in check from these, never from a host's result, so a host cannot change what the dashboard tells people to do ([ADR 0018](adr/0018-fix-text-comes-from-the-rules.md)) | | `GET /api/v1/matrix` | The latest status of every control on every host, hosts that fail most first; with `?format=csv`, a sheet for a spreadsheet (a row per host, a column per control, `?lang=ko` for Korean column titles; the dashboard offers it on the matrix page) | | `GET /api/v1/hosts/ID` | One host: its latest controls and its history | | `GET /api/v1/scans/ID` | A stored result, exactly as received; with `?format=csv`, the CSV report of `vmsctl scan --format csv` for a spreadsheet (the dashboard offers it in the history of a host) | diff --git a/internal/server/api.go b/internal/server/api.go index 5e4a6e8..34c6ee4 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "regexp" + "slices" "strconv" "strings" "sync" @@ -73,6 +74,7 @@ func (s *Server) routesRead(mux *http.ServeMux) { mux.HandleFunc("GET /api/v1/matrix", s.readAPI(s.handleMatrix)) mux.HandleFunc("GET /api/v1/controls", s.readAPI(s.handleControls)) mux.HandleFunc("GET /api/v1/controls/{profile}/{id}", s.readAPI(s.handleControl)) + mux.HandleFunc("GET /api/v1/controls/{profile}/{id}/info", s.readAPI(s.handleControlInfo)) mux.HandleFunc("GET /api/v1/hosts/{id}", s.readAPI(s.handleHost)) mux.HandleFunc("GET /api/v1/hosts/{id}/agent", s.readAPI(s.handleHostAgent)) mux.HandleFunc("GET /api/v1/scans/{id}", s.readAPI(s.handleScan)) @@ -337,6 +339,7 @@ func (s *Server) handleScan(w http.ResponseWriter, r *http.Request) { res.Controls[i].TitleKo = s.titleKo(res.Controls[i].Profile, res.Controls[i].ID) } } + s.trustFixes(res) var buf bytes.Buffer if err := output.Write(&buf, res, "csv", output.Options{}); err != nil { s.fail(w, err) @@ -625,6 +628,52 @@ func (s *Server) controlInfo(profile, id string) *ControlInfo { return nil } +// trustFixes replaces, in a stored result about to be shown, the fix text of the checks of built-in controls with the server's own +// (ADR 0018). A check that the rule's control does not list gets none: a host cannot slip its own text in under a built-in control. +// The controls of a policy pack's profile keep the text of the scan (the server has no rules for them). +func (s *Server) trustFixes(res *engine.Result) { + if s.cfg.Content == nil { + return + } + byRef := map[string]*engine.CheckResult{} + for i := range res.Checks { + byRef[res.Checks[i].Ref] = &res.Checks[i] + } + for _, c := range res.Controls { + ctl := s.builtinControl(c.Profile, c.ID) + if ctl == nil { + continue + } + for _, ref := range c.Checks { + ck := byRef[ref] + if ck == nil { + continue + } + rule := s.cfg.Content.Checks[ck.ID] + if rule == nil || !slices.Contains(ctl.Checks, ck.ID) { + ck.Remediation, ck.RemediationKo = "", "" + continue + } + ck.Remediation, ck.RemediationKo = strings.TrimSpace(rule.Remediation), strings.TrimSpace(rule.RemediationKo) + } + } +} + +// handleControlInfo is what a control of a built-in profile checks and how to fix it, from the server's own rules (ADR 0018): the +// fix text the dashboard shows, which a host cannot change. 404 for a control the server does not know (a policy pack's). +func (s *Server) handleControlInfo(w http.ResponseWriter, r *http.Request) { + if s.cfg.Content == nil { // not "unknown control": the dashboard would show the hosts' text for every control + writeError(w, http.StatusServiceUnavailable, "the server has no rules") + return + } + info := s.controlInfo(r.PathValue("profile"), r.PathValue("id")) + if info == nil { + writeError(w, http.StatusNotFound, "the server has no rules for this control") + return + } + writeJSON(w, http.StatusOK, info) +} + func (s *Server) handleControl(w http.ResponseWriter, r *http.Request) { after, err := staleAfter(r) if err != nil { diff --git a/internal/server/api_test.go b/internal/server/api_test.go index 040f1bf..41fd7e1 100644 --- a/internal/server/api_test.go +++ b/internal/server/api_test.go @@ -1172,3 +1172,107 @@ func TestControlFailingSince(t *testing.T) { t.Errorf("failing again: since %s, want %s (the last scan)", h.FailingSince, want) } } + +// The fix text the dashboard shows for a built-in control is the server's own (ADR 0018); a control it does not know has none. +func TestControlInfo(t *testing.T) { + f := newAPIFixture(t) + content, err := engine.Load(rules.FS, profiles.FS) + if err != nil { + t.Fatal(err) + } + srv := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }, Content: content}) + get := func(path string) (int, []byte) { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+f.api) + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.Bytes() + } + code, body := get("/api/v1/controls/kisa-2026/U-01/info") + var info ControlInfo + if err := json.Unmarshal(body, &info); code != http.StatusOK || err != nil || len(info.Checks) == 0 { + t.Fatalf("%d %s", code, body) + } + want := strings.TrimSpace(content.Checks[info.Checks[0].ID].Remediation) + if want == "" || info.Checks[0].Remediation != want { + t.Errorf("remediation %q, want the rule's %q", info.Checks[0].Remediation, want) + } + if code, _ := get("/api/v1/controls/x-acme/A-01/info"); code != http.StatusNotFound { + t.Errorf("a pack's control: %d", code) + } + // a read endpoint: not without a token + req := httptest.NewRequest(http.MethodGet, "/api/v1/controls/kisa-2026/U-01/info", nil) + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Errorf("without a token: %d", rec.Code) + } +} + +// A host cannot put its own fix text in what the server shows (ADR 0018): the CSV of a scan takes the fix of a built-in check from +// the server's rules, and a check that a built-in control does not list (slipped in by the host) gets none. +func TestScanCSVFixFromRules(t *testing.T) { + f := newAPIFixture(t) + content, err := engine.Load(rules.FS, profiles.FS) + if err != nil { + t.Fatal(err) + } + srv := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }, Content: content}) + var doc map[string]any + if err := json.Unmarshal(fixture(t, "web-01.json"), &doc); err != nil { + t.Fatal(err) + } + doc["scan"].(map[string]any)["id"] = "web-01-planted" + for _, c := range doc["checks"].([]any) { + if c.(map[string]any)["status"] == "FAIL" { + c.(map[string]any)["remediation"] = "PLANTED run this" + } + } + // a check of the host's own under the built-in control U-01, failing with its own "fix" + doc["checks"] = append(doc["checks"].([]any), map[string]any{"ref": "x-evil.fix", "id": "x-evil.fix", "title": "x", "severity": "high", "status": "FAIL", "statusSource": "observed", "remediation": "PLANTED too"}) + for _, c := range doc["controls"].([]any) { + if c.(map[string]any)["id"] == "U-01" { + c.(map[string]any)["checks"] = append([]any{"x-evil.fix"}, c.(map[string]any)["checks"].([]any)...) + c.(map[string]any)["status"] = "FAIL" + } + } + raw, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + f.clock = f.clock.Add(time.Hour) + if code, out := post(t, f.srv, token(t, f.store, ScopeIngest, ""), raw); code != http.StatusCreated { + t.Fatalf("not stored: %d %v", code, out) + } + var scans struct { + Scans []ScanRow `json:"scans"` + } + var hosts struct { + Hosts []struct{ ID int64 } `json:"hosts"` + } + f.json(t, "/api/v1/hosts?q=web-01", &hosts) + f.json(t, "/api/v1/hosts/"+itoa(hosts.Hosts[0].ID), &scans) + req := httptest.NewRequest(http.MethodGet, "/api/v1/scans/"+itoa(scans.Scans[0].ID)+"?format=csv", nil) + req.Header.Set("Authorization", "Bearer "+f.api) + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + body := rec.Body.String() + if strings.Contains(body, "PLANTED") { + t.Errorf("the host's fix text is in the CSV:\n%s", body) + } + if want := strings.Fields(strings.TrimSpace(content.Checks["ssh.permit-root-login"].Remediation))[0]; !strings.Contains(body, want) { + t.Errorf("the rule's fix is not in the CSV") + } + // a server without rules does not answer "unknown control", which would send the dashboard to the hosts' text + bare := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }}) + req = httptest.NewRequest(http.MethodGet, "/api/v1/controls/kisa-2026/U-01/info", nil) + req.Header.Set("Authorization", "Bearer "+f.api) + rec = httptest.NewRecorder() + bare.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusServiceUnavailable { + t.Errorf("without rules: %d", rec.Code) + } +} diff --git a/web/scripts/record-demo.mjs b/web/scripts/record-demo.mjs index 8d3e490..4e88b36 100644 --- a/web/scripts/record-demo.mjs +++ b/web/scripts/record-demo.mjs @@ -65,6 +65,8 @@ for (const pair of pairs) { for (const id of latest) await record(`/api/v1/scans/${id}`); for (const c of controls.values()) { await record(`/api/v1/controls/${encodeURIComponent(c.profile)}/${encodeURIComponent(c.id)}?staleDays=${STALE}`); + // the fix text of the evidence view comes from the server's rules (ADR 0018) + await record(`/api/v1/controls/${encodeURIComponent(c.profile)}/${encodeURIComponent(c.id)}/info`, { optional: true }); } // When it was recorded: the demo moves every time forward by the age of the file, so "41 minutes ago" stays that. diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 948de2c..23efb8a 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -76,6 +76,25 @@ function withProfile(path: string): string { const json = { "Content-Type": "application/json" }; +// The rules of a control do not change while the page is open: asked once per control (ADR 0018). +const infos = new Map>(); + +/** What a control of a built-in profile checks and how to fix it, from the server's rules; null when the server has no rules for it + * (404: a policy pack's control). Any other failure is an error, never null: null lets the scan's own fix text be shown. */ +function controlInfo(profile: string, id: string): Promise { + const key = `${profile}/${id}`; + let p = infos.get(key); + if (!p) { + p = request(`/api/v1/controls/${encodeURIComponent(profile)}/${encodeURIComponent(id)}/info`).catch((e: unknown) => { + if ((e as { status?: number })?.status === 404) return null; + infos.delete(key); // a failure is asked again next time + throw e; + }); + infos.set(key, p); + } + return p; +} + export const api = { session: () => request<{ authenticated: boolean; canScan?: boolean }>("/api/v1/session"), login: (token: string) => request<{ ok: boolean; name: string }>("/api/v1/login", { method: "POST", headers: json, body: JSON.stringify({ token }) }), @@ -90,6 +109,7 @@ export const api = { controls: () => request<{ controls: ControlSummary[] }>(withProfile("/api/v1/controls")), control: (profile: string, id: string, staleDays: number) => request<{ control: ControlDetail; info: ControlInfo | null }>(`/api/v1/controls/${encodeURIComponent(profile)}/${encodeURIComponent(id)}?staleDays=${staleDays}`), + controlInfo, matrix: (staleDays: number) => request(withProfile(`/api/v1/matrix?staleDays=${staleDays}`)), host: (id: number, staleDays: number) => request(withProfile(`/api/v1/hosts/${id}?staleDays=${staleDays}`)), hostAgent: (id: number) => request(`/api/v1/hosts/${id}/agent`), diff --git a/web/src/lib/i18n.tsx b/web/src/lib/i18n.tsx index 21b6b5b..695f925 100644 --- a/web/src/lib/i18n.tsx +++ b/web/src/lib/i18n.tsx @@ -102,6 +102,7 @@ const en = { "scan.refused": "The request was refused: {error}", "scan.hint": "Ask the agent on this host for a scan with one of the profiles it allows.", "host.howToFix": "How to fix:", + "host.fixFromScan": "as the scan reported it", "overview.trend": "Pass rate over time", "overview.trendHelp": "The fleet as it was each day: every host's latest scan until then.", "trend.days": "{n} days", @@ -320,6 +321,7 @@ const ko: Record = { "scan.refused": "요청이 거부되었습니다: {error}", "scan.hint": "이 호스트의 에이전트에게 허용된 프로파일 중 하나로 스캔을 요청합니다.", "host.howToFix": "조치 방법:", + "host.fixFromScan": "스캔이 보낸 내용", "overview.trend": "시간에 따른 통과율", "overview.trendHelp": "그날 기준으로 각 호스트의 가장 최근 스캔을 모아 계산한 모습입니다.", "trend.days": "{n}일", diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 51176f1..d1d4962 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -51,7 +51,7 @@ export interface Diff { } // The stored result document: only the parts the dashboard shows. Every string is host text. export interface Evidence { key: string; text: string; source?: string } -export interface DocCheck { ref: string; title: string; titleKo?: string; status: Status; reason?: string; reasonKo?: string; remediation?: string; remediationKo?: string; evidence?: Evidence[]; evidenceOmitted?: number } +export interface DocCheck { ref: string; id?: string; title: string; titleKo?: string; status: Status; reason?: string; reasonKo?: string; remediation?: string; remediationKo?: string; evidence?: Evidence[]; evidenceOmitted?: number } export interface DocControl { profile: string; id: string; reason?: string; checks: string[]; waiver?: { reason: string; expires: string } } export interface ScanDoc { controls: DocControl[]; checks: DocCheck[] } diff --git a/web/src/pages/Fix.tsx b/web/src/pages/Fix.tsx index ed901b7..fb5fa80 100644 --- a/web/src/pages/Fix.tsx +++ b/web/src/pages/Fix.tsx @@ -7,7 +7,7 @@ import { Await, Empty, Inline, PageHeader, Severity, Skeleton, StatusBadge } fro import { IconSearch } from "../components/icons"; import { ControlDetail } from "./Host"; import { STALE_DAYS } from "./Overview"; -import type { ControlHost, ControlSummary, ScanDoc } from "../lib/types"; +import type { ControlHost, ControlInfo, ControlSummary, ScanDoc } from "../lib/types"; /** The weight of a severity in the order to fix in, as the server's (internal/server, the overview's "fix first"). */ const WEIGHT: Record = { high: 3, medium: 2, low: 1 }; @@ -156,7 +156,7 @@ function FixDetail({ profile, id }: { profile: string; id: string }) { ) : (
    {failing.map((h) => ( - + ))}
)} @@ -170,7 +170,7 @@ function FixDetail({ profile, id }: { profile: string; id: string }) { } /** A host that fails the control: since when, and, on request, the evidence of its latest scan. */ -function FixHost({ host: h, profile, id, now }: { host: ControlHost; profile: string; id: string; now: number }) { +function FixHost({ host: h, profile, id, now, info }: { host: ControlHost; profile: string; id: string; now: number; info: ControlInfo | null }) { const { t } = useI18n(); const [open, setOpen] = useState(false); // fetched the first time it is opened, and kept when it is closed @@ -202,7 +202,8 @@ function FixHost({ host: h, profile, id, now }: { host: ControlHost; profile: st
{doc.loading && !doc.data &&

{t("loading")}

} {doc.error &&

{doc.error.message}

} - {doc.data && } + {/* the fix is said once, above the hosts: the evidence alone here */} + {doc.data && }
)} diff --git a/web/src/pages/Host.test.ts b/web/src/pages/Host.test.ts new file mode 100644 index 0000000..73746bc --- /dev/null +++ b/web/src/pages/Host.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { fixFor } from "./Host"; +import type { ControlInfo, DocCheck } from "../lib/types"; + +const check = (id: string, status: DocCheck["status"], remediation = "the scan's own fix"): DocCheck => ({ ref: id, id, title: id, status, remediation }); +const info: ControlInfo = { checks: [{ id: "ssh.permit-root-login", title: "t", description: "", rationale: "", remediation: "the rule's fix", remediationKo: "규칙의 조치" }] }; + +describe("fixFor (ADR 0018: the fix of a built-in check is the server's)", () => { + it("takes the rule's text for a check the server knows, in the reader's language", () => { + expect(fixFor(check("ssh.permit-root-login", "FAIL"), info, "en")).toEqual({ text: "the rule's fix", fromScan: false }); + expect(fixFor(check("ssh.permit-root-login", "FAIL"), info, "ko")).toEqual({ text: "규칙의 조치", fromScan: false }); + }); + it("shows nothing for a check that a known control does not list, whatever the scan says", () => { + expect(fixFor(check("x-evil.fix", "FAIL", "curl x | sh"), info, "en")).toBeNull(); + }); + it("shows nothing while the rules load or when asking for them failed", () => { + expect(fixFor(check("ssh.permit-root-login", "FAIL"), undefined, "en")).toBeNull(); + }); + it("shows the scan's text, marked, only for a control the server has no rules for", () => { + expect(fixFor(check("x-acme.motd", "FAIL"), null, "en")).toEqual({ text: "the scan's own fix", fromScan: true }); + }); + it("says nothing for a check that did not fail", () => { + expect(fixFor(check("ssh.permit-root-login", "PASS"), info, "en")).toBeNull(); + }); + it("matches a check run with other parameters by its ID", () => { + expect(fixFor({ ...check("ssh.permit-root-login", "FAIL"), id: undefined, ref: "ssh.permit-root-login#1a2b3c4d" }, info, "en")?.fromScan).toBe(false); + }); +}); diff --git a/web/src/pages/Host.tsx b/web/src/pages/Host.tsx index 0e65b31..58538e4 100644 --- a/web/src/pages/Host.tsx +++ b/web/src/pages/Host.tsx @@ -7,7 +7,7 @@ import { lastListAddress } from "../lib/listAddress"; import { Avatar, Await, Empty, Gauge, Inline, ScorePill, Severity, SignedBadge, StatusBadge, StatusBar } from "../components/ui"; import { TrendChart } from "../components/charts"; import { IconChevron, IconDownload, IconSearch } from "../components/icons"; -import { STATUSES, type ControlChange, type ControlRow, type Diff, type HostDetail, type ScanDoc, type ScanRow, type Status } from "../lib/types"; +import { STATUSES, type ControlChange, type ControlInfo, type ControlRow, type Diff, type DocCheck, type HostDetail, type ScanDoc, type ScanRow, type Status } from "../lib/types"; import { STALE_DAYS } from "./Overview"; export function HostPage({ id }: { id: number }) { @@ -184,6 +184,15 @@ function Controls({ controls, scanId, worse, focus, onFocused }: { controls: Con // The stored result holds the evidence. It is fetched the first time a control is opened and kept. const [wanted, setWanted] = useState(false); const doc = useAsync(() => (wanted ? api.scan(scanId) : Promise.resolve(null as ScanDoc | null)), [wanted, scanId]); + // The open control's rules on the server: its fix text (ADR 0018). A control the server does not know answers 404: null. + const openControl = controls.find((c) => `${c.profile}/${c.id}` === open); + // the answer carries the control it is for, so that the previous control's answer is never taken for this one's + const infoState = useAsync( + () => (openControl ? api.controlInfo(openControl.profile, openControl.id).then((info) => ({ key: open, info })) : Promise.resolve(null)), + [openControl?.profile, openControl?.id], + false, + ); + const info = infoState.data && infoState.data.key === open && !infoState.error ? infoState.data.info : undefined; const rows = useMemo(() => { const needle = q.trim().toLowerCase(); @@ -291,7 +300,7 @@ function Controls({ controls, scanId, worse, focus, onFocused }: { controls: Con
{doc.loading && !doc.data &&

{t("loading")}

} {doc.error &&

{doc.error.message}

} - {doc.data && } + {doc.data && }
)} @@ -333,8 +342,12 @@ function groupByArea(rows: ControlRow[], all: ControlRow[]): AreaGroup[] { return [...groups.values()].filter((g) => g.rows.length > 0); } -/** The checks of a control and what they observed. All of it is host text: shown as text only. */ -export function ControlDetail({ control, doc }: { control: Pick; doc: ScanDoc }) { +/** + * The checks of a control and what they observed. All of it is host text: shown as text only. The fix of a built-in check is the + * server's own (info, from its rules; ADR 0018): a host cannot change it. Only a check the server does not know (a policy pack's) + * shows the fix the scan reported, labelled so. info is undefined while it loads. + */ +export function ControlDetail({ control, doc, info, showFix = true }: { control: Pick; doc: ScanDoc; info: ControlInfo | null | undefined; showFix?: boolean }) { const { t, lang } = useI18n(); const dc = doc.controls.find((x) => x.profile === control.profile && x.id === control.id); const checks = (dc?.checks ?? []).map((ref) => doc.checks.find((c) => c.ref === ref)).filter((c) => c !== undefined); @@ -349,11 +362,7 @@ export function ControlDetail({ control, doc }: { control: Pick {ch.ref} {localized(lang, ch.title, ch.titleKo)} {ch.reason &&

{localized(lang, ch.reason, ch.reasonKo)}

} - {ch.remediation && ( -

- {t("host.howToFix")} -

- )} + {showFix && } {(ch.evidence?.length ?? 0) > 0 ? (
               {ch.evidence?.map((e) => `${e.text.startsWith(e.key) ? "" : `${e.key} `}${e.text}${e.source ? `   ${e.source}` : ""}`).join("\n")}
@@ -368,6 +377,38 @@ export function ControlDetail({ control, doc }: { control: Pick c.id === id);
+    const text = rule ? localized(lang, rule.remediation, rule.remediationKo) : "";
+    return text ? { text, fromScan: false } : null;
+  }
+  const text = ch.remediation ? localized(lang, ch.remediation, ch.remediationKo) : "";
+  return text ? { text, fromScan: true } : null;
+}
+
+function Fix({ check, info }: { check: DocCheck; info: ControlInfo | null | undefined }) {
+  const { t, lang } = useI18n();
+  const fix = fixFor(check, info, lang);
+  if (!fix) return null;
+  return fix.fromScan ? (
+    

+ {t("host.howToFix")} ({t("host.fixFromScan")}) {fix.text} +

+ ) : ( +

+ {t("host.howToFix")} +

+ ); +} + function History({ scans, initial }: { scans: ScanRow[]; initial: [number, number] | null }) { const { t } = useI18n(); const now = useNow();