Spaces:
Restarting

loopable / web /src /settings /CompliancePane.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
c72f0a1 verified
Raw History Blame Contribute Delete
6.89 kB
import { useEffect, useState } from "react";
import { API_V1, CREDENTIALS, checkTenant, UNAUTHORIZED_EVENT } from "../apiContract";
import "../styles/wave59/security.css";
type ClaimState = "met" | "not_met" | "unproven";
type Claim = {
id: string;
group: string;
claim: string;
state: ClaimState;
evidence: string;
source: string | null;
};
type Compliance = { claims: Claim[]; generated_at: number };
const STATE_WORDS: Record<ClaimState, string> = {
met: "Met", not_met: "Not met", unproven: "Unproven",
};
const UNAVAILABLE = "Amazon compliance could not be loaded.";
function requireResponse(response: Response): void {
if (checkTenant(response)) throw new Error(UNAVAILABLE);
if (response.status === 401) {
window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
throw new Error("Sign in again to view Amazon compliance.");
}
if (response.status === 403) throw new Error("Amazon compliance is available to administrators only.");
if (!response.ok) throw new Error(UNAVAILABLE);
}
function isClaim(value: unknown): value is Claim {
if (!value || typeof value !== "object") return false;
const row = value as Record<string, unknown>;
return ["id", "group", "claim", "evidence"].every((key) =>
typeof row[key] === "string" && row[key].trim().length > 0)
&& (row.state === "met" || row.state === "not_met" || row.state === "unproven")
&& (row.source === null || typeof row.source === "string");
}
function readCompliance(value: unknown): Compliance {
if (!value || typeof value !== "object") throw new Error(UNAVAILABLE);
const payload = value as Record<string, unknown>;
if (!Array.isArray(payload.claims) || !payload.claims.length || !payload.claims.every(isClaim)
|| new Set(payload.claims.map((row) => row.id)).size !== payload.claims.length
|| typeof payload.generated_at !== "number" || !Number.isFinite(payload.generated_at)) {
throw new Error(UNAVAILABLE);
}
return { claims: payload.claims, generated_at: payload.generated_at };
}
export default function CompliancePane() {
const [payload, setPayload] = useState<Compliance | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [downloading, setDownloading] = useState(false);
const [notice, setNotice] = useState("");
const [revision, setRevision] = useState(0);
const [downloadError, setDownloadError] = useState(false);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError("");
setDownloadError(false);
async function load() {
try {
const response = await fetch(`${API_V1}/security/compliance`, {
credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
});
requireResponse(response);
const result = readCompliance(await response.json());
if (!controller.signal.aborted) setPayload(result);
} catch (failure) {
if (!controller.signal.aborted) {
setError(failure instanceof Error && [UNAVAILABLE,
"Sign in again to view Amazon compliance.",
"Amazon compliance is available to administrators only."].includes(failure.message)
? failure.message : UNAVAILABLE);
}
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}
void load();
return () => controller.abort();
}, [revision]);
async function downloadEvidence() {
if (downloading) return;
setDownloading(true);
setError("");
setDownloadError(false);
setNotice("");
try {
const response = await fetch(`${API_V1}/security/compliance/export`, {
credentials: CREDENTIALS, cache: "no-store",
});
requireResponse(response);
if (!response.headers.get("Content-Type")?.startsWith("text/plain")) throw new Error(UNAVAILABLE);
const body = await response.text();
const url = URL.createObjectURL(new Blob([body], { type: "text/plain;charset=utf-8" }));
const anchor = window.document.createElement("a");
anchor.href = url;
anchor.download = "amazon-compliance.txt";
window.document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
setNotice("amazon-compliance.txt downloaded. It contains no credential or other secret.");
} catch {
setError("The evidence file could not be downloaded.");
setDownloadError(true);
} finally {
setDownloading(false);
}
}
const groups = new Map<string, Claim[]>();
for (const claim of payload?.claims ?? []) {
const rows = groups.get(claim.group) ?? [];
rows.push(claim);
groups.set(claim.group, rows);
}
return (
<div className="set-pane">
<h3 className="set-h">Amazon compliance</h3>
{loading ? <div className="set-skeleton" role="status" aria-label="Reading the current controls" aria-busy="true">
<span className="set-skeleton-line" aria-hidden="true" />
<span className="set-skeleton-line" aria-hidden="true" />
<span className="set-skeleton-line" aria-hidden="true" />
</div> : null}
{error ? <div className="set-error" role="alert"><span>{error}</span>
<button type="button" className="set-secondary" disabled={downloading} onClick={() => {
if (downloadError) void downloadEvidence();
else setRevision(value => value + 1);
}}>Retry</button></div> : null}
{!loading && payload ? <>
<p className="set-help">Observed {new Date(payload.generated_at * 1000).toLocaleString()}.</p>
<button type="button" className="security-compliance-download set-primary" disabled={downloading}
onClick={() => void downloadEvidence()}>
{downloading ? "Preparing the evidence file…" : "Download the evidence file"}
</button>
{notice ? <p className="set-help" role="status">{notice}</p> : null}
{Array.from(groups, ([group, claims]) => (
<section className="security-compliance-group" key={group}>
<h4 className="security-compliance-heading">{group}</h4>
<ul className="security-compliance-list">
{claims.map((claim) => (
<li className="security-compliance-row" key={claim.id} data-claim-id={claim.id}>
<div className="security-compliance-claim">
<span>{claim.claim}</span>
<span className={`security-compliance-state is-${claim.state.replace("_", "-")}`}>
{STATE_WORDS[claim.state]}
</span>
</div>
<p className="security-compliance-evidence">{claim.evidence}</p>
</li>
))}
</ul>
</section>
))}
</> : null}
</div>
);
}