Skip to content
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

[Core, Rust Server, ASP.NET Core] Fix Codegen Operation Scope Consistency #3495

Merged
merged 5 commits into from
Nov 8, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -17,6 +17,7 @@

package org.openapitools.codegen;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
Expand All @@ -38,7 +39,7 @@ public class CodegenSecurity {
// Oauth specific
public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes;
public Boolean isCode, isPassword, isApplication, isImplicit, hasScopes;
public Boolean isCode, isPassword, isApplication, isImplicit;

@Override
public String toString() {
Expand Down Expand Up @@ -100,4 +101,47 @@ public int hashCode() {
isImplicit,
scopes);
}

// Return a copy of the security object, filtering out any scopes from the passed-in list.
public CodegenSecurity filterByScopeNames(List<String> filterScopes) {
CodegenSecurity filteredSecurity = new CodegenSecurity();
// Copy all fields except the scopes.
filteredSecurity.name = name;
filteredSecurity.type = type;
filteredSecurity.hasMore = false;
filteredSecurity.isBasic = isBasic;
filteredSecurity.isBasicBasic = isBasicBasic;
filteredSecurity.isBasicBearer = isBasicBearer;
filteredSecurity.isApiKey = isApiKey;
filteredSecurity.isOAuth = isOAuth;
filteredSecurity.keyParamName = keyParamName;
filteredSecurity.isCode = isCode;
filteredSecurity.isImplicit = isImplicit;
filteredSecurity.isApplication = isApplication;
filteredSecurity.isPassword = isPassword;
filteredSecurity.isKeyInCookie = isKeyInCookie;
filteredSecurity.isKeyInHeader = isKeyInHeader;
filteredSecurity.isKeyInQuery = isKeyInQuery;
filteredSecurity.flow = flow;
filteredSecurity.tokenUrl = tokenUrl;
filteredSecurity.authorizationUrl = authorizationUrl;
// It is not possible to deep copy the extensions, as we have no idea what types they are.
// So the filtered method *will* refer to the original extensions, if any.
filteredSecurity.vendorExtensions = new HashMap<String, Object>(vendorExtensions);
List<Map<String, Object>> returnedScopes = new ArrayList<Map<String, Object>>();
Map<String, Object> lastScope = null;
for (String filterScopeName : filterScopes) {
for (Map<String, Object> scope : scopes) {
String name = (String) scope.get("scope");
if (filterScopeName.equals(name)) {
returnedScopes.add(scope);
lastScope = scope;
break;
}
}
}
filteredSecurity.scopes = returnedScopes;

return filteredSecurity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1057,50 +1057,11 @@ private void processOperation(String resourcePath, String httpMethod, Operation
}

if (authMethods != null && !authMethods.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(authMethods);
List<Map<String, Object>> scopes = new ArrayList<Map<String, Object>>();
if (codegenOperation.authMethods != null){
for (CodegenSecurity security : codegenOperation.authMethods){
if (security != null && security.isBasicBearer != null && security.isBasicBearer &&
securities != null){
for (SecurityRequirement req : securities){
if (req == null) continue;
for (String key : req.keySet()){
if (security.name != null && key.equals(security.name)){
int count = 0;
for (String sc : req.get(key)){
Map<String, Object> scope = new HashMap<String, Object>();
scope.put("scope", sc);
scope.put("description", "");
count++;
if (req.get(key) != null && count < req.get(key).size()){
scope.put("hasMore", "true");
} else {
scope.put("hasMore", null);
}
scopes.add(scope);
}
//end this inner for
break;
}
}

}
security.hasScopes = scopes.size() > 0;
security.scopes = scopes;
}
}
}
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities);
codegenOperation.hasAuthMethods = true;
}

/* TODO need to revise the logic below
Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents().getSecuritySchemes();
if (securitySchemeMap != null && !securitySchemeMap.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(securitySchemeMap);
codegenOperation.hasAuthMethods = true;
}
*/
} catch (Exception ex) {
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
Expand Down Expand Up @@ -1306,6 +1267,40 @@ private static OAuthFlow cloneOAuthFlow(OAuthFlow originFlow, List<String> opera
.scopes(newScopes);
}

private List<CodegenSecurity> filterAuthMethods(List<CodegenSecurity> authMethods, List<SecurityRequirement> securities) {
if (securities == null || securities.isEmpty()) {
return authMethods;
}

List<CodegenSecurity> result = new ArrayList<CodegenSecurity>();

for (CodegenSecurity security : authMethods){
boolean filtered = false;
if (security != null && security.scopes != null) {
for (SecurityRequirement requirement : securities) {
List<String> opScopes = requirement.get(security.name);
if (opScopes != null) {
// We have operation-level scopes for this method, so filter the auth method to
// describe the operation auth method with only the scopes that it requires.
// We have to create a new auth method instance because the original object must
// not be modified.
CodegenSecurity opSecurity = security.filterByScopeNames(opScopes);
result.add(opSecurity);
filtered = true;
break;
}
}
}

// If we didn't get a filtered version, then we can keep the original auth method.
if (!filtered) {
result.add(security);
}
}

return result;
}

private boolean hasOAuthMethods(List<CodegenSecurity> authMethods) {
for (CodegenSecurity cs : authMethods) {
if (Boolean.TRUE.equals(cs.isOAuth)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,15 @@ namespace {{apiPackage}}
/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}{{#responses}}
/// <response code="{{code}}">{{message}}</response>{{/responses}}
[{{httpMethod}}]
[Route("{{{basePathWithoutHost}}}{{{path}}}")]{{#hasAuthMethods}}{{#authMethods}}{{#isApiKey}}
[Authorize(Policy = "{{name}}")]{{/isApiKey}}{{#isBasicBearer}}
[Authorize{{#hasScopes}}(Roles = "{{#scopes}}{{scope}}{{#hasMore}},{{/hasMore}}{{/scopes}}"){{/hasScopes}}]{{/isBasicBearer}}{{/authMethods}}{{/hasAuthMethods}}
[Route("{{{basePathWithoutHost}}}{{{path}}}")]
{{#authMethods}}
{{#isApiKey}}
[Authorize(Policy = "{{name}}")]
{{/isApiKey}}
{{#isBasicBearer}}
[Authorize{{#scopes}}{{#-first}}(Roles = "{{/-first}}{{scope}}{{^-last}},{{/-last}}{{#-last}}"){{/-last}}{{/scopes}}]
{{/isBasicBearer}}
{{/authMethods}}
[ValidateModelState]{{#useSwashbuckle}}
[SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}{{^useSwashbuckle}}{{#responses}}{{#dataType}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,32 @@ paths:
responses:
'200':
description: 'OK'
/readonly_auth_scheme:
get:
security:
- authScheme: ["test.read"]
responses:
200:
description: Check that limiting to a single required auth scheme works
/multiple_auth_scheme:
get:
security:
- authScheme: ["test.read", "test.write"]
responses:
200:
description: Check that limiting to multiple required auth schemes works

components:
securitySchemes:
authScheme:
type: oauth2
flows:
authorizationCode:
authorizationUrl: 'http://example.org'
tokenUrl: 'http://example.org'
scopes:
test.read: Allowed to read state.
test.write: Allowed to change state.
schemas:
UuidObject:
description: Test a model containing a UUID
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.0.1-SNAPSHOT
4.1.0-SNAPSHOT
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using Org.OpenAPITools.Attributes;
using Org.OpenAPITools.Models;
using Microsoft.AspNetCore.Authorization;
using Org.OpenAPITools.Models;

namespace Org.OpenAPITools.Controllers
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using Org.OpenAPITools.Attributes;
using Org.OpenAPITools.Models;
using Microsoft.AspNetCore.Authorization;
using Org.OpenAPITools.Models;

namespace Org.OpenAPITools.Controllers
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using Org.OpenAPITools.Attributes;
using Org.OpenAPITools.Models;
using Microsoft.AspNetCore.Authorization;
using Org.OpenAPITools.Models;

namespace Org.OpenAPITools.Controllers
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public enum StatusEnum
/// Gets or Sets Complete
/// </summary>
[DataMember(Name="complete", EmitDefaultValue=false)]
public bool? Complete { get; set; }
public bool? Complete { get; set; } = false;

/// <summary>
/// Returns the string presentation of the object
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@
"type" : "array",
"items" : {
"type" : "string",
"default" : "available",
"enum" : [ "available", "pending", "sold" ]
"enum" : [ "available", "pending", "sold" ],
"default" : "available"
}
}
} ],
Expand Down
20 changes: 19 additions & 1 deletion samples/server/petstore/rust-server/output/openapi-v3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ cargo run --example server
To run a client, follow one of the following simple steps:

```
cargo run --example client MultipleAuthSchemeGet
cargo run --example client ReadonlyAuthSchemeGet
cargo run --example client RequiredOctetStreamPut
cargo run --example client XmlExtraPost
cargo run --example client XmlOtherPost
Expand Down Expand Up @@ -114,6 +116,8 @@ All URIs are relative to *http://localhost*

Method | HTTP request | Description
------------- | ------------- | -------------
[****](docs/default_api.md#) | **GET** /multiple_auth_scheme |
[****](docs/default_api.md#) | **GET** /readonly_auth_scheme |
[****](docs/default_api.md#) | **PUT** /required_octet_stream |
[****](docs/default_api.md#) | **POST** /xml_extra |
[****](docs/default_api.md#) | **POST** /xml_other |
Expand All @@ -135,8 +139,22 @@ Method | HTTP request | Description


## Documentation For Authorization
Endpoints do not require authorization.

## authScheme
- **Type**: OAuth
- **Flow**: accessCode
- **Authorization URL**: http://example.org
- **Scopes**:
- **test.read**: Allowed to read state.
- **test.write**: Allowed to change state.

Example
```
```

Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```
```

## Author

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,23 @@ paths:
responses:
200:
description: OK
/readonly_auth_scheme:
get:
responses:
200:
description: Check that limiting to a single required auth scheme works
security:
- authScheme:
- test.read
/multiple_auth_scheme:
get:
responses:
200:
description: Check that limiting to multiple required auth schemes works
security:
- authScheme:
- test.read
- test.write
components:
schemas:
UuidObject:
Expand Down Expand Up @@ -139,4 +156,14 @@ components:
xml:
name: snake_another_xml_object
namespace: http://foo.bar
securitySchemes:
authScheme:
flows:
authorizationCode:
authorizationUrl: http://example.org
scopes:
test.read: Allowed to read state.
test.write: Allowed to change state.
tokenUrl: http://example.org
type: oauth2

Loading