Skip to content

Conversation

@lakshayman
Copy link
Contributor

Date: 16 Jan 2025

Developer Name: @lakshayman


Description

This PR implements Phase 1, Week 2: Authentication Migration for the Feature Flag Backend. It enhances the authentication system to verify users against our internal database and provides user context throughout the request pipeline, moving away from external authentication dependency.

Key Features Implemented:

  1. Enhanced JWT Middleware with User Verification

    • Created JWTMiddlewareWithUserVerification() that validates JWT tokens and verifies users exist in our database
    • Checks if user account is active before allowing operations
    • Extracts role from both token and database (database is source of truth)
    • Returns UserContext with userId, role, and email
  2. User Context System

    • Added UserContext struct to pass authenticated user information through the request pipeline
    • Contains: userId, role, and email
    • Enables role-based access control in future iterations
  3. Database Helper Function

    • Added GetUserById() function in database layer for user lookups
    • Centralized user retrieval logic for consistency
  4. Endpoint Migration

    • Updated createFeatureFlag endpoint to use new authentication middleware
    • Removed userId requirement from request body (now uses authenticated user)
    • Improved security by preventing userId spoofing in requests
    • User ID is now automatically extracted from authenticated token
  5. Backward Compatibility

    • Original JWTMiddleware() remains unchanged for gradual migration
    • Existing endpoints continue to work during transition period
    • New middleware available for endpoints requiring user verification

Security Improvements:

  • User Verification: All authenticated requests now verify user exists in database
  • Active User Check: Inactive users are blocked from performing operations
  • Role Source of Truth: Database role takes precedence over token role, allowing role updates without re-login
  • UserId Protection: UserId can no longer be spoofed in request body - always uses authenticated user

Migration Strategy:

  • New endpoints use JWTMiddlewareWithUserVerification() for enhanced security
  • Existing endpoints can gradually migrate to new middleware
  • Both middleware functions coexist during transition period

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Database Changes:

  • No schema changes
  • Uses existing user table created in Week 1

Breaking Changes

  • Yes
  • No

Note: The CreateFeatureFlagRequest struct no longer requires userId in the request body. The userId is automatically extracted from the authenticated user's token. This is a non-breaking change as the field is now optional and will be ignored if provided.

Development Tested?

  • Yes
  • No

Testing:

  • ✅ SAM build passes successfully
  • ✅ Go compilation verified for all modified functions
  • ✅ Code follows existing patterns and conventions
  • ✅ Backward compatibility maintained

Screenshots

Screenshot 1

Test Coverage

Test Coverage Details

Additional Notes

API Changes

Before:
POST /feature-flags/
{
"name": "new-feature",
"description": "Description",
"userId": "user-123" // Required, but could be spoofed
}After:
POST /feature-flags/
{
"name": "new-feature",
"description": "Description"
// userId automatically extracted from authenticated token
}### Usage Example

New Middleware:
jwtResponse, userContext, err := jwt.JWTMiddlewareWithUserVerification()(req)
if err != nil || jwtResponse.StatusCode != http.StatusOK {
return jwtResponse, err
}

// Use userContext.UserId, userContext.Role, userContext.EmailOld Middleware (still works):
jwtResponse, userId, err := jwt.JWTMiddleware()(req)
if err != nil || jwtResponse.StatusCode != http.StatusOK {
return jwtResponse, err
}### Next Steps (Week 3)

  • Implement role-based access control (RBAC) middleware
  • Add permission checks for ADMIN, DEVELOPER, and VIEWER roles
  • Protect feature flag management endpoints with role requirements
  • Add comprehensive authorization logic

Security Considerations

  • User verification ensures only registered users can access the system
  • Active user check prevents disabled accounts from performing operations
  • Database role is source of truth, preventing token-based role manipulation
  • UserId in request body is ignored, preventing spoofing attacks

Files Changed

  • layer/jwt/jwt.go (updated - added enhanced middleware)
  • layer/database/dynamodb.go (updated - added GetUserById helper)
  • layer/utils/UserContext.go (new)
  • layer/utils/RequestResponse.go (updated - made userId optional)
  • createFeatureFlag/main.go (updated - uses new middleware)

Migration Path:

  1. ✅ Week 1: User service foundation
  2. ✅ Week 2: Authentication migration (this PR)
  3. 🔜 Week 3: Role-based access control
  4. 🔜 Week 4: Testing & documentation

- Enhance JWT middleware with user verification from database
- Add UserContext struct to pass authenticated user information
- Create JWTMiddlewareWithUserVerification for internal auth
- Add GetUserById database helper function
- Update createFeatureFlag endpoint to use authenticated user context
- Remove userId requirement from request body (use authenticated user)
- Verify user exists and is active before allowing operations
- Extract role from token and database for authorization
- Maintain backward compatibility with existing JWTMiddleware
@lakshayman lakshayman self-assigned this Jan 16, 2026
@coderabbitai
Copy link

coderabbitai bot commented Jan 16, 2026

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. 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.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lakshayman lakshayman changed the base branch from develop to phase1-week1-user-service-foundation January 16, 2026 10:02
@lakshayman lakshayman changed the title Phase1 week2 authentication migration feat: Phase 1 Week 2 - Authentication Migration Jan 16, 2026
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.

1 participant