WasmEdge / wasmedge_hyper_demo

Lightweight HTTP servers based on hyper / warp frameworks in the WasmEdge Runtime.
81 stars 15 forks source link

https example #14

Closed L-jasmine closed 1 year ago

L-jasmine commented 1 year ago

Add https example

juntao commented 1 year ago

Hello, I am a code review bot on flows.network. Here are my reviews of changed source code files in this PR.


.github/workflows/examples.yml

Here is the review of the provided source code:

  1. The YAML structure appears to be correct, no syntax errors found.

  2. The "Install apt-get packages" step uses the sudo command, which may require user input for password. Since this code is intended to be used in an automated environment, it is recommended to remove the sudo prefix and run the commands using the runner's privileges.

  3. The "Install WasmEdge" step downloads and installs various dependencies and binaries. It is important to ensure that the URLs from where the files are being downloaded are reliable and trusted sources.

  4. Both the "Client https example" and "Server example" steps execute Rust code and build wasm binaries using Cargo. Make sure that the dependencies and build steps are correctly specified in the relevant projects (client-https, server, and other server variants).

  5. In the "Server example" step, a background process (wasmedge) is started and its process ID is stored in the wasmedge.pid file. After sending a POST request to the server, the process is killed using the process ID. However, the cleanup of the background process and the wasmedge.pid file should also be handled in case of any failures or early termination of the workflow.

  6. Similar to the "Server example" step, the "Warp example" and "TFLite Server example" steps start background processes and perform cleanup. Make sure that these processes are properly terminated and all necessary resources are cleaned up.

  7. The "Client example" step runs the wasm binary using wasmedge and performs a similar check as the other steps. Verify that the wasm binary is correctly built and executed as expected.

Overall, the code appears to be a workflow that involves building and executing different client and server examples using Rust and wasm. However, to provide a more comprehensive review, it would be helpful to see the complete code and its associated patches.

The key changes in the provided patch are as follows:

  1. The patch adds a step to download the wasmedge_rustls_plugin zip file and extract its contents. The extracted file libwasmedge_rustls.so is then moved to /usr/local/lib/wasmedge directory.

  2. Another step is added to build the wasmedge_hyper_client_https binary using Cargo and wasm32-wasi target. The resulting wasm binary is then converted to the wasmedge_hyper_client_https.wasm file.

  3. After the build, the wasmedge_hyper_client_https.wasm file is executed using the wasmedge command. The output response is captured and checked for the presence of the string "WasmEdge". If the response contains "WasmEdge", it prints "Execution Success!". Otherwise, it prints "Execution Fail!" and exits with a status code of 1.

client-https/Cargo.toml

The dependencies section of the code is provided, but it's difficult to review without having access to the actual code implementation.

However, it appears that the code is configuring dependencies for a Rust project related to making HTTPS requests using the Hyper library.

Here are a few general points to consider when working with HTTPS in Rust:

  1. Verify proper SSL/TLS certificate validation: It's crucial to correctly verify the SSL/TLS certificates of the server when making HTTPS requests. Ensure that the code enforces proper certificate validation.

  2. Handle errors properly: Make sure that the code handles any potential errors that may occur during the HTTPS communication. Error handling should be done robustly and inform the caller about any failures.

  3. Encourage secure cipher suites: When making HTTPS requests, it's important to ensure that secure cipher suites are used. Review the code to ensure that it's using strong encryption algorithms and secure default cipher suites.

  4. Keep dependencies up to date: Regularly update the dependencies used in the project to include any security patches and bug fixes.

Since the code itself is not provided, it's not possible to review specific implementation details or potential vulnerability points. Therefore, it's important to thoroughly review the implementation and apply best practices for secure HTTPS communication in Rust.

The key changes in the provided patch include:

  1. Added a new package with the name "wasmedge_hyper_client_https".
  2. Set the version of the package to "0.1.0".
  3. Updated the edition of the package to "2021".
  4. Added dependencies for the project, including:
    • "hyper_wasi" version 0.15 with the "full" feature enabled.
    • "http-body-util" version 0.1.0-rc.2.
    • "tokio_wasi" version 1 with the features "rt", "macros", "net", "time", and "io-util" enabled.
    • "pretty_env_logger" version 0.4.0.
    • "wasmedge_rustls_api" version 0.1 with the "tokio_async" feature enabled.

These changes indicate the addition of necessary dependencies for the project, including the Hyper library for making HTTP requests, logging utilities, and other relevant dependencies required for HTTPS communication.

client-https/src/main.rs

Overall, the source code looks fine and follows good practices for handling HTTPS requests. However, there are a few areas that could be improved or have potential problems:

  1. Error Handling: The code extensively uses .unwrap() to handle errors, which can lead to panics if an error occurs. It would be better to use proper error handling using ? or Result to handle errors gracefully.

  2. Capturing Errors: The code uses println! to print out errors in the spawned task. It would be better to properly handle and report the errors using logging or returning them from the function.

  3. Unused Imports: The code imports tokio::net::TcpStream but uses hyper::Request without explicitly importing it. It is recommended to import all necessary dependencies explicitly to avoid confusion.

  4. Hardcoded URL: The code uses a hardcoded URL ("https://httpbin.org/get?msg=WasmEdge") to fetch the HTTPS URL. It would be better to make the URL configurable or accept it as a parameter.

  5. Magic Numbers: The code uses 443 as the default port for HTTPS, which is the standard port. It would be better to define this number as a constant or use a named constant from a library to improve readability.

  6. Error Handling for Parsing: The code uses .parse::<hyper::Uri>().unwrap() to parse the URL, assuming it will always be successful. It would be better to handle the parsing error using proper error handling mechanisms.

  7. Logging: Consider using a logging library instead of directly using println!. This will provide more flexibility and control over logging output.

  8. Code Structure: The code could benefit from separating concerns into smaller functions to improve readability, maintainability, and testability.

