Skip to content

[WIP] [Auth] Handle multiple security schemes #6840

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
import org.openapitools.codegen.meta.GeneratorMetadata;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public interface CodegenConfig {
GeneratorMetadata getGeneratorMetadata();
Expand Down Expand Up @@ -120,7 +122,7 @@ public interface CodegenConfig {

CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, List<Server> servers);

List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemas);
List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> schemas);

List<CodegenServer> fromServers(List<Server> servers);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4338,79 +4338,79 @@ public boolean isDataTypeFile(String dataType) {
* @return a list of Codegen Security objects
*/
@SuppressWarnings("static-method")
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> securitySchemeMap) {
public List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> securitySchemeMap) {
if (securitySchemeMap == null) {
return Collections.emptyList();
}

List<CodegenSecurity> codegenSecurities = new ArrayList<CodegenSecurity>(securitySchemeMap.size());
for (String key : securitySchemeMap.keySet()) {
final SecurityScheme securityScheme = securitySchemeMap.get(key);

CodegenSecurity cs = CodegenModelFactory.newInstance(CodegenModelType.SECURITY);
cs.name = key;
cs.type = securityScheme.getType().toString();
cs.isCode = cs.isPassword = cs.isApplication = cs.isImplicit = false;
cs.isHttpSignature = false;
cs.isBasicBasic = cs.isBasicBearer = false;
cs.scheme = securityScheme.getScheme();
if (securityScheme.getExtensions() != null) {
cs.vendorExtensions.putAll(securityScheme.getExtensions());
}

if (SecurityScheme.Type.APIKEY.equals(securityScheme.getType())) {
cs.isBasic = cs.isOAuth = false;
cs.isApiKey = true;
cs.keyParamName = securityScheme.getName();
cs.isKeyInHeader = securityScheme.getIn() == SecurityScheme.In.HEADER;
cs.isKeyInQuery = securityScheme.getIn() == SecurityScheme.In.QUERY;
cs.isKeyInCookie = securityScheme.getIn() == SecurityScheme.In.COOKIE; //it assumes a validation step prior to generation. (cookie-auth supported from OpenAPI 3.0.0)
} else if (SecurityScheme.Type.HTTP.equals(securityScheme.getType())) {
cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isOAuth = false;
cs.isBasic = true;
if ("basic".equals(securityScheme.getScheme())) {
cs.isBasicBasic = true;
} else if ("bearer".equals(securityScheme.getScheme())) {
cs.isBasicBearer = true;
cs.bearerFormat = securityScheme.getBearerFormat();
} else if ("signature".equals(securityScheme.getScheme())) {
// HTTP signature as defined in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/
// The registry of security schemes is maintained by IANA.
// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml
// As of January 2020, the "signature" scheme has not been registered with IANA yet.
// This scheme may have to be changed when it is officially registered with IANA.
cs.isHttpSignature = true;
once(LOGGER).warn("Security scheme 'HTTP signature' is a draft IETF RFC and subject to change.");
for(Entry<String, List<SecurityScheme>> e : securitySchemeMap.entrySet()){
for(final SecurityScheme securityScheme : e.getValue()){
final String key = e.getKey();
CodegenSecurity cs = CodegenModelFactory.newInstance(CodegenModelType.SECURITY);
cs.name = key;
cs.type = securityScheme.getType().toString();
cs.isCode = cs.isPassword = cs.isApplication = cs.isImplicit = false;
cs.isHttpSignature = false;
cs.isBasicBasic = cs.isBasicBearer = false;
cs.scheme = securityScheme.getScheme();
if (securityScheme.getExtensions() != null) {
cs.vendorExtensions.putAll(securityScheme.getExtensions());
}
} else if (SecurityScheme.Type.OAUTH2.equals(securityScheme.getType())) {
cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isBasic = false;
cs.isOAuth = true;
final OAuthFlows flows = securityScheme.getFlows();
if (securityScheme.getFlows() == null) {
throw new RuntimeException("missing oauth flow in " + cs.name);
}
if (flows.getPassword() != null) {
setOauth2Info(cs, flows.getPassword());
cs.isPassword = true;
cs.flow = "password";
} else if (flows.getImplicit() != null) {
setOauth2Info(cs, flows.getImplicit());
cs.isImplicit = true;
cs.flow = "implicit";
} else if (flows.getClientCredentials() != null) {
setOauth2Info(cs, flows.getClientCredentials());
cs.isApplication = true;
cs.flow = "application";
} else if (flows.getAuthorizationCode() != null) {
setOauth2Info(cs, flows.getAuthorizationCode());
cs.isCode = true;
cs.flow = "accessCode";
} else {
throw new RuntimeException("Could not identify any oauth2 flow in " + cs.name);

if (SecurityScheme.Type.APIKEY.equals(securityScheme.getType())) {
cs.isBasic = cs.isOAuth = false;
cs.isApiKey = true;
cs.keyParamName = securityScheme.getName();
cs.isKeyInHeader = securityScheme.getIn() == SecurityScheme.In.HEADER;
cs.isKeyInQuery = securityScheme.getIn() == SecurityScheme.In.QUERY;
cs.isKeyInCookie = securityScheme.getIn() == SecurityScheme.In.COOKIE; //it assumes a validation step prior to generation. (cookie-auth supported from OpenAPI 3.0.0)
} else if (SecurityScheme.Type.HTTP.equals(securityScheme.getType())) {
cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isOAuth = false;
cs.isBasic = true;
if ("basic".equals(securityScheme.getScheme())) {
cs.isBasicBasic = true;
} else if ("bearer".equals(securityScheme.getScheme())) {
cs.isBasicBearer = true;
cs.bearerFormat = securityScheme.getBearerFormat();
} else if ("signature".equals(securityScheme.getScheme())) {
// HTTP signature as defined in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/
// The registry of security schemes is maintained by IANA.
// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml
// As of January 2020, the "signature" scheme has not been registered with IANA yet.
// This scheme may have to be changed when it is officially registered with IANA.
cs.isHttpSignature = true;
once(LOGGER).warn("Security scheme 'HTTP signature' is a draft IETF RFC and subject to change.");
}
} else if (SecurityScheme.Type.OAUTH2.equals(securityScheme.getType())) {
cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isBasic = false;
cs.isOAuth = true;
final OAuthFlows flows = securityScheme.getFlows();
if (securityScheme.getFlows() == null) {
throw new RuntimeException("missing oauth flow in " + cs.name);
}
if (flows.getPassword() != null) {
setOauth2Info(cs, flows.getPassword());
cs.isPassword = true;
cs.flow = "password";
} else if (flows.getImplicit() != null) {
setOauth2Info(cs, flows.getImplicit());
cs.isImplicit = true;
cs.flow = "implicit";
} else if (flows.getClientCredentials() != null) {
setOauth2Info(cs, flows.getClientCredentials());
cs.isApplication = true;
cs.flow = "application";
} else if (flows.getAuthorizationCode() != null) {
setOauth2Info(cs, flows.getAuthorizationCode());
cs.isCode = true;
cs.flow = "accessCode";
} else {
throw new RuntimeException("Could not identify any oauth2 flow in " + cs.name);
}
}
codegenSecurities.add(cs);
}

codegenSecurities.add(cs);
}

// sort auth methods to maintain the same order
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.api.TemplateProcessor;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
Expand All @@ -58,6 +59,7 @@
import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.openapitools.codegen.utils.OnceLogger.once;

Expand Down Expand Up @@ -757,7 +759,7 @@ private Map<String, Object> buildSupportFileBundle(List<Object> allOperations, L
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());

Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
Map<String, List<SecurityScheme>> securitySchemeMap = openAPI.getComponents() != null ? AuthParser.toSecuritySchemeContainer(openAPI.getComponents().getSecuritySchemes()) : null;
List<CodegenSecurity> authMethods = config.fromSecurity(securitySchemeMap);
if (authMethods != null && !authMethods.isEmpty()) {
bundle.put("authMethods", authMethods);
Expand Down Expand Up @@ -1016,7 +1018,7 @@ private void processOperation(String resourcePath, String httpMethod, Operation
continue;
}

Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
Map<String, List<SecurityScheme>> authMethods = getAuthMethods(securities, securitySchemes);

if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
Expand Down Expand Up @@ -1161,11 +1163,11 @@ private Map<String, Object> processModels(CodegenConfig config, Map<String, Sche
return objs;
}

private Map<String, SecurityScheme> getAuthMethods(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
private Map<String, List<SecurityScheme>> getAuthMethods(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
if (securities == null || (securitySchemes == null || securitySchemes.isEmpty())) {
return null;
}
final Map<String, SecurityScheme> authMethods = new HashMap<>();
final Map<String, List<SecurityScheme>> authMethods = new HashMap<>();
for (SecurityRequirement requirement : securities) {
for (Map.Entry<String, List<String>> entry : requirement.entrySet()) {
final String key = entry.getKey();
Expand Down Expand Up @@ -1214,9 +1216,9 @@ private Map<String, SecurityScheme> getAuthMethods(List<SecurityRequirement> sec
oautUpdatedFlows.setClientCredentials(updatedFlow);
}

authMethods.put(key, oauthUpdatedScheme);
authMethods.computeIfAbsent(key, k -> new ArrayList<>()).add(securityScheme);
} else {
authMethods.put(key, securityScheme);
authMethods.computeIfAbsent(key, k -> new ArrayList<>()).add(securityScheme);
}
}
}
Expand Down Expand Up @@ -1259,7 +1261,6 @@ private List<CodegenSecurity> filterAuthMethods(List<CodegenSecurity> authMethod
opSecurity.hasMore = security.hasMore;
result.add(opSecurity);
filtered = true;
break;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@

package org.openapitools.codegen.auth;

import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.isNotEmpty;

Expand Down Expand Up @@ -72,4 +73,10 @@ public static String reconstruct(List<AuthorizationValue> authorizationValueList
return null;
}
}

public static Map<String, List<SecurityScheme>> toSecuritySchemeContainer(Map<String, SecurityScheme> m){
return Optional.ofNullable(m)
.orElse(new HashMap<>())
.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> Collections.singletonList(e.getValue())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
Expand All @@ -28,6 +29,7 @@
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

import static org.openapitools.codegen.utils.StringUtils.camelize;

Expand Down Expand Up @@ -83,8 +85,8 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));

// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
Map<String, List<SecurityScheme>> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? AuthParser.toSecuritySchemeContainer(openAPI.getComponents().getSecuritySchemes()) : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera
}

@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
public List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> schemes) {
List<CodegenSecurity> secs = super.fromSecurity(schemes);
for (CodegenSecurity sec : secs) {
String prefix = "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ public int compare(CodegenOperation one, CodegenOperation another) {
}

@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> securitySchemeMap) {
public List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> securitySchemeMap) {
List<CodegenSecurity> codegenSecurities = super.fromSecurity(securitySchemeMap);
if (Boolean.FALSE.equals(codegenSecurities.isEmpty())) {
supportingFiles.add(new SupportingFile("abstract_authenticator.mustache", toSrcPath(authPackage, srcBasePath), toAbstractName("Authenticator") + ".php"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.examples.ExampleGenerator;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
Expand All @@ -44,6 +45,7 @@
import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
Expand Down Expand Up @@ -148,8 +150,8 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("python-experimental/__init__apis.mustache", packagePath() + File.separatorChar + "apis", "__init__.py"));

// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
Map<String, List<SecurityScheme>> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? AuthParser.toSecuritySchemeContainer(openAPI.getComponents().getSecuritySchemes()) : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("python-experimental/signing.mustache", packagePath(), "signing.py"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
}

@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
public List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> schemes) {
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
if (!removeOAuthSecurities) {
return codegenSecurities;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
}

@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
public List<CodegenSecurity> fromSecurity(Map<String, List<SecurityScheme>> schemes) {
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
if (!removeOAuthSecurities) {
return codegenSecurities;
Expand Down
Loading