Spaces:
Running

File size: 9,302 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"use client";

import { ScaleIcon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";

import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";

import type { PolicyRuleOut } from "./types";

interface CompileError {
  message: string;
  errors?: string[];
  question?: string | null;
}

function compileError(err: unknown): CompileError | null {
  if (!(err instanceof ApiError)) return null;
  const d = (err.body as { detail?: unknown } | undefined)?.detail;
  if (d && typeof d === "object" && "message" in d) return d as CompileError;
  return { message: err.detail };
}

function RuleCard({ rule, children }: { rule: PolicyRuleOut; children?: React.ReactNode }) {
  const { t, m } = useI18n();
  return (
    <article className="space-y-3 rounded-lg border bg-card p-4" data-testid="rule" data-status={rule.status}>
      <div className="flex flex-wrap items-center gap-2">
        <Badge variant={rule.status === "active" ? "default" : "secondary"}>{(m.nlrules.statuses as Record<string, string>)[rule.status] ?? rule.status}</Badge>
        <span className="tabular text-xs text-muted-foreground">{t("nlrules.version", { n: rule.version })}</span>
        <span className="text-sm text-muted-foreground">“{rule.text}”</span>
      </div>
      <p className="text-sm font-medium" data-testid="rule-plain">
        {rule.plain}
      </p>
      {children}
    </article>
  );
}

function TestsTable({ rule }: { rule: PolicyRuleOut }) {
  const { t } = useI18n();
  return (
    <div className="overflow-x-auto">
      <p className="mb-1 text-xs font-medium text-muted-foreground">{t("nlrules.tests")}</p>
      <table className="w-full text-sm" data-testid="rule-tests">
        <thead className="text-start text-xs text-muted-foreground">
          <tr>
            <th className="py-1 text-start font-normal">{t("nlrules.call")}</th>
            <th className="py-1 text-start font-normal">{t("nlrules.actor")}</th>
            <th className="py-1 text-start font-normal">{t("nlrules.outcome")}</th>
          </tr>
        </thead>
        <tbody>
          {rule.tests.map((x, i) => (
            <tr key={i} className="border-t">
              <td className="py-1 font-mono text-xs" dir="ltr">
                {x.tool}({Object.entries(x.args).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ")})
              </td>
              <td className="py-1 text-xs">{x.actor}</td>
              <td className={cn("py-1 text-xs", x.matched ? "font-medium text-warning" : "text-muted-foreground")}>
                {x.matched ? `${t("nlrules.matched")}: ${x.outcome}` : t("nlrules.notMatched")}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export function RulesView() {
  const { t } = useI18n();
  const { hasRole } = useAuth();
  const owner = hasRole("owner");
  const rules = useApi<PolicyRuleOut[]>("/ext/rules");
  const [text, setText] = useState("");
  const [draft, setDraft] = useState<PolicyRuleOut | null>(null);
  const [problem, setProblem] = useState<CompileError | null>(null);
  const [allowPermit, setAllowPermit] = useState(false);
  const [busy, setBusy] = useState(false);

  const compile = async (e: FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setProblem(null);
    setDraft(null);
    try {
      setDraft(await api<PolicyRuleOut>("/ext/rules/compile", { method: "POST", body: { text } }));
    } catch (err) {
      setProblem(compileError(err) ?? { message: t("common.error") });
    } finally {
      setBusy(false);
    }
  };

  const confirm = async () => {
    if (!draft) return;
    try {
      await api(`/ext/rules/${draft.id}/confirm`, { method: "POST", body: { allow_permit: allowPermit } });
      toast.success(t("nlrules.confirmed"));
      setDraft(null);
      setText("");
      rules.reload();
    } catch (err) {
      toast.error(compileError(err)?.message ?? t("common.error"));
    }
  };

  const act = async (rule: PolicyRuleOut, action: "rollback" | "disable") => {
    try {
      await api(`/ext/rules/${rule.rule_key}/${action}`, { method: "POST" });
      toast.success(action === "rollback" ? t("nlrules.rolledBack") : t("nlrules.disabledToast"));
      rules.reload();
    } catch (err) {
      toast.error(compileError(err)?.message ?? t("common.error"));
    }
  };

  const active = rules.data?.filter((r) => r.status === "active") ?? [];
  const history = rules.data?.filter((r) => r.status !== "active" && r.status !== "draft") ?? [];

  return (
    <div className="space-y-6">
      <PageHeader title={t("nlrules.title")} subtitle={t("nlrules.subtitle")} />

      <form onSubmit={compile} className="space-y-3 rounded-lg border bg-card p-4">
        <Textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder={t("nlrules.placeholder")}
          aria-label={t("nlrules.placeholder")}
          rows={2}
          minLength={3}
          maxLength={500}
          required
        />
        <Button type="submit" disabled={busy || text.trim().length < 3}>
          {t("nlrules.compile")}
        </Button>
      </form>

      {problem && (
        <div role="alert" className="rounded-lg border border-warning/40 bg-warning-soft px-4 py-3 text-sm" data-testid="rule-problem">
          {problem.question ? (
            <>
              <p className="font-medium">{t("nlrules.question")}</p>
              <p>{problem.question}</p>
            </>
          ) : (
            <>
              <p className="font-medium">{problem.message}</p>
              {problem.errors?.map((e) => (
                <p key={e} className="text-xs">
                  {e}
                </p>
              ))}
            </>
          )}
        </div>
      )}

      {draft && (
        <section aria-label={t("nlrules.draft")} data-testid="rule-draft">
          <RuleCard rule={draft}>
            <p className="text-xs text-muted-foreground">{t("nlrules.understood")}</p>
            <TestsTable rule={draft} />
            <details>
              <summary className="cursor-pointer text-xs text-muted-foreground">{t("nlrules.policy")}</summary>
              <pre dir="ltr" className="mt-2 overflow-x-auto rounded-md bg-muted p-2 text-xs" data-testid="rule-cedar">
                {draft.cedar}
              </pre>
            </details>
            {owner ? (
              <div className="flex flex-wrap items-center gap-3">
                {draft.ast.effect === "permit" && (
                  <label className="flex items-center gap-2 text-sm">
                    <input type="checkbox" checked={allowPermit} onChange={(e) => setAllowPermit(e.target.checked)} />
                    {t("nlrules.allowPermit")}
                  </label>
                )}
                <Button onClick={confirm} disabled={draft.ast.effect === "permit" && !allowPermit}>
                  {t("nlrules.confirm")}
                </Button>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground">{t("nlrules.ownerOnly")}</p>
            )}
          </RuleCard>
        </section>
      )}

      <section className="space-y-3">
        <h2 className="text-sm font-semibold">{t("nlrules.active")}</h2>
        {rules.error && <ErrorState error={rules.error} onRetry={rules.reload} />}
        {!rules.data && !rules.error && <Skeleton className="h-24 w-full" />}
        {rules.data && active.length === 0 && <EmptyState icon={ScaleIcon} title={t("nlrules.noRules")} />}
        {active.map((r) => (
          <RuleCard key={r.id} rule={r}>
            {owner && (
              <div className="flex gap-2">
                {r.version > 1 && (
                  <Button size="sm" variant="outline" onClick={() => void act(r, "rollback")}>
                    {t("nlrules.rollback")}
                  </Button>
                )}
                <Button size="sm" variant="ghost" onClick={() => void act(r, "disable")}>
                  {t("nlrules.disable")}
                </Button>
              </div>
            )}
          </RuleCard>
        ))}
      </section>

      {history.length > 0 && (
        <section className="space-y-2">
          <h2 className="text-sm font-semibold">{t("nlrules.history")}</h2>
          <ul className="space-y-1 text-sm text-muted-foreground">
            {history.map((r) => (
              <li key={r.id}>
                <Badge variant="secondary">{r.status}</Badge> {t("nlrules.version", { n: r.version })} — {r.plain}
              </li>
            ))}
          </ul>
        </section>
      )}
    </div>
  );
}