Skip to content

Commit

Permalink
squash! - pull the token scope from the openapi json file
Browse files Browse the repository at this point in the history
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 <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed Oct 4, 2024
1 parent 90f2850 commit 20d64d4
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 122 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ Install the following dependencies:

```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
go get golang.org/x/net/context
```

Expand Down Expand Up @@ -94,33 +93,14 @@ Class | Method | HTTP request | Description


Authentication schemes defined for the API:
### OAuth2
### bearerTokenAuth


- **Type**: OAuth
- **Flow**: accessCode
- **Authorization URL**: http://0.0.0.0:4000/oauth/authorize
- **Scopes**:
- **read:health**: Read health information
- **read:metrics**: Read metrics information
- **read:spec**: Read OpenAPI specification
- **Type**: HTTP Bearer token authentication

Example

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

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

```golang
import "golang.org/x/oauth2"

/* Perform OAuth2 round trip request and obtain a token */

tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARER_TOKEN_STRING")
r, err := client.Service.Operation(auth, args)
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ info:
servers:
- url: /
security:
- OAuth2:
- bearerTokenAuth:
- read:health
- read:metrics
- read:spec
Expand All @@ -29,7 +29,7 @@ paths:
"401":
description: Unauthorized
security:
- OAuth2:
- bearerTokenAuth:
- read:health
summary: Can be used to verify liveness of an API server instance
x-hyperledger-cacti:
Expand Down Expand Up @@ -72,7 +72,7 @@ paths:
"401":
description: Unauthorized
security:
- OAuth2:
- bearerTokenAuth:
- read:spec
x-hyperledger-cacti:
http:
Expand Down Expand Up @@ -148,13 +148,7 @@ components:
nullable: false
type: string
securitySchemes:
OAuth2:
flows:
authorizationCode:
authorizationUrl: http://0.0.0.0:4000/oauth/authorize
scopes:
read:health: Read health information
read:metrics: Read metrics information
read:spec: Read OpenAPI specification
tokenUrl: http://0.0.0.0:4000/oauth/token
type: oauth2
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.

Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ module github.com/hyperledger/cactus-cmd-api-server/src/main/go/generated/openap
go 1.18

require (
golang.org/x/oauth2 v0.0.0-20210323180902-22b0adad7558
)
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
23 changes: 7 additions & 16 deletions packages/cactus-cmd-api-server/src/main/json/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,16 @@
}
},
"securitySchemes": {
"OAuth2": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"read:health": "Read health information",
"read:metrics": "Read metrics information",
"read:spec": "Read OpenAPI specification"
}
}
}
"bearerTokenAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JSON Web Tokens"
}
}
},
"security": [
{
"OAuth2": ["read:health", "read:metrics", "read:spec"]
"bearerTokenAuth": ["read:health", "read:metrics", "read:spec"]
}
],
"paths": {
Expand Down Expand Up @@ -129,7 +120,7 @@
},
"security": [
{
"OAuth2": ["read:health"]
"bearerTokenAuth": ["read:health"]
}
]
}
Expand Down Expand Up @@ -195,7 +186,7 @@
},
"security": [
{
"OAuth2": ["read:spec"]
"bearerTokenAuth": ["read:spec"]
}
]
}
Expand Down
23 changes: 7 additions & 16 deletions packages/cactus-cmd-api-server/src/main/json/openapi.tpl.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,16 @@
}
},
"securitySchemes": {
"OAuth2": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"read:health": "Read health information",
"read:metrics": "Read metrics information",
"read:spec": "Read OpenAPI specification"
}
}
}
"bearerTokenAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JSON Web Tokens"
}
}
},
"security": [
{
"OAuth2": ["read:health", "read:metrics", "read:spec"]
"bearerTokenAuth": ["read:health", "read:metrics", "read:spec"]
}
],
"paths": {
Expand Down Expand Up @@ -129,7 +120,7 @@
},
"security": [
{
"OAuth2": ["read:health"]
"bearerTokenAuth": ["read:health"]
}
]
}
Expand Down Expand Up @@ -195,7 +186,7 @@
},
"security": [
{
"OAuth2": ["read:spec"]
"bearerTokenAuth": ["read:spec"]
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,8 @@ Class | Method | HTTP request | Description


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

- **Type**: OAuth
- **Flow**: accessCode
- **Authorization URL**: http://0.0.0.0:4000/oauth/authorize
- **Scopes**:
- read:health: Read health information
- read:metrics: Read metrics information
- read:spec: Read OpenAPI specification
<a id="bearerTokenAuth"></a>
### bearerTokenAuth

- **Type**: HTTP basic authentication

Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ 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 "
requestConfig.headers[Authorization] = "Bearer $accessToken"
}
}
}
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,9 +128,9 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication OAuth2 required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2", ["read:health"], configuration)
// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



Expand Down Expand Up @@ -161,9 +161,9 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication OAuth2 required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2", ["read:spec"], configuration)
// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



Expand Down Expand Up @@ -195,9 +195,9 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

// authentication OAuth2 required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2", ["read:metrics"], configuration)
// authentication bearerTokenAuth required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)



Expand Down
Loading

0 comments on commit 20d64d4

Please sign in to comment.