Skip to content

Conversation

Copy link

Copilot AI commented Dec 5, 2025

Implements production-grade JWT-based authentication for API endpoints. Static user configuration for MVP; designed for OAuth/OIDC integration.

Core Implementation

  • JWT utilities (src/utils/auth.py): Token creation/validation, bcrypt password hashing, FastAPI dependency for route protection
  • Protected endpoints (src/interfaces/web_api.py): /chat, /ws/chat, /auth/refresh require valid JWT; health endpoints remain public
  • Login flow: POST /auth/login accepts username/password, returns JWT access token

Configuration

# .env
JWT_SECRET=<required-cryptographically-secure-string>
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
STATIC_USERS=username:bcrypt_hash

Application fails fast if JWT_SECRET not set.

WebSocket Authentication

ws.send(JSON.stringify({
  type: 'auth',
  token: '<jwt-token>'
}));
// First message must authenticate before subsequent chat messages

Security

  • CORS restricted to localhost:3000,8080 (update for production domains)
  • Bcrypt password hashing with salt
  • Token expiration enforced
  • Dependencies patched: fastapi==0.115.5, python-multipart==0.0.18 (fixes ReDoS and DoS CVEs)

Testing

24 tests covering authentication flows, token validation, protected/public endpoint access, WebSocket auth. CI pipeline via GitHub Actions.

Production Readiness

TODOs marked for production deployment:

  • Replace static users with OAuth/OIDC (Azure AD, Auth0, Okta)
  • Migrate HS256 to RS256/ES256 asymmetric keys
  • Implement refresh token rotation and revocation
  • Add rate limiting and audit logging

Default credentials (dev only): admin/admin123

Original prompt

Add production-grade authentication and authorization to protect the API and dashboard. Create a new feature branch (feature/auth-jwt) and open a PR with the changes. The PR should be a minimal, secure, and reviewable implementation that can be extended later.

Scope and acceptance criteria (actionable tasks):

  1. Implement JWT-based auth utilities

    • Add src/utils/auth.py with functions to create and verify JWT access tokens using a symmetric secret (env var JWT_SECRET) and algorithm (JWT_ALGORITHM, default HS256).
    • Provide functions: create_access_token(data: dict, expires_delta: Optional[timedelta]) -> str and decode_access_token(token: str) -> dict (raises custom exception on invalid/expired).
    • Add Pydantic model for TokenData and a simple User model used by the dependency.
  2. FastAPI dependency and route protection

    • Add a dependency get_current_user in src/utils/auth.py that extracts the Authorization header, validates the token, and returns the user object or HTTP 401/403 on failure.
    • Protect sensitive endpoints: update src/interfaces/web_api.py to require get_current_user for POST /chat, WebSocket /ws/chat, and any dashboard routes (if present). Non-sensitive health and open endpoints remain public.
  3. Login route and bootstrap

    • Add POST /auth/login that accepts username/password (for initial MVP use a configurable static user list via env or .env.example) and returns an access token. Make clear TODOs to replace with real identity provider (OAuth/SSO) for production.
    • Add POST /auth/refresh to exchange refresh token for new access token (optional minimal implementation if time permits) or document as TODO.
  4. Configuration and secrets

    • Add .env.example entries: JWT_SECRET (placeholder), JWT_ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES.
    • Add guidance in README excerpt about rotating keys and replacing symmetric JWT with asymmetric keys or integrating with OIDC in production.
  5. Tests and CI

    • Add tests/test_auth.py with pytest that verifies: login returns token, protected route returns 401 without token and 200 with valid token.
    • Ensure tests are included in the existing CI workflow; update .github/workflows/ci.yml if needed.
  6. Branch/PR details

    • Create branch feature/auth-jwt off main and open PR titled: "Add JWT authentication and authorization for API and dashboard". Include a clear description of what was added, how to test locally (env vars, run backend, curl commands), and a checklist for reviewers.
  7. Code quality

    • Use type hints, docstrings, and TODO comments where future work is expected (e.g., replace static user store with OIDC).
    • Do not commit any real secrets. Use .env.example and ask reviewers to set real secrets in their environment.

