diff --git a/README.md b/README.md index 5c7194d8..39f308e2 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Thanks to our sponsors for supporting this project! ### API Info - API license must be present and non-empty string +- License url and identifier are mutually exclusive, at most one of them may be set (OpenAPI 3.1) - API description must be present and non-empty string - API contact must be present and non-empty string diff --git a/cli/src/test/java/org/openapitools/openapistylevalidator/cli/ValidationInitiatorTest.java b/cli/src/test/java/org/openapitools/openapistylevalidator/cli/ValidationInitiatorTest.java index 06017d19..58c93671 100644 --- a/cli/src/test/java/org/openapitools/openapistylevalidator/cli/ValidationInitiatorTest.java +++ b/cli/src/test/java/org/openapitools/openapistylevalidator/cli/ValidationInitiatorTest.java @@ -308,6 +308,29 @@ void shouldNotFailWhenThereAreNoPaths() throws Throwable { assertDoesNotThrow(() -> validationInitiator.validate(optionManager, commandLine)); } + + /** + * See https://github.com/OpenAPITools/openapi-style-validator/issues/92 + * + *

End-to-end, the swagger-parser only carries `license.identifier` + * when the license declares no `url`: a license declaring both is + * reported by the parser itself as an unexpected attribute and the + * identifier never reaches the validator. The flagging of a license + * declaring both is therefore covered by the unit tests of the lib + * module, this only asserts that a 3.1 license using `identifier` + * alone passes the validation. + */ + @Test + void shouldAcceptLicenseWithIdentifierOnly() throws ParseException { + CommandLine commandLine = parser.parse(options, new String[] { + "-s", "src/test/resources/licenseIdentifierOnly.yaml", + "-o", "src/test/resources/default.json" + }); + + List errorList = validationInitiator.validate(optionManager, commandLine); + + assertEquals(0, errorList.size()); + } } private void assertThrowsIllegalArgumentExceptionWithExceptedMessage( diff --git a/cli/src/test/resources/licenseIdentifierOnly.yaml b/cli/src/test/resources/licenseIdentifierOnly.yaml new file mode 100644 index 00000000..9939d476 --- /dev/null +++ b/cli/src/test/resources/licenseIdentifierOnly.yaml @@ -0,0 +1,24 @@ +openapi: 3.1.0 +info: + title: Example specification + version: '1.0' + description: Example API + contact: + name: OpenAPI Tools + email: team@openapitools.org + license: + name: Eclipse Public License 2.0 + identifier: EPL-2.0 +servers: + - url: 'http://localhost:8080/' +paths: + /ping: + get: + operationId: ping + summary: A simple get call + description: When this method is called, the server answers with 200 OKs + tags: + - demo + responses: + '200': + description: OK diff --git a/lib/build.gradle b/lib/build.gradle index 5ec0211a..c180608b 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -6,6 +6,7 @@ dependencies { implementation 'org.eclipse.microprofile.openapi:microprofile-openapi-api:3.1.1' testImplementation 'org.slf4j:slf4j-jdk14:2.0.16' testImplementation 'org.openapitools.empoa:empoa-simple-models-impl:2.1.0' + testImplementation 'io.swagger.core.v3:swagger-models:2.2.23' testImplementation 'nl.jqno.equalsverifier:equalsverifier:3.16.2' } diff --git a/lib/src/main/java/org/openapitools/openapistylevalidator/ErrorAggregator.java b/lib/src/main/java/org/openapitools/openapistylevalidator/ErrorAggregator.java index 416518f0..e3bb8539 100644 --- a/lib/src/main/java/org/openapitools/openapistylevalidator/ErrorAggregator.java +++ b/lib/src/main/java/org/openapitools/openapistylevalidator/ErrorAggregator.java @@ -34,6 +34,14 @@ void validateMinimumInfo( } } + void logLicenseUrlAndIdentifierBothSet() { + errorList.add(new GenericStyleError( + StyleError.StyleCheckSection.APIInfo, + "license", + "url|identifier", + "The license url and identifier are mutually exclusive, only one of them should be set")); + } + List getErrorList() { return errorList; } diff --git a/lib/src/main/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidator.java b/lib/src/main/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidator.java index 10a0671e..a3a0107e 100644 --- a/lib/src/main/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidator.java +++ b/lib/src/main/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidator.java @@ -1,5 +1,6 @@ package org.openapitools.openapistylevalidator; +import java.lang.reflect.Method; import java.util.*; import org.eclipse.microprofile.openapi.models.OpenAPI; import org.eclipse.microprofile.openapi.models.Operation; @@ -46,6 +47,42 @@ private void validateStructure() { } } + /* + * The `identifier` field of the license object was introduced by OpenAPI + * 3.1.0. The MicroProfile OpenAPI API this library is built against (3.1) + * predates it and declares no `identifier` accessor: `getIdentifier()` + * exists only on models aligned with OAS 3.1, such as the MicroProfile + * OpenAPI 4.0 API. + * + * The CLI, Gradle and Maven plugins parse specifications with + * swagger-parser and convert the result through empoa-swagger-core, whose + * wrapper keeps the underlying swagger model - which does carry + * `identifier` - behind its `getSw()` accessor. + * + * Both situations are handled reflectively so the check works with any of + * them; when neither is available, no identifier is reported. + * See https://github.com/OpenAPITools/openapi-style-validator/issues/92 + */ + private static String getLicenseIdentifier(License license) { + try { + Method getIdentifier = license.getClass().getMethod("getIdentifier"); + return (String) getIdentifier.invoke(license); + } catch (NoSuchMethodException e) { + // The model has no identifier accessor: try the swagger model behind an empoa wrapper, if any + } catch (ReflectiveOperationException e) { + return null; + } + + try { + Method getSw = license.getClass().getMethod("getSw"); + Object swaggerLicense = getSw.invoke(license); + Method getIdentifier = swaggerLicense.getClass().getMethod("getIdentifier"); + return (String) getIdentifier.invoke(swaggerLicense); + } catch (ReflectiveOperationException e) { + return null; + } + } + private void validateInfo() { Info info = openAPI.getInfo(); License license = info.getLicense(); @@ -56,6 +93,20 @@ private void validateInfo() { infoPresence.add(license.getUrl() != null && !license.getUrl().isEmpty()); errorAggregator.validateMinimumInfo( infoPresence, StyleError.StyleCheckSection.APIInfo, "license", "name|url"); + + /* + * See https://github.com/OpenAPITools/openapi-style-validator/issues/92 + * + * In an OpenAPI 3.1.0 document the `identifier` field of the + * license object is mutually exclusive of the `url` field. + */ + String identifier = getLicenseIdentifier(license); + if (license.getUrl() != null + && !license.getUrl().isEmpty() + && identifier != null + && !identifier.isEmpty()) { + errorAggregator.logLicenseUrlAndIdentifierBothSet(); + } } else { errorAggregator.logMissingOrEmptyAttribute(StyleError.StyleCheckSection.APIInfo, "license"); } diff --git a/lib/src/test/java/org/openapitools/openapistylevalidator/ErrorAggregatorTest.java b/lib/src/test/java/org/openapitools/openapistylevalidator/ErrorAggregatorTest.java index 4905dcd5..71acff4e 100644 --- a/lib/src/test/java/org/openapitools/openapistylevalidator/ErrorAggregatorTest.java +++ b/lib/src/test/java/org/openapitools/openapistylevalidator/ErrorAggregatorTest.java @@ -45,4 +45,15 @@ void logMissingModelProperty() { nameOfMissingProperty); assertEquals(Collections.singletonList(expectedError), errorAggregator.getErrorList()); } + + @Test + void logLicenseUrlAndIdentifierBothSetShouldAddToErrorList() { + errorAggregator.logLicenseUrlAndIdentifierBothSet(); + + Assertions.assertAll( + () -> assertEquals(1, errorAggregator.getErrorList().size()), + () -> assertEquals( + "*ERROR* Section: APIInfo: 'url|identifier' in license -> The license url and identifier are mutually exclusive, only one of them should be set", + errorAggregator.getErrorList().get(0).toString())); + } } diff --git a/lib/src/test/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidatorTest.java b/lib/src/test/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidatorTest.java index 31d088b7..c54f19df 100644 --- a/lib/src/test/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidatorTest.java +++ b/lib/src/test/java/org/openapitools/openapistylevalidator/OpenApiSpecStyleValidatorTest.java @@ -6,6 +6,7 @@ import java.util.stream.Collectors; import org.eclipse.microprofile.openapi.OASFactory; import org.eclipse.microprofile.openapi.models.OpenAPI; +import org.eclipse.microprofile.openapi.models.info.License; import org.eclipse.microprofile.openapi.models.media.Schema; import org.eclipse.microprofile.openapi.models.media.Schema.SchemaType; import org.eclipse.microprofile.openapi.models.parameters.Parameter.In; @@ -13,6 +14,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.openapitools.empoa.simple.internal.models.info.LicenseImpl; import org.openapitools.openapistylevalidator.ValidatorParameters.NamingConvention; import org.openapitools.openapistylevalidator.styleerror.StyleError; @@ -221,6 +223,125 @@ void testSuccessOfAllValidations() { assertEquals(0, errors.size(), errors.toString()); } + /* + * See https://github.com/OpenAPITools/openapi-style-validator/issues/92 + * + * Plain @Test methods are used on purpose: junit-jupiter-params is + * declared testCompileOnly in the root build.gradle, so @ParameterizedTest + * methods compile but are silently skipped at runtime. + */ + @Test + void testLicenseUrlOnlyIsValid() { + OpenAPI openAPI = createValidOpenAPI(); + openAPI.getInfo() + .license(OASFactory.createLicense() + .name("Eclipse Public License 2.0") + .url("https://www.eclipse.org/legal/epl-2.0/")); + + ValidatorParameters parameters = + TestDataProvider.createParametersDisablingAllValidations().setValidateInfoLicense(true); + + List errors = new OpenApiSpecStyleValidator(openAPI).validate(parameters); + assertEquals(0, errors.size()); + } + + /* + * The simple model has no identifier accessor, so this fake provides one + * the way an OAS 3.1-aware model (e.g. MicroProfile OpenAPI 4.0) does. + */ + private static License licenseWithIdentifier(String url, String identifier) { + return new LicenseImpl() { + @SuppressWarnings("unused") + public String getIdentifier() { + return identifier; + } + }.name("Eclipse Public License 2.0").url(url); + } + + /* + * Mimics the license wrapper produced by empoa-swagger-core (SwLicense), + * which delegates name and url but keeps the underlying swagger model - + * carrying `identifier` - accessible only through its `getSw()` accessor. + */ + private static License licenseThroughSwaggerModel(String url, String identifier) { + io.swagger.v3.oas.models.info.License swaggerLicense = new io.swagger.v3.oas.models.info.License() + .name("Eclipse Public License 2.0") + .url(url) + .identifier(identifier); + return new LicenseImpl() { + @SuppressWarnings("unused") + public io.swagger.v3.oas.models.info.License getSw() { + return swaggerLicense; + } + }.name("Eclipse Public License 2.0").url(url); + } + + @Test + void testLicenseIdentifierOnlyIsValid() { + OpenAPI openAPI = createValidOpenAPI(); + openAPI.getInfo().license(licenseWithIdentifier(null, "EPL-2.0")); + + ValidatorParameters parameters = + TestDataProvider.createParametersDisablingAllValidations().setValidateInfoLicense(true); + + List errors = new OpenApiSpecStyleValidator(openAPI).validate(parameters); + assertEquals(0, errors.size()); + } + + @Test + void testLicenseUrlAndIdentifierAreMutuallyExclusive() { + OpenAPI openAPI = createValidOpenAPI(); + openAPI.getInfo().license(licenseWithIdentifier("https://www.eclipse.org/legal/epl-2.0/", "EPL-2.0")); + + ValidatorParameters parameters = + TestDataProvider.createParametersDisablingAllValidations().setValidateInfoLicense(true); + + List errors = new OpenApiSpecStyleValidator(openAPI).validate(parameters); + Assertions.assertAll( + () -> assertEquals(1, errors.size()), + () -> assertEquals( + "*ERROR* Section: APIInfo: 'url|identifier' in license -> The license url and identifier are mutually exclusive, only one of them should be set", + errors.get(0).toString())); + } + + /* + * The CLI, Gradle and Maven plugins convert the parsed specification to + * MicroProfile models through empoa-swagger-core: the license is a wrapper + * around the swagger model, which carries `identifier` even though the + * wrapper does not expose it. + */ + @Test + void testLicenseUrlAndIdentifierAreMutuallyExclusiveThroughSwaggerModel() { + OpenAPI openAPI = createValidOpenAPI(); + openAPI.getInfo().license(licenseThroughSwaggerModel("https://www.eclipse.org/legal/epl-2.0/", "EPL-2.0")); + + ValidatorParameters parameters = + TestDataProvider.createParametersDisablingAllValidations().setValidateInfoLicense(true); + + List errors = new OpenApiSpecStyleValidator(openAPI).validate(parameters); + Assertions.assertAll( + () -> assertEquals(1, errors.size()), + () -> assertEquals( + "*ERROR* Section: APIInfo: 'url|identifier' in license -> The license url and identifier are mutually exclusive, only one of them should be set", + errors.get(0).toString())); + } + + /* + * A license carrying only an identifier behind the swagger model is valid: + * the two fields must not be flagged when they are not both set. + */ + @Test + void testLicenseIdentifierOnlyIsValidThroughSwaggerModel() { + OpenAPI openAPI = createValidOpenAPI(); + openAPI.getInfo().license(licenseThroughSwaggerModel(null, "EPL-2.0")); + + ValidatorParameters parameters = + TestDataProvider.createParametersDisablingAllValidations().setValidateInfoLicense(true); + + List errors = new OpenApiSpecStyleValidator(openAPI).validate(parameters); + assertEquals(0, errors.size()); + } + /** * See https://github.com/OpenAPITools/openapi-style-validator/issues/190 */