Overall, the code works, but addressing these areas would result in more robust and maintainable code.

The key changes in the patch are as follows:

  1. Import hyper::Request and tokio::net::TcpStream.

  2. Define a Result type alias for handling errors.

  3. Wrap the main function in the tokio::main attribute to enable asynchronous execution.

  4. Add fetch_https_url function to handle fetching the HTTPS URL asynchronously.

  5. Parse the hardcoded URL to a hyper::Uri and pass it to the fetch_https_url function.

  6. Handle the error cases using proper error handling mechanisms such as unwrap() and ?.

  7. Connect to the HTTPS server using a TcpStream and wasmedge_rustls_api::ClientConfig.

  8. Perform a handshake with the server to establish the TLS connection using wasmedge_rustls_api::stream::async_stream::TlsStream.

  9. Use a spawned task to handle errors in the connection.

  10. Build the HTTP request with the URI, host header, and an empty body.

  11. Send the request using the sender obtained from the connection.

  12. Print the response status and headers.

  13. Read the response body and print it as a UTF-8 string.

  14. Print a message indicating the completion of the request.

  15. Return a Result indicating the success or failure of the function.

client/Cargo.toml

The provided code is a Cargo.toml file, which is used in Rust projects to declare dependencies and define project metadata. The code consists of dependency specifications for the project. Let's review the code for potential problems:

  1. Version Specification: The version field for dependencies should be carefully considered. Ensure that the specified versions are compatible with the project and its requirements. It's a good practice to use the tilde (~) or caret (^) operator for specifying version ranges, allowing for compatible updates.

  2. Dependency Audit: Review the dependencies for their stability, security, and maintenance status. Ensure that the specified versions of the dependencies are actively maintained and have no known security issues.

  3. Unused Dependencies: Check if any of the dependencies listed are not being used in the project. Removing unused dependencies helps reduce the size of the final build and avoids unnecessary dependencies.

  4. Transitive Dependencies: Some dependencies might bring along their own dependencies ('transitive dependencies'). Make sure these dependencies are also reviewed for compatibility, stability, and security.

  5. Licensing: Review the licenses of the dependencies to ensure they are compatible with the project's requirements. Ensure that all required licenses and attributions are provided and comply with the open-source licenses, if applicable.

  6. Compatibility: Verify that the specified versions of the dependencies are compatible with each other. Incompatible versions may cause conflicts during compilation or runtime.

  7. Documentation: Verify that the dependencies have appropriate documentation available, such as API references, examples, and usage guides.

It's important to note that without the actual code and its usage, it's not possible to thoroughly review the dependencies and their compatibility with the project. The provided code is only a partial portion of the Cargo.toml file, so a more comprehensive review is not possible.

The key changes in the patch are as follows:

  1. Indentation: The patch fixes the indentation within the tokio_wasi dependency specification. Each feature is now properly indented for better readability.

  2. Code Formatting: The patch adds whitespace around the curly braces {} of both hyper_wasi and tokio_wasi dependencies. This change improves code formatting consistency.

Besides these formatting changes, there are no major modifications or additions in the provided patch.

client/src/main.rs

Overall, the code looks fine and there are no major issues. However, there are a few potential problems and improvements that can be made:

  1. Incomplete URL Parsing: The code uses url_str.parse::<hyper::Uri>().unwrap() to parse the URL. This assumes that the URL parsing will always succeed, which can lead to a panic if the parsing fails. It's better to use url_str.parse::<hyper::Uri>()? instead and return an error if the parsing fails.

  2. Lack of Error Handling: The code does not handle errors properly in some places. For example, if an error occurs during the HTTP request, it is simply ignored in fetch_url, fetch_url_return_str, and post_url_return_str functions. It's important to handle errors and propagate them up the call stack.

  3. Printed Response as Byte Stream: In the fetch_url function, the response payload is printed as a byte stream using println!("{:#?}", chunk). This can lead to a large amount of output, especially for large responses. It might be better to comment out this line or remove it in a production environment.

  4. Unused import statement: There is an unused import statement for tokio::io::AsyncWriteExt commented out in the code. This should be removed to keep the code clean.

  5. Sleeping for Arbitrary Time: The code uses tokio::time::sleep to sleep for an arbitrary time (5 seconds) between different requests. This is often unnecessary and can be removed unless there is a specific reason for the delay.

  6. Redundant Send and Sync Bounds: The Result type alias has unnecessary Send and Sync bounds, which are not required for error handling. The type alias can be simplified to type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>.

Overall, these are minor suggestions and improvements to make the code cleaner and more robust.

The key changes in the patch are as follows:

  1. Added a delay of 5 seconds using tokio::time::sleep after the first HTTP request in the main function and after fetching the result as a string in the fetch_url_return_str function.

  2. Removed the commented-out AsyncWriteExt import statement, which was unused.

  3. Removed unnecessary whitespace around function names in the function definitions of fetch_url_return_str and post_url_return_str.