Skip to content
Merged
9,407 changes: 9,407 additions & 0 deletions lib/cli/lib/openapi/openapi.0.6.0.yaml

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions lib/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"js-yaml": "^4.3.2",
"json-schema-merge-allof": "^0.8.1",
"openapi-types": "^12.1.3",
"semver": "^7.7.4",
"swagger-ui-express": "^5.0.1",
"zod": "catalog:"
},
Expand All @@ -78,6 +79,7 @@
"@types/js-yaml": "^4.0.9",
"@types/json-schema-merge-allof": "^0.6.5",
"@types/node": "catalog:",
"@types/semver": "^7.7.1",
"@types/supertest": "^7.2.1",
"@types/swagger-ui-express": "^4.1.8",
"@typespec/json-schema": "catalog:",
Expand Down
41 changes: 38 additions & 3 deletions lib/cli/src/__tests__/commands/check/check-args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
CheckSpecArgsSchema,
CheckSpecOptionsSchema,
availableVersions,
parseBaseVersions,
} from "../../../commands/check/check-args";

describe("Check Args Validation", () => {
Expand Down Expand Up @@ -91,7 +92,7 @@ describe("Check Args Validation", () => {
// #########################################################

describe("CheckSpecOptionsSchema", () => {
it.each(["0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0"])(
it.each(["0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0", "0.6.0"])(
"should accept valid protocolVersion %s",
version => {
const result = CheckSpecOptionsSchema.safeParse({
Expand All @@ -101,8 +102,9 @@ describe("Check Args Validation", () => {
}
);

it("should list 0.5.0 as the latest (default) protocolVersion", () => {
expect(availableVersions[0]).toBe("0.5.0");
it("should default to 0.6.0 when no protocolVersion flag is passed", () => {
// The newest bundled version is the default when no flag is passed
expect(availableVersions[0]).toBe("0.6.0");
});

it("should reject invalid protocolVersion", () => {
Expand All @@ -125,4 +127,37 @@ describe("Check Args Validation", () => {
expect(result.success).toBe(true);
});
});

// #########################################################
// # Parse Base Versions
// #########################################################

describe("parseBaseVersions", () => {
it("should sort versions newest first by version number, not by string", () => {
// Arrange
const fileNames = ["openapi.0.9.0.yaml", "openapi.0.10.0.yaml", "openapi.0.2.0.yaml"];

// Act
const versions = parseBaseVersions(fileNames);

// Assert
expect(versions).toEqual(["0.10.0", "0.9.0", "0.2.0"]);
});

it("should ignore files whose name does not match openapi.<semver>.yaml", () => {
// Arrange
const fileNames = [
"openapi.0.5.0.yaml",
"openapi.latest.yaml",
"README.md",
"openapi.0.10.0.yaml",
];

// Act
const versions = parseBaseVersions(fileNames);

// Assert
expect(versions).toEqual(["0.10.0", "0.5.0"]);
});
});
});
161 changes: 152 additions & 9 deletions lib/cli/src/__tests__/commands/check/check-service-file.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
import { vi } from "vitest";
import { DefaultCheckService } from "../../../commands/check/check-service";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as yaml from "js-yaml";
import { OpenAPIV3 } from "openapi-types";

const mockConsoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
const mockConsoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
const mockConsoleError = vi.spyOn(console, "error").mockImplementation(() => {});

afterAll(() => {
mockConsoleLog.mockRestore();
mockConsoleWarn.mockRestore();
mockConsoleError.mockRestore();
});

// No mocks - we want to test the real behavior
describe("DefaultCheckService - Circular References", () => {
let service: DefaultCheckService;
const mockConsoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
const mockConsoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
const mockConsoleError = vi.spyOn(console, "error").mockImplementation(() => {});

beforeEach(() => {
service = new DefaultCheckService();
vi.clearAllMocks();
});

afterAll(() => {
mockConsoleLog.mockRestore();
mockConsoleWarn.mockRestore();
mockConsoleError.mockRestore();
});

it("should handle circular references gracefully with the fix", async () => {
// This test uses the actual test files we created and verified manually
const basePath = path.join(__dirname, "test-files/base.yaml");
Expand Down Expand Up @@ -53,3 +58,141 @@ describe("DefaultCheckService - Circular References", () => {
expect(mockConsoleError).not.toHaveBeenCalled();
});
});

describe("DefaultCheckService - Bundled Base Specs", () => {
const VERSION_PARAM_REF = "#/components/parameters/CommonGrants.Headers.VersionRequest";
let service: DefaultCheckService;
let tmpDir: string;

beforeEach(() => {
service = new DefaultCheckService();
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cg-check-"));
vi.clearAllMocks();
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

/** Load a base spec bundled with the CLI, to edit into an implementation spec */
function loadBundledSpec(version: string): OpenAPIV3.Document {
const specPath = path.resolve(__dirname, `../../../../lib/openapi/openapi.${version}.yaml`);
return yaml.load(fs.readFileSync(specPath, "utf8")) as OpenAPIV3.Document;
}

/** Write an implementation spec to a temp file and return its path */
function writeTempSpec(doc: OpenAPIV3.Document): string {
const specPath = path.join(tmpDir, "impl.yaml");
fs.writeFileSync(specPath, yaml.dump(doc));
return specPath;
}

function removeVersionParam(operation: OpenAPIV3.OperationObject): void {
operation.parameters = operation.parameters!.filter(
param => !("$ref" in param) || param.$ref !== VERSION_PARAM_REF
);
}

function prefixPaths(doc: OpenAPIV3.Document, prefix: string): OpenAPIV3.Document {
const paths = Object.entries(doc.paths).map(([route, item]) => [`${prefix}${route}`, item]);
return { ...doc, paths: Object.fromEntries(paths) };
}

it("should use the bundled 0.6.0 base spec when protocolVersion is 0.6.0", async () => {
// The 0.6.0 base is the simplest spec that is compliant with itself
const implPath = path.resolve(__dirname, "../../../../lib/openapi/openapi.0.6.0.yaml");

// Act & Assert - Should resolve without a "Base spec file not found" error
await service.checkSpec(implPath, { protocolVersion: "0.6.0" });

// Verify success
expect(mockConsoleLog).toHaveBeenCalledWith("Spec is valid and compliant with base spec");
});

it.each(["0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0"])(
"should leave the output unchanged when checking the bundled %s spec against itself",
async version => {
const implPath = path.resolve(__dirname, `../../../../lib/openapi/openapi.${version}.yaml`);

// Act & Assert - Pre-0.6.0 specs have no version headers and must be unaffected
await service.checkSpec(implPath, { protocolVersion: version });

// Verify the exact success output and no warnings
expect(mockConsoleLog).toHaveBeenCalledWith("Spec is valid and compliant with base spec");
expect(mockConsoleWarn).not.toHaveBeenCalled();
}
);

it("should report operations missing the CG-Version parameter or CG-Version-Served header", async () => {
const impl = loadBundledSpec("0.6.0");
removeVersionParam(impl.paths["/common-grants/opportunities"]!.get!);
const read = impl.paths["/common-grants/opportunities/{oppId}"]!.get!;
delete (read.responses["200"] as OpenAPIV3.ResponseObject).headers!["CG-Version-Served"];

// Act & Assert - Both operations should be reported end to end
const result = service.checkSpec(writeTempSpec(impl), { protocolVersion: "0.6.0" });
await expect(result).rejects.toThrow(/GET \/common-grants\/opportunities\b(?!\/)/);
await expect(result).rejects.toThrow("[CG-Version]");
await expect(result).rejects.toThrow("GET /common-grants/opportunities/{oppId}");
await expect(result).rejects.toThrow("CG-Version-Served");
});

it("should report missing version headers on an experimental route", async () => {
const impl = loadBundledSpec("0.6.0");
const list = impl.paths["/common-grants/forms"]!.get!;
expect(list.tags).toContain("experimental");
removeVersionParam(list);
delete (list.responses["200"] as OpenAPIV3.ResponseObject).headers;

// Act & Assert - Experimental routes skip the other checks but not the headers
const result = service.checkSpec(writeTempSpec(impl), { protocolVersion: "0.6.0" });
await expect(result).rejects.toThrow("GET /common-grants/forms");
await expect(result).rejects.toThrow("[CG-Version]");
await expect(result).rejects.toThrow("[CG-Version-Served]");
});

it("should accept the CG-Version parameter declared once on the path item", async () => {
const impl = loadBundledSpec("0.6.0");
const pathItem = impl.paths["/common-grants/opportunities"]!;
removeVersionParam(pathItem.get!);
pathItem.parameters = [{ $ref: VERSION_PARAM_REF }];

// Act & Assert - Neither a missing header nor an extra "PARAMETERS" route is reported
await service.checkSpec(writeTempSpec(impl), { protocolVersion: "0.6.0" });

// Verify success
expect(mockConsoleLog).toHaveBeenCalledWith("Spec is valid and compliant with base spec");
});

it("should report one error when routes carry a version segment instead of listing missing routes", async () => {
const impl = prefixPaths(loadBundledSpec("0.6.0"), "/v0.6");

// Act
const result = service.checkSpec(writeTempSpec(impl), { protocolVersion: "0.6.0" });

// Assert - One error points at the CG-Version header; no per-route findings
await expect(result).rejects.toThrow("CG-Version");
await expect(result).rejects.toThrow("/v0.6/common-grants/");
await expect(result).rejects.toThrow("1 errors");
await expect(result).rejects.not.toThrow("Routes missing");
});

it("should not point at the CG-Version header when checking against a version without it", async () => {
const impl = prefixPaths(loadBundledSpec("0.5.0"), "/v0.5");

// Act
const result = service.checkSpec(writeTempSpec(impl), { protocolVersion: "0.5.0" });

// Assert - Still one error instead of the missing routes, without the header advice
await expect(result).rejects.toThrow("/v0.5/common-grants/");
await expect(result).rejects.toThrow("1 errors");
await expect(result).rejects.not.toThrow("CG-Version");
});

it("should default to 0.6.0 when no protocol version is given", async () => {
const implPath = path.resolve(__dirname, "../../../../lib/openapi/openapi.0.5.0.yaml");

// Act & Assert - 0.5.0 has no version headers, so the 0.6.0 default must flag them
await expect(service.checkSpec(implPath, {})).rejects.toThrow("[CG-Version]");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,48 @@ describe("checkExtraRoutes", () => {
// Assert - No errors
expect(errors.getErrorCount()).toBe(0);
});

// ############################################################
// Ignore path item fields that aren't operations
// ############################################################

it("should not flag path-level parameters or summary as extra routes", () => {
// Arrange - Create base spec with one route
const baseDoc: OpenAPIV3.Document = {
openapi: "3.0.0",
info: { title: "Base", version: "1.0.0" },
paths: {
"/common-grants/foo": {
get: {
responses: {
"200": { description: "OK" },
},
},
},
},
};

// Arrange - Create impl spec that declares a header once for the whole path
const implDoc: OpenAPIV3.Document = {
openapi: "3.0.0",
info: { title: "Impl", version: "1.0.0" },
paths: {
"/common-grants/foo": {
summary: "Foo",
parameters: [{ name: "CG-Version", in: "header" }],
get: {
responses: {
"200": { description: "OK" },
},
},
},
},
};

// Act
const errors = checkExtraRoutes(baseDoc, implDoc);

// Assert - No errors
expect(errors.getErrorCount()).toBe(0);
});
});
Loading
Loading