Skip to content

Test and Update Authentication Module #124

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

Draft
wants to merge 114 commits into
base: develop
Choose a base branch
from

Conversation

codegen-sh[bot]
Copy link

@codegen-sh codegen-sh bot commented May 17, 2025

Overview

This PR implements comprehensive testing and security updates for the Authentication module in the Codegen SDK.

Changes

  1. Added Comprehensive Test Suite:

    • Created unit tests for all authentication components
    • Added tests for token management, login flow, session handling, and decorators
    • Implemented test fixtures for reusable test components
  2. Security Improvements:

    • Enhanced token storage security with proper file permissions
    • Implemented secure token deletion with file overwriting
    • Added atomic file operations for token storage
    • Improved directory permission handling
  3. Error Handling Enhancements:

    • Added comprehensive error handling for authentication failures
    • Improved logging for authentication operations
    • Enhanced error messages for better user experience
  4. Documentation Updates:

    • Added detailed README.md for the authentication module
    • Improved docstrings for all authentication components
    • Added usage examples for authentication interfaces

Testing

All tests pass successfully, verifying the functionality and security of the authentication module.

Related Issues

Resolves ZAM-412


💻 View my workAbout Codegen

Note

I'm currently writing a description for your pull request. I should be done shortly (<1 minute). Please don't edit the description field until I'm finished, or we may overwrite each other. If I find nothing to write about, I'll delete this message.

Summary by Sourcery

Secure and harden the Authentication module by enforcing file/dir permission controls, using atomic writes and secure deletion for tokens, improving error handling and logging in authentication flows and decorators, and adding comprehensive unit tests and documentation. Also adjust CI config in package.json and pyproject.toml.

Enhancements:

  • Enforce secure permissions on config directory and token files with atomic write operations and secure deletion.
  • Improve error handling and logging in TokenManager methods, login flow, and auth decorators, including graceful browser fallback and login failure handling.

CI:

  • Update release branch configuration and packageManager field in package.json and comment out temporary pytest addopts in pyproject.toml.

Documentation:

  • Add detailed README.md and enhance docstrings for authentication components.

Tests:

  • Add comprehensive unit tests covering TokenManager, login flow, decorators, and CodegenSession behaviors.

clee-codegen and others added 30 commits February 26, 2025 23:54
# Motivation

The **Codegen on OSS** package provides a pipeline that:

- **Collects repository URLs** from different sources (e.g., CSV files
or GitHub searches).
- **Parses repositories** using the codegen tool.
- **Profiles performance** and logs metrics for each parsing run.
- **Logs errors** to help pinpoint parsing failures or performance
bottlenecks.

<!-- Why is this change necessary? -->

# Content

