|
| 1 | +/* |
| 2 | + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) |
| 3 | + * Copyright 2018 SmartBear Software |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.openapitools.codegen.languages; |
| 19 | + |
| 20 | +import io.swagger.v3.oas.models.OpenAPI; |
| 21 | +import io.swagger.v3.oas.models.Operation; |
| 22 | +import io.swagger.v3.oas.models.security.SecurityRequirement; |
| 23 | +import io.swagger.v3.oas.models.security.SecurityScheme; |
| 24 | +import java.util.Collections; |
| 25 | +import java.util.List; |
| 26 | +import java.util.Map; |
| 27 | +import org.openapitools.codegen.CodegenOperation; |
| 28 | +import org.slf4j.Logger; |
| 29 | +import org.slf4j.LoggerFactory; |
| 30 | + |
| 31 | +/** |
| 32 | + * Translates an OpenAPI operation's security requirements into Jakarta security |
| 33 | + * vendor extensions on a {@link CodegenOperation} for downstream Mustache templates. |
| 34 | + * |
| 35 | + * <p>The OpenAPI {@code security} array uses OR semantics (any one alternative |
| 36 | + * satisfies the request); the Jakarta annotations are AND-stacked. The two cannot |
| 37 | + * always be reconciled, so this class emits the least restrictive annotation that |
| 38 | + * is still correct for the OR group. |
| 39 | + * |
| 40 | + * <p>A single vendor extension {@code x-jakarta-roles-allowed} carries the value to |
| 41 | + * emit. For the any-authenticated-user case it is set to the singleton list |
| 42 | + * {@code ["**"]}, producing {@code @RolesAllowed({"**"})}. Future PRs will reuse |
| 43 | + * the same extension to emit scoped roles (e.g. {@code ["admin"]}) without needing |
| 44 | + * a second flag or template branch. |
| 45 | + */ |
| 46 | +final class JakartaSecurityAnnotationProcessor { |
| 47 | + |
| 48 | + static final String VENDOR_X_JAKARTA_ROLES_ALLOWED = "x-jakarta-roles-allowed"; |
| 49 | + |
| 50 | + private static final List<String> ANY_AUTHENTICATED_ROLE = Collections.singletonList("**"); |
| 51 | + |
| 52 | + private final Logger LOGGER = LoggerFactory.getLogger(JakartaSecurityAnnotationProcessor.class); |
| 53 | + |
| 54 | + /** |
| 55 | + * Inspects {@code rawOp}'s security requirements (falling back to the global |
| 56 | + * {@code openAPI.security} when the operation does not override) and sets |
| 57 | + * {@code x-jakarta-roles-allowed} on {@code op} when the operation qualifies |
| 58 | + * for {@code @RolesAllowed} emission. |
| 59 | + */ |
| 60 | + void applyTo(CodegenOperation op, Operation rawOp, OpenAPI openAPI) { |
| 61 | + // Use the raw Operation here rather than op.authMethods: by the time postProcessOperationsWithModels |
| 62 | + // runs, DefaultGenerator.filterAuthMethods has flattened all SecurityRequirements into a plain list, |
| 63 | + // losing the AND-group structure needed to evaluate mixed-scope combinations correctly. |
| 64 | + List<SecurityRequirement> requirements = rawOp.getSecurity(); |
| 65 | + if (requirements == null) { |
| 66 | + // Fall back to the global security block when the operation does not override it. |
| 67 | + requirements = openAPI.getSecurity(); |
| 68 | + } |
| 69 | + Map<String, SecurityScheme> schemes = resolveSchemes(openAPI); |
| 70 | + |
| 71 | + if (qualifiesForAnyRoles(requirements, schemes)) { |
| 72 | + op.vendorExtensions.put(VENDOR_X_JAKARTA_ROLES_ALLOWED, ANY_AUTHENTICATED_ROLE); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Returns true when at least one OR alternative fully qualifies for |
| 78 | + * {@code @RolesAllowed({"**"})} and no alternative is anonymous ({@code - {}}). |
| 79 | + * |
| 80 | + * <p>An empty {@link SecurityRequirement} ({@code - {}}) inside the OR list means |
| 81 | + * the operation may also be called unauthenticated. When that is present, the |
| 82 | + * least-restrictive alternative is "no auth required", so emitting |
| 83 | + * {@code @RolesAllowed({"**"})} would force authentication and contradict the |
| 84 | + * spec -- we return false instead and let the future {@code @PermitAll} branch |
| 85 | + * handle that case. |
| 86 | + */ |
| 87 | + private boolean qualifiesForAnyRoles(List<SecurityRequirement> requirements, |
| 88 | + Map<String, SecurityScheme> schemes) { |
| 89 | + if (requirements == null || requirements.isEmpty()) { |
| 90 | + return false; |
| 91 | + } |
| 92 | + boolean anyQualifies = false; |
| 93 | + for (SecurityRequirement requirement : requirements) { |
| 94 | + if (requirement.isEmpty()) { |
| 95 | + // Anonymous OR alternative -- least restrictive wins; do not emit @RolesAllowed. |
| 96 | + return false; |
| 97 | + } |
| 98 | + if (andGroupQualifies(requirement, schemes)) { |
| 99 | + anyQualifies = true; |
| 100 | + } |
| 101 | + } |
| 102 | + return anyQualifies; |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * A single {@link SecurityRequirement} is an AND group: all schemes must be |
| 107 | + * satisfied simultaneously. If any scheme in the group has explicit scopes |
| 108 | + * (e.g. {@code oauth2: [admin:write]}), the combined requirement is more |
| 109 | + * restrictive than "any authenticated user" and does not qualify. |
| 110 | + */ |
| 111 | + private boolean andGroupQualifies(SecurityRequirement requirement, Map<String, SecurityScheme> schemes) { |
| 112 | + for (Map.Entry<String, List<String>> entry : requirement.entrySet()) { |
| 113 | + SecurityScheme scheme = schemes.get(entry.getKey()); |
| 114 | + if (scheme == null) { |
| 115 | + LOGGER.warn("Security requirement references undefined scheme '{}' -- skipping Jakarta security annotation for this AND group.", |
| 116 | + entry.getKey()); |
| 117 | + return false; |
| 118 | + } |
| 119 | + if (!schemeQualifies(scheme, entry.getValue())) { |
| 120 | + return false; |
| 121 | + } |
| 122 | + } |
| 123 | + return true; |
| 124 | + } |
| 125 | + |
| 126 | + private boolean schemeQualifies(SecurityScheme scheme, List<String> scopes) { |
| 127 | + if (scheme.getType() == null) { |
| 128 | + LOGGER.warn("Security scheme is missing 'type' -- skipping Jakarta security annotation."); |
| 129 | + return false; |
| 130 | + } |
| 131 | + switch (scheme.getType()) { |
| 132 | + case OAUTH2: |
| 133 | + case OPENIDCONNECT: |
| 134 | + // Empty scope list means the operation requires authentication but no specific role, |
| 135 | + // so @RolesAllowed({"**"}) is correct. Non-empty scopes belong to a future @RolesAllowed({scope}) PR. |
| 136 | + return scopes == null || scopes.isEmpty(); |
| 137 | + case HTTP: |
| 138 | + case APIKEY: |
| 139 | + case MUTUALTLS: |
| 140 | + // These schemes have no scope concept; any valid credential satisfies them. |
| 141 | + return true; |
| 142 | + default: |
| 143 | + LOGGER.warn("Unrecognised security scheme type '{}' -- skipping Jakarta security annotation.", |
| 144 | + scheme.getType()); |
| 145 | + return false; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + private static Map<String, SecurityScheme> resolveSchemes(OpenAPI openAPI) { |
| 150 | + if (openAPI.getComponents() != null && openAPI.getComponents().getSecuritySchemes() != null) { |
| 151 | + return openAPI.getComponents().getSecuritySchemes(); |
| 152 | + } |
| 153 | + return Collections.emptyMap(); |
| 154 | + } |
| 155 | +} |
0 commit comments