Skip to content

feat: expose library crate for programmatic API access#376

Closed
geofflittle wants to merge 9 commits intogoogleworkspace:mainfrom
geofflittle:feat/library-crate
Closed

feat: expose library crate for programmatic API access#376
geofflittle wants to merge 9 commits intogoogleworkspace:mainfrom
geofflittle:feat/library-crate

Conversation

@geofflittle
Copy link

Summary

  • Adds a library crate (lib.rs) so gws can be used as a Rust dependency for programmatic API access
  • Extracts config_dir() and Model Armor sanitization types into standalone modules (config.rs, sanitize.rs) to decouple library from CLI
  • Moves parse_service_and_version() to services.rs for dual crate-root access
  • Includes GCP location validation to prevent SSRF, --api-version flag parsing fix, and config dir env override restoration

Zero behavior changes to the binary. All existing tests pass.

Supersedes #214 (auto-closed by stale bot). Addresses #211.

Test plan

  • cargo test — all existing tests pass
  • cargo clippy -- -D warnings clean
  • New integration tests (tests/lib_integration.rs) verify library surface
  • Manual verification of --api-version flag parsing

🤖 Generated with Claude Code

@geofflittle geofflittle requested a review from jpoehnelt as a code owner March 10, 2026 16:28
@changeset-bot
Copy link

changeset-bot bot commented Mar 10, 2026

🦋 Changeset detected

Latest commit: 88de70a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@googleworkspace/cli Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the gws project by introducing a dedicated library crate, making its core functionalities programmatically accessible. This involved a substantial internal refactoring effort to separate shared logic, such as configuration directory resolution and Model Armor sanitization, into new, independent modules. The changes also include crucial security improvements like GCP location validation and a more robust --api-version flag parsing mechanism, all while preserving the existing CLI behavior.

Highlights

  • Library Crate Exposure: Exposed a new library crate (lib.rs) to allow programmatic API access to gws functionality, enabling its use as a Rust dependency.
  • Module Refactoring: Refactored config_dir() and Model Armor sanitization types into new standalone modules (config.rs, sanitize.rs) to decouple core logic from CLI-specific components, facilitating dual crate-root access.
  • API Version Parsing Improvement: Moved parse_service_and_version() to services.rs and enhanced its logic to correctly parse the --api-version flag, including cases like --api-version=v1.
  • Security Enhancements: Implemented GCP location validation to prevent Server-Side Request Forgery (SSRF) by disallowing dots and other invalid characters in location identifiers used in API URLs.
  • No Behavioral Changes: Ensured that all changes maintain existing binary behavior, with all previous tests passing and new integration tests verifying the library surface.
Changelog
  • .changeset/add-library-crate.md
    • Added a new changeset file.
    • Documented the addition of the library crate.
    • Documented the extraction of config_dir() and Model Armor sanitization types.
  • .changeset/sanitize-ssrf-validation.md
    • Added a new changeset file.
    • Documented the validation of sanitize template parameters against path traversal and SSRF.
  • Cargo.toml
    • Configured the project to expose src/lib.rs as the library crate.
  • src/auth.rs
    • Updated the config_dir() function call to use the new config module.
  • src/auth_commands.rs
    • Removed the config_dir() implementation.
    • Delegated config_dir() to crate::config::config_dir().
  • src/config.rs
    • Created a new module to centralize the config_dir() logic.
    • Moved the config_dir() function from src/auth_commands.rs to this file.
    • Added documentation for config_dir().
  • src/credential_store.rs
    • Updated config_dir() function calls to use the new config module.
  • src/discovery.rs
    • Updated the config_dir() function call to use the new config module.
  • src/executor.rs
    • Updated references to Model Armor sanitization types and functions to the new sanitize module.
  • src/helpers/modelarmor.rs
    • Removed SanitizationResult, SanitizeMode, SanitizeConfig structs and CLOUD_PLATFORM_SCOPE constant.
    • Removed sanitize_text, build_sanitize_request_data, and parse_sanitize_response functions.
    • Added pub use crate::sanitize::{...} to re-export these types and functions from the new sanitize module.
    • Updated SanitizeMode::from_str calls in tests to SanitizeMode::from.
    • Added new tests for build_sanitize_request_data to reject path traversal, query injection, percent-encoded, and dotted locations.
  • src/lib.rs
    • Created a new file to serve as the library crate entry point.
    • Declared public modules for programmatic access.
    • Added #![allow(dead_code)] for internal modules shared with the binary.
  • src/main.rs
    • Added pub(crate) mod config; and pub(crate) mod sanitize; declarations.
    • Updated helpers::modelarmor::SanitizeMode::from_str to helpers::modelarmor::SanitizeMode::from.
    • Changed select_scope(&method.scopes) to services::select_scope(&method.scopes).
    • Removed the local select_scope function.
    • Changed the local parse_service_and_version function to call services::parse_service_and_version.
    • Removed tests related to select_scope.
  • src/oauth_config.rs
    • Updated the config_dir() function call to use the new config module.
  • src/sanitize.rs
    • Created a new module to encapsulate Model Armor sanitization logic and types.
    • Moved SanitizationResult, SanitizeMode, SanitizeConfig structs and CLOUD_PLATFORM_SCOPE constant from src/helpers/modelarmor.rs.
    • Moved sanitize_text, build_sanitize_request_data, and parse_sanitize_response functions from src/helpers/modelarmor.rs.
    • Added regional_base_url and extract_location helper functions.
    • Integrated crate::validate::validate_resource_name and crate::validate::validate_gcp_location into build_sanitize_request_data.
  • src/services.rs
    • Moved the select_scope function from src/main.rs to this file.
    • Moved the parse_service_and_version function from src/main.rs to this file.
    • Enhanced parse_service_and_version to handle --api-version flag parsing more robustly.
    • Added tests for select_scope.
  • src/validate.rs
    • Added pub fn validate_gcp_location(s: &str) to validate GCP region/location identifiers, specifically disallowing dots to prevent SSRF.
    • Added tests for validate_gcp_location.
  • tests/lib_integration.rs
    • Created a new file.
    • Added integration tests to verify the public API of the gws library crate.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Generative AI Prohibited Use Policy, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request successfully refactors the codebase to expose a library crate, which is a great step for enabling programmatic use of gws. The extraction of configuration and sanitization logic into separate modules (config.rs, sanitize.rs) is well-executed and improves the project structure. I appreciate the security enhancements, particularly the GCP location validation to prevent SSRF and the more robust parsing of --api-version. The changes are clean and the addition of integration tests for the new library is a good practice. I have one suggestion regarding the public API of the new library crate to improve its design.