<!-- Please include a summary of the change -->
see
[codegen-on-oss/README.md](https://github.com/codegen-sh/codegen-sdk/blob/acfe3dc07b65670af33b977fa1e7bc8627fd714e/codegen-on-oss/README.md)

# Testing

<!-- How was the change tested? -->
`uv run modal run modal_run.py`
No unit tests yet 😿 

# Please check the following before marking your PR as ready for review

- [ ] I have added tests for my changes
- [x] I have updated the documentation or added new documentation as
needed
Original commit by Tawsif Kamal: Revert "Revert "Adding Schema for Tool Outputs"" (codegen-sh#894)

Reverts codegen-sh#892

---------

Co-authored-by: Rushil Patel <rpatel@codegen.com>
Co-authored-by: rushilpatel0 <171610820+rushilpatel0@users.noreply.github.com>
Original commit by Ellen Agarwal: fix: Workaround for relace not adding newlines (codegen-sh#907)
Copy link

korbit-ai bot commented May 17, 2025

By default, I don't review pull requests opened by bots. If you would like me to review this pull request anyway, you can request a review via the /korbit-review command in a comment.

Copy link

coderabbitai bot commented May 17, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Join our Discord community for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

sourcery-ai bot commented May 17, 2025

Reviewer's Guide

This PR introduces a comprehensive unit test suite for the Authentication module, hardens token storage and removal with atomic file operations and strict permissions, enhances error handling and logging across authentication workflows, refines the decorator-based login flow, updates documentation and docstrings, and tweaks project configuration for testing and release management.

Sequence Diagram for Secure Token Saving (TokenManager.save_token)

sequenceDiagram
    participant C as Client
    participant TM as TokenManager
    participant FS as FileSystem

    C->>TM: save_token(api_token)
    TM->>TM: _ensure_config_dir()  // Ensures dir exists with 0700 permissions
    Note over TM,FS: Writes token to a temporary file first
    TM->>FS: open(temp_file, "w")
    TM->>FS: json.dump({"token": api_token}, f)
    TM->>FS: os.chmod(temp_file, 0o600) // Secure temp file
    Note over TM,FS: Atomically replaces the old token file
    TM->>FS: os.replace(temp_file, self.token_file)
    alt Error During Save
        TM->>FS: Operation Fails (e.g., I/O error)
        FS-->>TM: Raises OSError
        TM-->>C: Raises OSError (logs error)
    end
Loading

Sequence Diagram for Secure Token Retrieval (TokenManager.get_token)

sequenceDiagram
    participant C as Client
    participant TM as TokenManager
    participant FS as FileSystem

    C->>TM: get_token()
    TM->>FS: os.access(config_dir, R_OK)?
    alt Config directory not readable
        FS-->>TM: False (or raises error)
        TM->>TM: Log warning
        TM-->>C: None
    end
    TM->>FS: os.path.exists(token_file)?
    alt Token file does not exist
        FS-->>TM: False
        TM-->>C: None
    end
    TM->>FS: os.stat(token_file) // Get file mode
    FS-->>TM: file_mode
    alt Insecure file permissions (group/other access)
        TM->>TM: Log warning "Token file has insecure permissions, fixing..."
        TM->>FS: os.chmod(token_file, 0o600) // Set to read/write for owner only
    end
    TM->>FS: open(token_file, "r")
    FS-->>TM: File handle
    TM->>TM: data = json.load(f)
    alt Invalid JSON or No Token in file
        TM->>TM: Log error (e.g., "Invalid JSON in token file")
        TM-->>C: None
    else Token Key Missing
        TM->>TM: Log warning ("Token file exists but contains no token")
        TM-->>C: None
    end
    TM-->>C: token
    alt OSError during read
        TM->>TM: Log error
        TM-->>C: None
    end
Loading

Sequence Diagram for requires_auth Decorator Logic

sequenceDiagram
    actor User
    participant CLIApp as "CLI Application"
    participant DecoratedFunc as "Decorated Function"
    participant RequiresAuth as "@requires_auth"
    participant TokenHelper as "Token Handling (get_current_token, TokenManager)"
    participant LoginRoutine as "login_routine"

    User->>CLIApp: Executes command
    CLIApp->>DecoratedFunc: Call protected function
    activate RequiresAuth
    RequiresAuth->>RequiresAuth: Check active session (CodegenSession)
    alt No active session
        RequiresAuth->>User: Error: "No active session. Please run 'codegen init'."
        RequiresAuth-->>CLIApp: Abort
    end

    RequiresAuth->>TokenHelper: get_current_token()
    TokenHelper-->>RequiresAuth: token / None

    alt No token found (token is None)
        RequiresAuth->>User: "Not authenticated. Let's get you logged in first!"
        RequiresAuth->>LoginRoutine: login_routine()
        activate LoginRoutine
        LoginRoutine-->>RequiresAuth: Success (token authenticated & saved) / Abort on failure
        deactivate LoginRoutine
        alt login_routine aborted
            RequiresAuth-->>CLIApp: Abort
        end
    else Token found
        RequiresAuth->>TokenHelper: TokenManager().authenticate_token(token)
        alt AuthError (token invalid/expired)
            TokenHelper-->>RequiresAuth: AuthError
            RequiresAuth->>User: "Authentication token is invalid or expired. Let's get you logged in again!"
            RequiresAuth->>LoginRoutine: login_routine()
            activate LoginRoutine
            LoginRoutine-->>RequiresAuth: Success (token authenticated & saved) / Abort on failure
            deactivate LoginRoutine
            alt login_routine aborted
                RequiresAuth-->>CLIApp: Abort
            end
        else Token is valid
            TokenHelper-->>RequiresAuth: Success
        end
    end

    opt Authentication Succeeded
        RequiresAuth->>DecoratedFunc: Execute original_function(session=...)
        DecoratedFunc-->>RequiresAuth: result
    end
    RequiresAuth-->>CLIApp: result / (already aborted if auth failed)
    deactivate RequiresAuth
Loading

Sequence Diagram for login_routine Authentication Flow

sequenceDiagram
    participant Caller as "Caller (e.g. @requires_auth)"
    participant LoginRoutine as "login_routine"
    participant Env as "Environment Vars"
    actor User
    participant WebBrowser as "webbrowser"
    participant CLIPrompt as "CLI Prompt (click)"
    participant TokenMgr as "TokenManager"
    participant RestAPI as "RestAPI"

    Caller->>LoginRoutine: login_routine(token_arg)
    LoginRoutine->>LoginRoutine: Use token_arg if provided
    alt No token_arg provided
        LoginRoutine->>Env: Get CODEGEN_USER_ACCESS_TOKEN
        Env-->>LoginRoutine: env_token / None
        LoginRoutine->>LoginRoutine: Use env_token if provided
    end

    alt Still no token (from arg or ENV)
        LoginRoutine->>User: "Opening <USER_SECRETS_ROUTE> to get your token..."
        LoginRoutine->>WebBrowser: open_new(USER_SECRETS_ROUTE)
        alt webbrowser.open_new() fails
            WebBrowser-->>LoginRoutine: Exception (e.g., browser not found)
            LoginRoutine->>User: "Could not open browser. Please visit URL manually."
        end
        LoginRoutine->>CLIPrompt: click.prompt("Please enter your authentication token")
        CLIPrompt-->>LoginRoutine: user_entered_token
        alt User provides no token via prompt
             LoginRoutine-->>Caller: Raise ClickException("Token is required for authentication.")
        end
    end

    LoginRoutine->>TokenMgr: TokenManager().authenticate_token(final_token)
    activate TokenMgr
    TokenMgr->>RestAPI: identify()
    RestAPI-->>TokenMgr: Identity / AuthError
    alt Authentication successful
        TokenMgr->>TokenMgr: save_token(final_token) // Securely saves the token
        TokenMgr-->>LoginRoutine: Success
        LoginRoutine->>User: "Successfully logged in..." (example message)
        LoginRoutine-->>Caller: final_token
    else Authentication failed (AuthError)
        TokenMgr-->>LoginRoutine: AuthError (e.g. invalid token)
        LoginRoutine->>User: Error message (e.g. "Error: Current session is not active...")
        LoginRoutine-->>Caller: Raise ClickException
    deactivate TokenMgr
    else Unexpected Error during login
        LoginRoutine->>User: Error message (e.g. "Unexpected error: ...")
        LoginRoutine-->>Caller: Raise ClickException
    end
Loading

Updated Class Diagram for TokenManager

classDiagram
    class TokenManager {
        +config_dir: Path
        +token_file: Path
        +__init__()
        +_ensure_config_dir()
        +authenticate_token(token: str)
        +save_token(token: str)
        +get_token() str | None
        +clear_token()
    }
    note for TokenManager "_ensure_config_dir(): Sets secure directory permissions (0700)."
    note for TokenManager "authenticate_token(token): Enhanced with comprehensive error handling and logging."
    note for TokenManager "save_token(token): Implements secure atomic write using a temporary file and sets secure file permissions (0600)."
    note for TokenManager "get_token(): Adds checks for file permissions (fixing if insecure), improved error handling for file read/parse issues, and logging."
    note for TokenManager "clear_token(): Securely overwrites the token file content with null bytes before deletion."
Loading

File-Level Changes

Change Details Files
Added comprehensive test suite for authentication components
  • Created unit tests covering TokenManager, login, decorators, session and constants
  • Introduced fixtures for reusable test setup
  • Verified token flows, error cases and CLI behaviors
  • Grouped tests under tests/unit/codegen/cli/auth
tests/unit/codegen/cli/auth/test_session.py
tests/unit/codegen/cli/auth/test_token_manager.py
tests/unit/codegen/cli/auth/test_decorators.py
tests/unit/codegen/cli/auth/test_login.py
tests/unit/codegen/cli/auth/simple_test.py
tests/unit/codegen/cli/auth/test_constants.py
tests/unit/codegen/cli/auth/conftest.py
Enhanced security and atomic operations in TokenManager
  • Set config directory permissions to owner-only (0700)
  • Wrote tokens via a temp file with 0600 permissions
  • Replaced old token file atomically
  • Overwrote and securely deleted token files
src/codegen/cli/auth/token_manager.py
Improved error handling and logging across auth workflows
  • Wrapped token authentication and login routines in try/except with detailed logs
  • Logged and fixed insecure token file permissions on read
  • Added JSON decode and I/O error handling
  • Enhanced error messages for better user feedback
src/codegen/cli/auth/token_manager.py
src/codegen/cli/auth/login.py
Refined requires_auth decorator and login flow
  • Logged missing/invalid session and token events
  • Wrapped login flow calls in try/except with logging and error display
  • Added debug logs for token validation steps
src/codegen/cli/auth/decorators.py
Augmented documentation and docstrings
  • Added detailed README.md with module overview, usage examples and security notes
  • Improved docstrings for token manager, decorators and login functions
  • Documented components, error types and security measures
src/codegen/cli/auth/README.md
src/codegen/cli/auth/token_manager.py
src/codegen/cli/auth/decorators.py
src/codegen/cli/auth/login.py
Updated project configuration for testing and release
  • Commented out pytest addopts in pyproject.toml for current tests
  • Added explicit packageManager entry to package.json
  • Refined semantic-release branches formatting
pyproject.toml
package.json

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Author

codegen-sh bot commented May 17, 2025

I see a check failed - I'm on it! 🫡

💻 View my work

Copy link
Author

codegen-sh bot commented May 17, 2025

✅ Fixed the failing pre-commit checks in this commit. The issues were primarily formatting-related:

  1. Fixed formatting in package.json and pyproject.toml
  2. Improved error logging in authentication module (using logger.exception instead of logger.error)
  3. Fixed whitespace, indentation, and markdown formatting issues

The CI should now pass successfully.

💻 View my work • React 👍 or 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants