Skip to content

Commit c5090b9

Browse files
authored
refactor(policy): centralize doctor health-check descriptors (#117578)
1 parent ebf121a commit c5090b9

11 files changed

Lines changed: 454 additions & 880 deletions

File tree

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import type {
2+
HealthCheckContext,
3+
HealthFinding,
4+
HealthRepairContext,
5+
HealthRepairResult,
6+
} from "openclaw/plugin-sdk/health";
7+
import { describe, expect, it, vi } from "vitest";
8+
import { createPolicyScopedChecks } from "./check-factory.js";
9+
import { CHECK_IDS } from "./check-ids.js";
10+
import type { PolicyEvaluation } from "./types.js";
11+
12+
describe("policy scoped health checks", () => {
13+
const evaluation = {} as PolicyEvaluation;
14+
const context = {} as HealthCheckContext;
15+
16+
it("preserves registration order, descriptions, metadata, and repair capability", () => {
17+
const repair = vi.fn(async (): Promise<HealthRepairResult> => ({ changes: [] }));
18+
const checks = createPolicyScopedChecks(
19+
{
20+
evaluatePolicy: vi.fn(async () => evaluation),
21+
findingsForCheck: vi.fn(() => []),
22+
},
23+
[
24+
[CHECK_IDS.policyMissingFile, "The policy file exists."],
25+
[CHECK_IDS.policyDeniedChannelProvider, "Channels satisfy policy.", repair],
26+
],
27+
);
28+
29+
expect(
30+
checks.map(({ id, description, kind, source }) => ({ id, description, kind, source })),
31+
).toEqual([
32+
{
33+
id: CHECK_IDS.policyMissingFile,
34+
description: "The policy file exists.",
35+
kind: "plugin",
36+
source: "policy",
37+
},
38+
{
39+
id: CHECK_IDS.policyDeniedChannelProvider,
40+
description: "Channels satisfy policy.",
41+
kind: "plugin",
42+
source: "policy",
43+
},
44+
]);
45+
expect(Object.hasOwn(checks[0]!, "repair")).toBe(false);
46+
expect(Object.hasOwn(checks[1]!, "repair")).toBe(true);
47+
expect(checks[1]).toMatchObject({ repair });
48+
});
49+
50+
it("awaits the policy evaluation before selecting findings for the same check", async () => {
51+
const findings: HealthFinding[] = [
52+
{ checkId: CHECK_IDS.policyMissingFile, severity: "error", message: "Missing policy." },
53+
];
54+
let releaseEvaluation!: () => void;
55+
const evaluationGate = new Promise<void>((resolve) => {
56+
releaseEvaluation = resolve;
57+
});
58+
const evaluatePolicy = vi.fn(async (received: HealthCheckContext) => {
59+
expect(received).toBe(context);
60+
await evaluationGate;
61+
return evaluation;
62+
});
63+
const findingsForCheck = vi.fn(() => findings);
64+
const [check] = createPolicyScopedChecks({ evaluatePolicy, findingsForCheck }, [
65+
[CHECK_IDS.policyMissingFile, "The policy file exists."],
66+
]);
67+
68+
const result = check!.detect(context);
69+
expect(evaluatePolicy).toHaveBeenCalledOnce();
70+
expect(findingsForCheck).not.toHaveBeenCalled();
71+
72+
releaseEvaluation();
73+
await expect(result).resolves.toBe(findings);
74+
expect(findingsForCheck).toHaveBeenCalledExactlyOnceWith(
75+
evaluation,
76+
CHECK_IDS.policyMissingFile,
77+
);
78+
});
79+
80+
it("propagates evaluation failures without selecting findings", async () => {
81+
const failure = new Error("policy evaluation failed");
82+
const evaluatePolicy = vi.fn(async () => {
83+
throw failure;
84+
});
85+
const findingsForCheck = vi.fn(() => []);
86+
const [check] = createPolicyScopedChecks({ evaluatePolicy, findingsForCheck }, [
87+
[CHECK_IDS.policyMissingFile, "The policy file exists."],
88+
]);
89+
90+
await expect(check!.detect(context)).rejects.toBe(failure);
91+
expect(findingsForCheck).not.toHaveBeenCalled();
92+
});
93+
94+
it("retains the original repair callback and its exact result promise", () => {
95+
const repairContext = {} as HealthRepairContext;
96+
const findings: HealthFinding[] = [];
97+
const pendingRepair = Promise.resolve<HealthRepairResult>({ changes: ["repaired"] });
98+
const repair = vi.fn(() => pendingRepair);
99+
const [check] = createPolicyScopedChecks(
100+
{
101+
evaluatePolicy: vi.fn(async () => evaluation),
102+
findingsForCheck: vi.fn(() => []),
103+
},
104+
[[CHECK_IDS.policyDeniedChannelProvider, "Channels satisfy policy.", repair]],
105+
);
106+
107+
expect(check).toMatchObject({ repair });
108+
expect(check!.repair!(repairContext, findings)).toBe(pendingRepair);
109+
expect(repair).toHaveBeenCalledExactlyOnceWith(repairContext, findings);
110+
});
111+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { HealthCheck } from "openclaw/plugin-sdk/health";
2+
import type { POLICY_CHECK_IDS } from "./check-ids.js";
3+
import type { PolicyDoctorCheckDeps } from "./types.js";
4+
5+
type PolicyDoctorCheckDefinition = readonly [
6+
id: (typeof POLICY_CHECK_IDS)[number],
7+
description: string,
8+
repair?: NonNullable<HealthCheck["repair"]>,
9+
];
10+
11+
export function createPolicyScopedChecks(
12+
deps: Pick<PolicyDoctorCheckDeps, "evaluatePolicy" | "findingsForCheck">,
13+
definitions: readonly PolicyDoctorCheckDefinition[],
14+
): readonly HealthCheck[] {
15+
const { evaluatePolicy, findingsForCheck } = deps;
16+
return definitions.map(([id, description, repair]) => ({
17+
id,
18+
kind: "plugin",
19+
description,
20+
source: "policy",
21+
async detect(ctx) {
22+
return findingsForCheck(await evaluatePolicy(ctx), id);
23+
},
24+
...(repair ? { repair } : {}),
25+
}));
26+
}
Lines changed: 54 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Policy doctor health-check factories for one policy scope.
22
import type { HealthCheck } from "openclaw/plugin-sdk/health";
33
import { repairPolicyAutomaticNarrower } from "../automatic-repairs.js";
4+
import { createPolicyScopedChecks } from "../check-factory.js";
45
import { CHECK_IDS } from "../check-ids.js";
56
import type { PolicyDoctorCheckDeps } from "../types.js";
67

@@ -10,109 +11,66 @@ export function createPolicyChannelProviderChecks(
1011
const {
1112
channelIdsFromFindings,
1213
disableChannels,
13-
evaluatePolicy,
14-
findingsForCheck,
1514
workspaceRepairsDisabledResult,
1615
workspaceRepairsEnabled,
1716
} = deps;
1817

19-
const policyChannelsDeniedProviderCheck: HealthCheck = {
20-
id: CHECK_IDS.policyDeniedChannelProvider,
21-
kind: "plugin",
22-
description: "Configured channels satisfy policy deny rules.",
23-
source: "policy",
24-
async detect(ctx) {
25-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyDeniedChannelProvider);
26-
},
27-
async repair(ctx, findings) {
28-
if (!workspaceRepairsEnabled(ctx)) {
29-
return workspaceRepairsDisabledResult("channel config");
30-
}
31-
const channelIds = channelIdsFromFindings(findings);
32-
if (channelIds.length === 0) {
18+
return createPolicyScopedChecks(deps, [
19+
[
20+
CHECK_IDS.policyDeniedChannelProvider,
21+
"Configured channels satisfy policy deny rules.",
22+
async (ctx, findings) => {
23+
if (!workspaceRepairsEnabled(ctx)) {
24+
return workspaceRepairsDisabledResult("channel config");
25+
}
26+
const channelIds = channelIdsFromFindings(findings);
27+
if (channelIds.length === 0) {
28+
return {
29+
status: "skipped",
30+
reason: "no channel findings matched a configurable channel",
31+
changes: [],
32+
};
33+
}
34+
const next = disableChannels(ctx.cfg, channelIds);
35+
if (next.changed.length === 0) {
36+
return {
37+
status: "skipped",
38+
reason: "matching channels were already disabled or missing",
39+
changes: [],
40+
};
41+
}
3342
return {
34-
status: "skipped",
35-
reason: "no channel findings matched a configurable channel",
36-
changes: [],
43+
config: next.config,
44+
changes: next.changed.map(
45+
(id) => `Disabled channels.${id}.enabled for policy conformance.`,
46+
),
3747
};
38-
}
39-
const next = disableChannels(ctx.cfg, channelIds);
40-
if (next.changed.length === 0) {
41-
return {
42-
status: "skipped",
43-
reason: "matching channels were already disabled or missing",
44-
changes: [],
45-
};
46-
}
47-
return {
48-
config: next.config,
49-
changes: next.changed.map(
50-
(id) => `Disabled channels.${id}.enabled for policy conformance.`,
51-
),
52-
};
53-
},
54-
};
55-
56-
return [policyChannelsDeniedProviderCheck];
48+
},
49+
],
50+
]);
5751
}
5852

5953
export function createPolicyIngressChecks(deps: PolicyDoctorCheckDeps): readonly HealthCheck[] {
60-
const { evaluatePolicy, findingsForCheck } = deps;
61-
62-
const policyIngressDmPolicyUnapprovedCheck: HealthCheck = {
63-
id: CHECK_IDS.policyIngressDmPolicyUnapproved,
64-
kind: "plugin",
65-
description: "Channel direct-message access policy matches ingress requirements.",
66-
source: "policy",
67-
async detect(ctx) {
68-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyIngressDmPolicyUnapproved);
69-
},
70-
};
71-
const policyIngressDmScopeUnapprovedCheck: HealthCheck = {
72-
id: CHECK_IDS.policyIngressDmScopeUnapproved,
73-
kind: "plugin",
74-
description: "Direct-message sessions use the policy-required isolation scope.",
75-
source: "policy",
76-
async detect(ctx) {
77-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyIngressDmScopeUnapproved);
78-
},
79-
};
80-
const policyIngressOpenGroupsDeniedCheck: HealthCheck = {
81-
id: CHECK_IDS.policyIngressOpenGroupsDenied,
82-
kind: "plugin",
83-
description: "Channel group access does not use open group policy when denied.",
84-
source: "policy",
85-
async detect(ctx) {
86-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyIngressOpenGroupsDenied);
87-
},
88-
async repair(ctx, findings) {
89-
return repairPolicyAutomaticNarrower(ctx, findings, CHECK_IDS.policyIngressOpenGroupsDenied);
90-
},
91-
};
92-
const policyIngressGroupMentionRequiredCheck: HealthCheck = {
93-
id: CHECK_IDS.policyIngressGroupMentionRequired,
94-
kind: "plugin",
95-
description: "Channel group access keeps mention gates enabled when required.",
96-
source: "policy",
97-
async detect(ctx) {
98-
return findingsForCheck(
99-
await evaluatePolicy(ctx),
100-
CHECK_IDS.policyIngressGroupMentionRequired,
101-
);
102-
},
103-
async repair(ctx, findings) {
104-
return repairPolicyAutomaticNarrower(
105-
ctx,
106-
findings,
107-
CHECK_IDS.policyIngressGroupMentionRequired,
108-
);
109-
},
110-
};
111-
112-
return [
113-
policyIngressDmPolicyUnapprovedCheck,
114-
policyIngressDmScopeUnapprovedCheck,
115-
policyIngressOpenGroupsDeniedCheck,
116-
policyIngressGroupMentionRequiredCheck,
117-
];
54+
return createPolicyScopedChecks(deps, [
55+
[
56+
CHECK_IDS.policyIngressDmPolicyUnapproved,
57+
"Channel direct-message access policy matches ingress requirements.",
58+
],
59+
[
60+
CHECK_IDS.policyIngressDmScopeUnapproved,
61+
"Direct-message sessions use the policy-required isolation scope.",
62+
],
63+
[
64+
CHECK_IDS.policyIngressOpenGroupsDenied,
65+
"Channel group access does not use open group policy when denied.",
66+
async (ctx, findings) =>
67+
repairPolicyAutomaticNarrower(ctx, findings, CHECK_IDS.policyIngressOpenGroupsDenied),
68+
],
69+
[
70+
CHECK_IDS.policyIngressGroupMentionRequired,
71+
"Channel group access keeps mention gates enabled when required.",
72+
async (ctx, findings) =>
73+
repairPolicyAutomaticNarrower(ctx, findings, CHECK_IDS.policyIngressGroupMentionRequired),
74+
],
75+
]);
11876
}
Lines changed: 10 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,17 @@
11
// Policy doctor health-check factories for one policy scope.
22
import type { HealthCheck } from "openclaw/plugin-sdk/health";
3+
import { createPolicyScopedChecks } from "../check-factory.js";
34
import { CHECK_IDS } from "../check-ids.js";
45
import type { PolicyDoctorCheckDeps } from "../types.js";
56

