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

refactor(cmd-api-server): pull OAuth2 endpoint scopes from openapi.json #3463

Open
wants to merge 1 commit into
base: main
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 @@ -91,7 +91,18 @@ Class | Method | HTTP request | Description

## Documentation For Authorization

Endpoints do not require authorization.

Authentication schemes defined for the API:
### bearerTokenAuth

- **Type**: HTTP Bearer token authentication

Example

```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARER_TOKEN_STRING")
r, err := client.Service.Operation(auth, args)
```


## Documentation for Utility Methods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ info:
version: 2.0.0-rc.7
servers:
- url: /
security:
- bearerTokenAuth:
- read:health
- read:metrics
- read:spec
paths:
/api/v1/api-server/healthcheck:
get:
Expand All @@ -21,6 +26,11 @@ paths:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
description: OK
"401":
description: Unauthorized
security:
- bearerTokenAuth:
- read:health
summary: Can be used to verify liveness of an API server instance
x-hyperledger-cacti:
http:
Expand All @@ -37,6 +47,11 @@ paths:
schema:
$ref: '#/components/schemas/PrometheusExporterMetricsResponse'
description: OK
"401":
description: Unauthorized
security:
- OAuth2:
- read:metrics
summary: Get the Prometheus Metrics
x-hyperledger-cacti:
http:
Expand All @@ -54,6 +69,11 @@ paths:
schema:
$ref: '#/components/schemas/GetOpenApiSpecV1EndpointResponse'
description: OK
"401":
description: Unauthorized
security:
- bearerTokenAuth:
- read:spec
x-hyperledger-cacti:
http:
verbLowerCase: get
Expand Down Expand Up @@ -127,3 +147,8 @@ components:
GetOpenApiSpecV1EndpointResponse:
nullable: false
type: string
securitySchemes:
bearerTokenAuth:
bearerFormat: JSON Web Tokens
scheme: bearer
type: http

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 39 additions & 3 deletions packages/cactus-cmd-api-server/src/main/json/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,20 @@
"type": "string",
"nullable": false
}
},
"securitySchemes": {
"bearerTokenAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JSON Web Tokens"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:health", "read:metrics", "read:spec"]
}
],
"paths": {
"/api/v1/api-server/healthcheck": {
"get": {
Expand All @@ -101,8 +113,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:health"]
}
]
}
},
"/api/v1/api-server/get-prometheus-exporter-metrics": {
Expand All @@ -126,8 +146,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"OAuth2": ["read:metrics"]
}
]
}
},
"/api/v1/api-server/get-open-api-spec": {
Expand All @@ -151,8 +179,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:spec"]
}
]
}
}
}
Expand Down
42 changes: 39 additions & 3 deletions packages/cactus-cmd-api-server/src/main/json/openapi.tpl.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,20 @@
"type": "string",
"nullable": false
}
},
"securitySchemes": {
"bearerTokenAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JSON Web Tokens"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:health", "read:metrics", "read:spec"]
}
],
"paths": {
"/api/v1/api-server/healthcheck": {
"get": {
Expand All @@ -101,8 +113,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:health"]
}
]
}
},
"/api/v1/api-server/get-prometheus-exporter-metrics": {
Expand All @@ -126,8 +146,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:metrics"]
}
]
}
},
"/api/v1/api-server/get-open-api-spec": {
Expand All @@ -151,8 +179,16 @@
}
}
}
},
"401": {
"description": "Unauthorized"
}
}
},
"security": [
{
"bearerTokenAuth": ["read:spec"]
}
]
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,10 @@ Class | Method | HTTP request | Description
<a id="documentation-for-authorization"></a>
## Documentation for Authorization

Endpoints do not require authorization.

Authentication schemes defined for the API:
<a id="bearerTokenAuth"></a>
### bearerTokenAuth

- **Type**: HTTP basic authentication

Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient
path = "/api/v1/api-server/healthcheck",
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = false,
requiresAuthentication = true,
body = localVariableBody
)
}
Expand Down Expand Up @@ -176,7 +176,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient
path = "/api/v1/api-server/get-open-api-spec",
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = false,
requiresAuthentication = true,
body = localVariableBody
)
}
Expand Down Expand Up @@ -243,7 +243,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient
path = "/api/v1/api-server/get-prometheus-exporter-metrics",
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = false,
requiresAuthentication = true,
body = localVariableBody
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,20 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie
}
}

protected fun <T> updateAuthParams(requestConfig: RequestConfig<T>) {
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
accessToken?.let { accessToken ->
requestConfig.headers[Authorization] = "Bearer $accessToken"
}
}
}

protected inline fun <reified I, reified T: Any?> request(requestConfig: RequestConfig<I>): ApiResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")

// take authMethod from operation
updateAuthParams(requestConfig)

val url = httpUrl.newBuilder()
.addEncodedPathSegments(requestConfig.path.trimStart('/'))
.apply {
Expand Down
30 changes: 13 additions & 17 deletions packages/cactus-cmd-api-server/src/main/typescript/api-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ import {
GetOpenApiSpecV1Endpoint,
IGetOpenApiSpecV1EndpointOptions,
} from "./web-services/get-open-api-spec-v1-endpoint";
import {
GetHealthcheckV1Endpoint,
IGetHealthcheckV1EndpointOptions,
} from "./web-services/get-healthcheck-v1-endpoint";

export interface IApiServerConstructorOptions {
readonly pluginManagerOptions?: { pluginsPath: string };
Expand Down Expand Up @@ -640,6 +644,15 @@ export class ApiServer {
const { logLevel } = this.options.config;
const pluginRegistry = await this.getOrInitPluginRegistry();

{
const opts: IGetHealthcheckV1EndpointOptions = {
process: global.process,
logLevel,
};
const endpoint = new GetHealthcheckV1Endpoint(opts);
await registerWebServiceEndpoint(app, endpoint);
}

{
const oasPath = OAS.paths["/api/v1/api-server/get-open-api-spec"];

Expand All @@ -657,23 +670,6 @@ export class ApiServer {
await registerWebServiceEndpoint(app, endpoint);
}

const healthcheckHandler = (req: Request, res: Response) => {
res.json({
success: true,
createdAt: new Date(),
memoryUsage: process.memoryUsage(),
});
};

const { "/api/v1/api-server/healthcheck": oasPath } = OAS.paths;
const { http } = oasPath.get["x-hyperledger-cacti"];
const { path: httpPath, verbLowerCase: httpVerb } = http;
if (!isExpressHttpVerbMethodName(httpVerb)) {
const eMsg = `${fnTag} Invalid HTTP verb "${httpVerb}" in cmd-api-server OpenAPI specification for HTTP path: "${httpPath}"`;
throw new RuntimeError(eMsg);
}
app[httpVerb](httpPath, healthcheckHandler);

this.wsApi.on("connection", (socket: SocketIoSocket) => {
const { id } = socket;
const transport = socket.conn.transport.name; // in most cases, "polling"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



setSearchParams(localVarUrlObj, localVarQueryParameter);
Expand Down Expand Up @@ -157,6 +161,10 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



setSearchParams(localVarUrlObj, localVarQueryParameter);
Expand Down Expand Up @@ -187,6 +195,10 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



setSearchParams(localVarUrlObj, localVarQueryParameter);
Expand Down
Loading
Loading