@github-actions
Copy link
Contributor

/gemini review

1 similar comment
@github-actions
Copy link
Contributor

/gemini review

@codecov
Copy link

codecov bot commented Mar 10, 2026

Codecov Report

❌ Patch coverage is 72.34043% with 65 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.38%. Comparing base (58c412c) to head (88de70a).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
src/sanitize.rs 60.00% 32 Missing ⚠️
src/services.rs 47.61% 22 Missing ⚠️
src/executor.rs 50.00% 3 Missing ⚠️
src/main.rs 0.00% 3 Missing ⚠️
src/auth.rs 0.00% 1 Missing ⚠️
src/discovery.rs 0.00% 1 Missing ⚠️
src/helpers/calendar.rs 0.00% 1 Missing ⚠️
src/helpers/gmail/triage.rs 0.00% 1 Missing ⚠️
src/helpers/workflows.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #376      +/-   ##
==========================================
+ Coverage   63.23%   63.38%   +0.15%     
==========================================
  Files          38       40       +2     
  Lines       15102    15188      +86     
==========================================
+ Hits         9549     9627      +78     
- Misses       5553     5561       +8     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jpoehnelt
Copy link
Member

Please rebase on main.

@googleworkspace-bot
Copy link
Collaborator

/gemini review

Extract `config_dir()` into `src/config.rs` and Model Armor sanitization
types into `src/sanitize.rs` so they can be shared between the binary and
library targets without pulling in CLI-only code. Add `src/lib.rs` with
public module re-exports and `tests/lib_integration.rs` with offline tests.

Also moves `parse_service_and_version()` from `main.rs` to `services.rs`
so it is accessible from both the lib and bin crate roots.

Zero behavior changes to the binary.
Add validate_resource_name() and validate_api_identifier() checks in
build_sanitize_request_data() to prevent path traversal, query injection,
and percent-encoded bypasses in the template parameter.
…ntax

- Remove #[cfg(test)] from GOOGLE_WORKSPACE_CLI_CONFIG_DIR check in
  config_dir() so the override works in release builds.
- Handle --api-version=v3 syntax in parse_service_and_version(), not
  just --api-version v3.
… template

Replace validate_api_identifier (which allows dots) with a stricter
validate_gcp_location that only permits lowercase alphanumeric and
hyphens. This prevents an attacker from injecting a dotted domain
(e.g. evil.com) into the Model Armor regional hostname.
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces a new library crate for programmatic API access to the Google Workspace CLI, involving significant refactoring to move shared utilities like config_dir() and Model Armor sanitization logic into dedicated, reusable modules (src/config.rs and src/sanitize.rs). It also enhances security by adding validation for sanitize template parameters to prevent path traversal and SSRF vulnerabilities. Review comments suggest improving the library's public API surface by making several modules pub(crate) instead of pub to limit exposure of CLI-specific or internal details, and refactoring a C-style loop in src/sanitize.rs to a more idiomatic and safer Rust iterator-based approach.

@googleworkspace-bot
Copy link
Collaborator

/gemini review

- Restrict public API surface: make commands, credential_store,
  formatter, oauth_config, and token_storage pub(crate) instead of pub
- Refactor extract_location in sanitize.rs to use idiomatic iterator
  pattern instead of C-style indexed loop
@googleworkspace-bot
Copy link
Collaborator

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request successfully exposes a library crate for programmatic API access by refactoring shared logic into standalone modules. Key changes include moving configuration and sanitization logic into config.rs and sanitize.rs respectively. The pull request also introduces critical security improvements by validating GCP location parameters to prevent SSRF, and fixes a bug in --api-version flag parsing. The overall structure is sound, and the changes are of high quality. I have no further recommendations for improvement.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a significant and well-executed refactoring to expose a library crate, which will greatly improve the reusability of the project's core logic. The code has been thoughtfully decoupled into more logical modules, such as config and sanitize. I particularly appreciate the security enhancements, including the GCP location validation to prevent SSRF and the fix for --api-version flag parsing.

I've found one critical issue regarding module visibility that prevents a key part of the new public API from being used. Please see my comment for details. Once that is addressed, this will be an excellent addition to the codebase.

pub mod discovery;
pub mod error;
pub mod executor;
pub(crate) mod formatter;
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The formatter module is declared as pub(crate), which makes its contents, including the OutputFormat enum, inaccessible to external crates. However, the public function executor::execute_method has a parameter of type &crate::formatter::OutputFormat. This makes it impossible for consumers of this library to call execute_method, as they cannot construct a value of the required OutputFormat type. To make the public API usable, the formatter module should be made public.

Suggested change
pub(crate) mod formatter;
pub mod formatter;

@jpoehnelt
Copy link
Member

Thanks for the idea, will reconsider with some additional research on the best way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: auth area: core Core CLI parsing, commands, error handling, utilities area: discovery area: distribution area: http

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants