Skip to content

Commit 82ebd77

Browse files
joe4devclaude
andcommitted
fix(app-inspector): normalise empty IAM parameters; keep the analyzer's ENGINE_ONLY recommendation
From a second review round: - empty strings and lists count as absent for the IAM actions before any check, so newer_than "" lists the first page as such; a prefix-only newer_than ("nt:") is rejected - explain-iam rejects a newer_than value passed as its pagination_token - the analyzer skips its recommendation only on its failure titles, so a status in a state it doesn't know (ENGINE_ONLY) keeps it - the analyzer handler tests answer with JSON, so the failure test reaches the failure it names Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2c93b8d commit 82ebd77

4 files changed

Lines changed: 90 additions & 14 deletions

File tree

‎src/tools-tests/localstack-app-inspector.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,33 @@ describe("list-iam-denials", () => {
372372
expect(sent).toEqual([]);
373373
});
374374

375+
test("an empty or prefix-only newer_than never lists old denials as new", async () => {
376+
route("GET", IAM_EVENTS, (r) =>
377+
r.query.name === "iam.policy.denied"
378+
? { body: { events: [iamEvent(missingPermission)], pagination: { prev_cursor: "P" } } }
379+
: undefined
380+
);
381+
headerRoutes();
382+
const empty = text(await call({ action: "list-iam-denials", newer_than: "" }));
383+
expect(denialsCall().query).toEqual({ limit: "20", name: "iam.policy.denied" });
384+
expect(empty).toContain("## IAM Denials (1)");
385+
expect(empty).not.toContain("New IAM Denials");
386+
const prefixOnly = await call({ action: "list-iam-denials", newer_than: "nt:" });
387+
expect(prefixOnly.isError).toBe(true);
388+
expect(text(prefixOnly)).toContain("Cursor Not Usable");
389+
});
390+
391+
test("an empty list counts as absent, and explain-iam rejects a newer_than value", async () => {
392+
route("GET", IAM_EVENTS, (r) =>
393+
r.query.name === "iam.policy.denied" ? { body: { events: [] } } : undefined
394+
);
395+
headerRoutes();
396+
expect((await call({ action: "list-iam-denials", trace_ids: [] })).isError).toBeUndefined();
397+
const swapped = await call({ action: "explain-iam", span_id: "s", pagination_token: "nt:C" });
398+
expect(swapped.isError).toBe(true);
399+
expect(text(swapped)).toContain("Cursor Not Usable");
400+
});
401+
375402
test("an empty string counts as absent", async () => {
376403
route("GET", IAM_EVENTS, (r) =>
377404
r.query.name === "iam.policy.denied" ? { body: { events: [] } } : undefined

‎src/tools-tests/localstack-iam-policy-analyzer.test.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,20 +54,37 @@ test("the handler adds no recommendation to an error", async () => {
5454
expect(result.content[0].text).not.toContain("Recommended");
5555
});
5656

57+
const json = (body: unknown, status = 200) =>
58+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
59+
5760
test("the handler adds no recommendation to a markdown failure", async () => {
5861
process.env.MCP_ANALYTICS_DISABLED = "1";
5962
process.env.LOCALSTACK_AUTH_TOKEN = "ls-FAKE";
6063
global.fetch = jest.fn(async (input: string | URL | Request) => {
6164
const path = new URL(String(input)).pathname;
62-
if (path === "/_localstack/health") return new Response(JSON.stringify({ services: {} }));
65+
if (path === "/_localstack/health") return json({ services: { s3: "running" } });
6366
if (path === "/_localstack/licenseinfo") {
64-
return new Response(
65-
JSON.stringify({ available_plugins: ["localstack.platform.plugin/iam-enforcement"] })
66-
);
67+
return json({ available_plugins: ["localstack.platform.plugin/iam-enforcement"] });
6768
}
6869
return new Response("nope", { status: 404 });
6970
}) as typeof fetch;
7071
const result = await localstackIamPolicyAnalyzer({ action: "get-status", mode: undefined });
71-
expect(result.content[0].text).toMatch(/^\s*(❌|⚠️)/u);
72+
expect(result.content[0].text).toContain("IAM Configuration Not Available");
7273
expect(result.content[0].text).not.toContain("Recommended");
7374
});
75+
76+
test("a status in a state the analyzer doesn't know keeps the recommendation", async () => {
77+
process.env.MCP_ANALYTICS_DISABLED = "1";
78+
process.env.LOCALSTACK_AUTH_TOKEN = "ls-FAKE";
79+
global.fetch = jest.fn(async (input: string | URL | Request) => {
80+
const path = new URL(String(input)).pathname;
81+
if (path === "/_localstack/health") return json({ services: { s3: "running" } });
82+
if (path === "/_localstack/licenseinfo") {
83+
return json({ available_plugins: ["localstack.platform.plugin/iam-enforcement"] });
84+
}
85+
return json({ state: "ENGINE_ONLY" });
86+
}) as typeof fetch;
87+
const result = await localstackIamPolicyAnalyzer({ action: "get-status", mode: undefined });
88+
expect(result.content[0].text).toContain("ENGINE_ONLY");
89+
expect(result.content[0].text).toContain("**Recommended:**");
90+
});

‎src/tools/localstack-app-inspector.ts‎

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,10 @@ export const metadata: ToolMetadata = {
206206
},
207207
};
208208

209-
export default async function localstackAppInspector(params: AppInspectorArgs) {
210-
const { action } = params;
209+
export default async function localstackAppInspector(raw: AppInspectorArgs) {
210+
const { action } = raw;
211+
// Empty strings and lists count as absent for the IAM actions, so every check, handler and analytics see one value
212+
const params = IAM_ACTIONS.has(action) ? withoutEmptyValues(raw) : raw;
211213
return withToolAnalytics(
212214
"localstack-app-inspector",
213215
buildAppInspectorAnalyticsArgs(params),
@@ -302,12 +304,29 @@ function requiredFeature(action: AppInspectorArgs["action"]): ProFeature {
302304
}
303305
}
304306

307+
/** The parameters without empty strings and empty lists, which some clients send for unset optional fields */
308+
export function withoutEmptyValues(params: AppInspectorArgs): AppInspectorArgs {
309+
return Object.fromEntries(
310+
Object.entries(params).filter(
311+
([, value]) => value !== "" && !(Array.isArray(value) && value.length === 0)
312+
)
313+
) as AppInspectorArgs;
314+
}
315+
305316
export function validateIamParams(params: AppInspectorArgs) {
306317
const allowed = IAM_ACTION_PARAMS[params.action];
307318
if (!allowed) return null;
308319
for (const key of Object.keys(params) as Array<keyof AppInspectorArgs>) {
309320
const value = params[key];
310-
if (key === "action" || value === undefined || value === "" || allowed.includes(key)) continue;
321+
// Empty values are also skipped here for direct callers; the handler has already removed them
322+
if (
323+
key === "action" ||
324+
value === undefined ||
325+
value === "" ||
326+
(Array.isArray(value) && value.length === 0) ||
327+
allowed.includes(key)
328+
)
329+
continue;
311330
const owners = Object.entries(IAM_ACTION_PARAMS)
312331
.filter(([, keys]) => keys.includes(key))
313332
.map(([name]) => `\`${name}\``);
@@ -325,7 +344,11 @@ export function validateIamParams(params: AppInspectorArgs) {
325344
);
326345
}
327346
// A swapped cursor would list older denials as new: LocalStack encodes the direction inside it
328-
if (params.newer_than && !params.newer_than.startsWith(NEWER_THAN_PREFIX)) {
347+
if (
348+
params.newer_than !== undefined &&
349+
(!params.newer_than.startsWith(NEWER_THAN_PREFIX) ||
350+
params.newer_than.length === NEWER_THAN_PREFIX.length)
351+
) {
329352
return ResponseBuilder.error(
330353
"Cursor Not Usable",
331354
`\`newer_than\` takes the value printed after "newer_than" in a first page's footer (it starts with \`${NEWER_THAN_PREFIX}\`), not a \`pagination_token\` or a time.`
@@ -345,6 +368,12 @@ export function validateIamParams(params: AppInspectorArgs) {
345368
}
346369
break;
347370
case "explain-iam":
371+
if (params.pagination_token?.startsWith(NEWER_THAN_PREFIX)) {
372+
return ResponseBuilder.error(
373+
"Cursor Not Usable",
374+
"This is a `newer_than` value of list-iam-denials, not a `pagination_token` of explain-iam."
375+
);
376+
}
348377
if (params.event_id && params.span_id) {
349378
return ResponseBuilder.error(
350379
"Invalid Parameters",
@@ -585,9 +614,10 @@ async function countEvaluationErrors(client: AppInspectorApiClient): Promise<num
585614
async function handleListDenials(client: AppInspectorApiClient, params: AppInspectorArgs) {
586615
const result = await client.listIamEvents("*", "*", {
587616
limit: params.limit ?? DEFAULT_DENIALS_LIMIT,
588-
pagination_token: params.newer_than
589-
? params.newer_than.slice(NEWER_THAN_PREFIX.length)
590-
: params.pagination_token,
617+
pagination_token:
618+
params.newer_than !== undefined
619+
? params.newer_than.slice(NEWER_THAN_PREFIX.length)
620+
: params.pagination_token,
591621
name: IAM_DENIED_EVENT_NAME,
592622
});
593623
if (!result.success) return formatEventsError(result);

‎src/tools/localstack-iam-policy-analyzer.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@ export default async function localstackIamPolicyAnalyzer({
5757
return withToolAnalytics("localstack-iam-policy-analyzer", { action, mode }, async () => {
5858
const response = await runAction(action, mode);
5959
// No pointer on errors, so an agent is never sent back and forth; the App Inspector-based actions only when licensed
60-
// Some failures are markdown starting with ❌ or ⚠️ rather than isError
60+
// Some failures are markdown with a failure title rather than isError; a status with an unknown state is not one
6161
const first = (response as { content?: Array<{ text?: string }> }).content?.[0]?.text ?? "";
62-
if ((response as { isError?: boolean }).isError || /^\s*(❌|⚠️)/u.test(first)) return response;
62+
const failure =
63+
/^\s*(❌|⚠️) \*\*(Failed to|Policy Analysis Failed|LocalStack IAM Configuration Not Available)/u;
64+
if ((response as { isError?: boolean }).isError || failure.test(first)) return response;
6365
if (action === "analyze-policies") {
6466
const license = await checkProFeature(ProFeature.APP_INSPECTOR);
6567
if (!license.isSupported) return response;

0 commit comments

Comments
 (0)