Skip to content

Commit

Permalink
refactor(cmd-api-server): pull OAuth2 endpoint scopes from openapi.json
Browse files Browse the repository at this point in the history
Primary Changes
----------------
1. added OAuth2 security endpoints scopes to openapi.json
2. added a test to make sure if the scopes are indeed getting
   pulled from the spec file

Fixes #2693

Signed-off-by: aldousalvarez <[email protected]>

1. Please also refactor the third endpoint (prometheus metrics) accordingly
2. Also please extend the test case with each tokens having specific scopes
and then assert that the tokesn with the correct scopes work and the ones
that don't have the correct scopes do not even when they are otherwise
valid tokens.

Signed-off-by: Peter Somogyvari <[email protected]>
  • Loading branch information
aldousalvarez committed Oct 4, 2024
1 parent 164addf commit af634c3
Show file tree
Hide file tree
Showing 14 changed files with 511 additions and 30 deletions.
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": [
{
"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
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

0 comments on commit af634c3

Please sign in to comment.