67
export function createPolicyCoreChecks(deps: PolicyDoctorCheckDeps): readonly HealthCheck[] {
7-
const { evaluatePolicy, findingsForCheck } = deps;
8-
9-
const policyMissingFileCheck: HealthCheck = {
10-
id: CHECK_IDS.policyMissingFile,
11-
kind: "plugin",
12-
description: "The enabled Policy plugin has a policy file to verify.",
13-
source: "policy",
14-
async detect(ctx) {
15-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyMissingFile);
16-
},
17-
};
18-
const policyHashMismatchCheck: HealthCheck = {
19-
id: CHECK_IDS.policyHashMismatch,
20-
kind: "plugin",
21-
description: "The policy file matches the configured expected hash.",
22-
source: "policy",
23-
async detect(ctx) {
24-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyHashMismatch);
25-
},
26-
};
27-
const policyAttestationMismatchCheck: HealthCheck = {
28-
id: CHECK_IDS.policyAttestationMismatch,
29-
kind: "plugin",
30-
description: "The current policy check matches the accepted attestation.",
31-
source: "policy",
32-
async detect(ctx) {
33-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyAttestationMismatch);
34-
},
35-
};
36-
const policyInvalidFileCheck: HealthCheck = {
37-
id: CHECK_IDS.policyInvalidFile,
38-
kind: "plugin",
39-
description: "The enabled policy file parses before policy checks run.",
40-
source: "policy",
41-
async detect(ctx) {
42-
return findingsForCheck(await evaluatePolicy(ctx), CHECK_IDS.policyInvalidFile);
43-
},
44-
};
45-
46-
return [
47-
policyMissingFileCheck,
48-
policyInvalidFileCheck,
49-
policyHashMismatchCheck,
50-
policyAttestationMismatchCheck,
51-
];
8+
return createPolicyScopedChecks(deps, [
9+
[CHECK_IDS.policyMissingFile, "The enabled Policy plugin has a policy file to verify."],
10+
[CHECK_IDS.policyInvalidFile, "The enabled policy file parses before policy checks run."],
11+
[CHECK_IDS.policyHashMismatch, "The policy file matches the configured expected hash."],
12+
[
13+
CHECK_IDS.policyAttestationMismatch,
14+
"The current policy check matches the accepted attestation.",
15+
],
16+
]);
5217
}

0 commit comments

Comments
 (0)