Notes:

  • This PR is intended to be the first production-hardening change and should be small and reviewable.
  • If you prefer OAuth/SSO instead of JWT, we can pivot, but JWT provides a fast improvement to secure endpoints.

Please create the issues for the checklist items and open the PR branch with the above implementation plan.

This pull request was created as a result of the following prompt from Copilot chat.

Add production-grade authentication and authorization to protect the API and dashboard. Create a new feature branch (feature/auth-jwt) and open a PR with the changes. The PR should be a minimal, secure, and reviewable implementation that can be extended later.

Scope and acceptance criteria (actionable tasks):

  1. Implement JWT-based auth utilities

    • Add src/utils/auth.py with functions to create and verify JWT access tokens using a symmetric secret (env var JWT_SECRET) and algorithm (JWT_ALGORITHM, default HS256).
    • Provide functions: create_access_token(data: dict, expires_delta: Optional[timedelta]) -> str and decode_access_token(token: str) -> dict (raises custom exception on invalid/expired).
    • Add Pydantic model for TokenData and a simple User model used by the dependency.
  2. FastAPI dependency and route protection

    • Add a dependency get_current_user in src/utils/auth.py that extracts the Authorization header, validates the token, and returns the user object or HTTP 401/403 on failure.
    • Protect sensitive endpoints: update src/interfaces/web_api.py to require get_current_user for POST /chat, WebSocket /ws/chat, and any dashboard routes (if present). Non-sensitive health and open endpoints remain public.
  3. Login route and bootstrap

    • Add POST /auth/login that accepts username/password (for initial MVP use a configurable static user list via env or .env.example) and returns an access token. Make clear TODOs to replace with real identity provider (OAuth/SSO) for production.
    • Add POST /auth/refresh to exchange refresh token for new access token (optional minimal implementation if time permits) or document as TODO.
  4. Configuration and secrets

    • Add .env.example entries: JWT_SECRET (placeholder), JWT_ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES.
    • Add guidance in README excerpt about rotating keys and replacing symmetric JWT with asymmetric keys or integrating with OIDC in production.
  5. Tests and CI

    • Add tests/test_auth.py with pytest that verifies: login returns token, protected route returns 401 without token and 200 with valid token.
    • Ensure tests are included in the existing CI workflow; update .github/workflows/ci.yml if needed.
  6. Branch/PR details

    • Create branch feature/auth-jwt off main and open PR titled: "Add JWT authentication and authorization for API and dashboard". Include a clear description of what was added, how to test locally (env vars, run backend, curl commands), and a checklist for reviewers.
  7. Code quality

    • Use type hints, docstrings, and TODO comments where future work is expected (e.g., replace static user store with OIDC).
    • Do not commit any real secrets. Use .env.example and ask reviewers to set real secrets in their environment.

Notes:

  • This PR is intended to be the first production-hardening change and should be small and reviewable.
  • If you prefer OAuth/SSO instead of JWT, we can pivot, but JWT provides a fast improvement to secure endpoints.

Please create the issues for the checklist items and open the PR branch with the above implementation plan.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 5 commits December 5, 2025 03:09
Co-authored-by: Stacey77 <54900383+Stacey77@users.noreply.github.com>
Co-authored-by: Stacey77 <54900383+Stacey77@users.noreply.github.com>
Co-authored-by: Stacey77 <54900383+Stacey77@users.noreply.github.com>
…cies

Co-authored-by: Stacey77 <54900383+Stacey77@users.noreply.github.com>
Copilot AI changed the title [WIP] Add production-grade JWT authentication and authorization Add JWT authentication and authorization to API endpoints Dec 5, 2025
Copilot AI requested a review from Stacey77 December 5, 2025 03:25
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