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

[k6] Add authentication variables in headers and cookies #19060

Merged
merged 6 commits into from
Jul 10, 2024

Conversation

willie5588912
Copy link
Contributor

It seems that the authentication statement is not handled in k6, so here I add a patch for parsing global authentication statement (only API Keys and Cookie Authentication). The parsed variables will be added to all the k6 test functions in either headers or cookies based on its statement.

Take petstore-with-fake-endpoints-models-for-testing.yaml as an example, which is used by k6:

openapi: 3.0.0
info:
  description: >-
    This spec is mainly for testing Petstore server and contains fake endpoints,
    models. Please do not use this for any other purpose. Special characters: "
    \
  version: 1.0.0
  title: OpenAPI Petstore
  license:
    name: Apache-2.0
    url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
  - name: pet
    description: Everything about your Pets
  - name: store
    description: Access to Petstore orders
  - name: user
    description: Operations about user

##### add security specification globally (header and cookie)
security:
  - global_api_key_header: []
  - global_api_key_cookie: []

paths:
  /foo:
    get:
      responses:
        default:
          description: response
          content:
            application/json:
              schema:
                type: object
                properties:
                  string:
                    $ref: '#/components/schemas/Foo'

##### define api_key in header/cookie here
components:  
  securitySchemes:    
    global_api_key_header:
      type: apiKey
      name: global_api_key_header
      in: header
    global_api_key_cookie:
      type: apiKey
      name: global_api_key_cookie
      in: cookie

With the authentication statement specified above, the generated code would be as follows:

let globalApiKeyCookie = "TODO_EDIT_THE_GLOBAL_API_KEY_COOKIE";
let globalApiKeyHeader = "TODO_EDIT_THE_GLOBAL_API_KEY_HEADER";

export default function() {
    group("/foo", () => {

        // Request No. 1: 
        {
            let url = BASE_URL + `/foo`;
            let params = {
                headers: {
                    "global_api_key_header": `${globalApiKeyHeader}`, "Accept": "application/json"
                }, cookies: {
                    "global_api_key_cookie": `${globalApiKeyCookie}`
                }
            };
            let request = http.get(url, params);

            check(request, {
                "response": (r) => r.status === 200
            });
        }
    });
}

If the global authentication is not specified, the headers works same as before, and the cookies gets disappeared (seems cookies not handled in k6 mustache originally, so without cookie authentication, the content is empty. Therefore, I made the cookies disappear if it is empty.)

While, I'm not sure if it is correct to add all the automatically generated samples into a commit, since there are lots of files.
Please help check this PR, thanks for your help!

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@wing328
Copy link
Member

wing328 commented Jul 6, 2024

thanks for the PR

cc @mostafa

global_api_key_cookie:
type: apiKey
name: global_api_key_cookie
in: cookie
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please copy this file to modules/openapi-generator/src/test/resources/3_0/k6/petstore-with-fake-endpoints-models-for-testing.yaml and revert the change in this file which is used by many other generators for testing?

please also update https://github.com/OpenAPITools/openapi-generator/blob/master/bin/configs/k6.yaml#L3 with the new path to the test spec used by k6

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I've modified this PR according to your comment, thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks. looks good

if there's no further feedback from @mostafa, i will merge it early next week

have a nice weekend

Comment on lines +671 to +678
if (globalAuthMethod.isKeyInHeader) {
httpParams.add(new Parameter(globalAuthMethod.keyParamName, getTemplateString(toVarName(globalAuthMethod.keyParamName))));
extraParameters.add(new Parameter(toVarName(globalAuthMethod.keyParamName), globalAuthMethod.keyParamName.toUpperCase(Locale.ROOT)));
}
if (globalAuthMethod.isKeyInCookie) {
cookieParams.add(new Parameter(globalAuthMethod.keyParamName, getTemplateString(toVarName(globalAuthMethod.keyParamName))));
extraParameters.add(new Parameter(toVarName(globalAuthMethod.keyParamName), globalAuthMethod.keyParamName.toUpperCase(Locale.ROOT)));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@willie5588912 Is it either/or? Or can it be both? 🤔

Copy link
Contributor Author

@willie5588912 willie5588912 Jul 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it can be in both. In some cases, we may need authentication token both in headers and cookies, and this depends on the requirement from the server side.
As the implementation here, it gives the flexibility for authentication token in headers and cookies since they are independent from each other and both ok if provided or not provided.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mostafa thanks for reviewing. I saw the thumb up so I'll merge it to get the ball rolling.

@wing328 wing328 merged commit 42b0b20 into OpenAPITools:master Jul 10, 2024
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants