CSC/ECE 517 Fall 2024 - E2487. Reimplement authorization helper.rb

From Expertiza_Wiki
Jump to navigation Jump to search

Introduction

Expertiza currently uses session-based authentication in its AuthorizationHelper module. However, the new back-end reimplementation adopts JSON Web Token (JWT) for authentication. This transition is necessary to make the system more scalable, stateless, and secure. JWT-based authentication will replace session-based methods, requiring updates to the AuthorizationHelper module and associated methods.

Background

The AuthorizationHelper module in Expertiza plays a critical role in managing user permissions and access control within the system. It provides methods to verify a user’s privileges based on their assigned roles, such as Super-Admin, Admin, Instructor, TA, or Student. These methods check if the user is authorized to perform actions like submitting assignments, reviewing work, or participating in quizzes. Additionally, it determines whether a user is involved in specific assignments, either as a participant, instructor, or through TA mappings.

Problem Statement

Expertiza currently uses session-based authentication in its [AuthorizationHelper] module. The [reimplementation-back-end] however, uses JWT (JSON Web Token) based authentication. This requires a redesign of the AuthorizationHelper module to accommodate JWT-based authentication.

The following points need to be taken care of as per the requirement

  • JWT Creation :
    • Enable the system to process, verify, and decode JWT tokens.
    • Use token data to authenticate users and authorize their actions.
  • Token expiry and revocation :
    • Implement token expiry mechanisms to ensure tokens have limited lifetimes.
    • Add a strategy to handle token revocation, such as maintaining a revocation list.
  • Privilege Verification :
    • Update methods to validate user privileges using JWT claims.
  • Testing and Documentation :
    • Write comprehensive unit tests for all JWT-related methods.
    • Include clear documentation and comments to aid future developers.

Proposed Changes

JWT Token Overview

A JSON Web Token (JWT) is a compact, URL-safe token format commonly used for securely transmitting information between parties. It is widely used in web applications for authentication and authorization, as it allows information to be verified and trusted. In the context of our reimplemented AuthorizationHelper module, JWT tokens will replace session-based authentication, enabling stateless and more secure access control.

A JWT Token consists of three main parts:

  • Header: Contains metadata about the token, such as the type (JWT) and the hashing algorithm used (e.g., HS256 or RS256).
  • Payload: Includes claims, which are statements about an entity (typically, the user) and additional data like the user’s role and permissions.
  • Signature: A cryptographic signature generated by encoding the header and payload with a secret key or private key, ensuring data integrity.

These three sections are separated by dots (.), forming a token that looks like this: <Header>.<Payload>.<Signature>

Methods to implement

  • jwt_verify_and_decode(token): This method will verify and decode a JWT token and return the user's information, including role and claims. Successful verification of the token signature with the secret key will be followed by extraction of the payload which will contain important information about the user and their role for authentication and authorization.
  • check_user_privileges(user_info, required_privilege): extract the user's roles or permissions from user_info (e.g., from the decoded JWT payload). Then, check if required_privilege exists within the user's permissions, returning true if it does and false otherwise to control access accordingly.

Existing Methods to update

  • current_user_is_a?(role_name):
 def current_user_is_a?(role_name)
     current_user_and_role_exist? && session[:user].role.name == role_name
 end

Currently this method relies on the session variable which is populated at the time of login to determine the role of a user. This would have to be updated to decode the user's role from the JWT payload

  • user_logged_in?:
 def user_logged_in?
     !session[:user].nil?
 end

This method will have to be updated to check the user's login status based on JWT validity

  • current_user_has_privileges_of?(role_name)
 def current_user_has_privileges_of?(role_name)
    current_user_and_role_exist? && session[:user].role.has_all_privileges_of?(Role.find_by(name: role_name))
 end

Needs to remove dependency on session variable and get user information from the JWT's decoded payload

  • current_user_and_role_exist?
 def current_user_and_role_exist?
     user_logged_in? && !session[:user].role.nil?
 end

Similarly, the role here needs to be checked from the JWT payload Similarly methods like current_user_has_id?(id) will also have to be updated to remove dependencies from the session object, which are all part of the [AuthorizationHelper] module

Anticipated Outcomes

1. Enhanced AuthorizationHelper Module with JWT Integration:
Updated and operational AuthorizationHelper module that would use JWT-based authentication. The module would be restructured to incorporate token-based authentication checks, replacing prior session-based methods.

2. Updated Associated Methods:
Methods within the module will have to be updated to leverage JWT claims, ensuring authentication and authorization are handled based on token data. This will allow the module to verify user roles and permissions effectively through JWT claims.

3. Comprehensive JWT Error Handling:
Built-in error handling to manage potential JWT-related issues, such as token expiration, tampering, or invalid claims. This ensures that unauthorized access is blocked, and clear error messages are provided when issues arise.

4. Robust Unit Tests for Validation:
A full suite of unit tests covering various scenarios, including normal, boundary, and edge cases, to validate each method’s functionality and confirm that all JWT-based authentication flows work reliably.

5. Detailed Documentation and Code Comments:
In-depth documentation and comments would be added to each function, explaining purpose, usage, and JWT-related adjustments, aiding in code readability and future maintenance.

Design Principles

The redesign of the AuthorizationHelper module for JWT-based authentication adheres to several core design principles to ensure scalability, maintainability, security, and user-centric functionality. Below, we outline the principles and their application in the context of this project:

1. Single Responsibility Principle (SRP) Definition: Each module or class should have one and only one reason to change. Application:

  • The AuthorizationHelper module is solely responsible for managing user authentication and authorization. By separating authentication (token verification) and authorization (privilege checking) into distinct methods, we ensure clarity and easier maintenance.
  • Methods like jwt_verify_and_decode focus exclusively on token verification, while methods like check_user_privileges handle role-based privilege checks.

2. Separation of Concerns Definition: Different concerns of a system should be managed in distinct parts of the codebase. Application:

  • JWT creation and decoding are handled by the JsonWebToken class, ensuring the AuthorizationHelper module is not overloaded with cryptographic logic.
  • Business logic for determining user privileges is distinct from the logic for managing user sessions or tokens, allowing modular testing and independent updates.

3. Security by Design Definition: Security considerations should be integral to the system's design from the outset. Application:

  • Sensitive token data (e.g., secret keys) is stored securely in environment variables.
  • JWT tokens are validated for expiry and tampering before any privilege checks occur.
  • Role-based access control (RBAC) ensures fine-grained control over user actions based on claims within the token.
  • All communication involving JWTs is secured using HTTPS to prevent token interception.

4. Statelessness Definition: The system should not store client-specific data on the server between requests. Application:

  • JWT-based authentication eliminates the dependency on session storage, making the system stateless and scalable.
  • All necessary information about the user is encoded in the token, allowing distributed servers to authenticate and authorize users without shared session data.

5. DRY (Don’t Repeat Yourself) Definition: Avoid duplication of code by abstracting reusable logic. Application:

  • Common operations, such as JWT decoding, privilege checks, and role comparisons, are encapsulated in reusable methods (jwt_verify_and_decode, check_user_privileges).
  • This reduces redundancy and makes updates easier, as changes in logic need to be applied only once.

6. Fail Fast Definition: Systems should detect errors early and fail predictably. Application:

  • Methods like jwt_verify_and_decode and check_user_privileges handle invalid tokens or missing claims by immediately returning error responses.
  • Explicit checks for token validity, role presence, and privilege requirements ensure errors are caught before proceeding to sensitive operations.

7. Testability Definition: Code should be designed to facilitate comprehensive and reliable testing. Application:

  • Modular methods, each with a single responsibility, make unit testing straightforward.
  • Mock tokens can be used to test various scenarios, including valid, expired, and tampered tokens.
  • Edge cases, such as missing roles or conflicting claims, are explicitly tested.

8. Scalability Definition: Systems should be able to handle increased load without significant changes to the architecture. Application:

  • Stateless JWT authentication allows multiple servers to handle authentication independently, enhancing horizontal scalability.
  • A revocation list stored in a distributed cache (e.g., Redis) ensures token invalidation mechanisms scale with user growth.

9. Code Readability Definition: Code should be easy to read and understand for future developers. Application:

  • Each method is well-documented with clear comments explaining its purpose, inputs, outputs, and error handling.
  • Logical naming conventions (check_user_privileges, current_user_is_a?) make the code self-explanatory.

10. Extensibility Definition: Design should allow easy addition of new features without affecting existing functionality. Application:

  • New roles or privileges can be added by updating the role hierarchy and claims in the JWT payload without modifying core logic.
  • The modular design supports the addition of new methods or extensions for custom token handling or privilege checks.

Test Plan

Unit Tests

Definition: Unit tests focus on testing individual methods in isolation to ensure they function correctly under various conditions.

Tests for jwt_verify_and_decode

Valid Token Test:

  • Input: A valid JWT token with claims such as id, role, and exp.
  • Expected Output: Decoded payload as a HashWithIndifferentAccess.
  • Validation: Verify that the returned hash matches the expected payload.

Expired Token Test:

  • Input: A token with an exp claim set to a past timestamp.
  • Expected Output: nil with an appropriate error logged.
  • Validation: Confirm that the method gracefully handles expired tokens without crashing.

Invalid Token Test:

  • Input: A tampered JWT token (e.g., signature mismatch).
  • Expected Output: nil.
  • Validation: Ensure an appropriate error message is logged, and no sensitive information is exposed.

Missing Claims Test:

  • Input: A valid token missing required claims like role.
  • Expected Output: nil.
  • Validation: Confirm that the method flags the token as invalid due to incomplete data.

Tests for check_user_privileges

Sufficient Privileges Test:

  • Input: User info with a role claim as Admin and a required_privilege of Student.
  • Expected Output: true.
  • Validation: Confirm that the method correctly evaluates hierarchical roles.

Insufficient Privileges Test:

  • Input: User info with a role claim as Student and a required_privilege of Instructor.
  • Expected Output: false.
  • Validation: Verify that the method denies access when privileges are insufficient.

Missing Role Test:

  • Input: User info with no role claim.
  • Expected Output: false.
  • Validation: Ensure the method handles missing data gracefully.

Invalid Privilege Test:

  • Input: Invalid privilege name not defined in the system (e.g., Super-TA).
  • Expected Output: false.
  • Validation: Confirm that the method denies access for undefined privileges.

Tests for current_user_is_a?

Correct Role Test:

  • Input: Token with role claim as Instructor and role_name as Instructor.
  • Expected Output: true.
  • Validation: Verify that the method returns true when roles match exactly.

Incorrect Role Test:

  • Input: Token with role claim as TA and role_name as Instructor.
  • Expected Output: false.
  • Validation: Ensure the method denies access when roles don’t match.

Missing Token Test:

  • Input: nil token.
  • Expected Output: false.
  • Validation: Confirm that the method handles missing tokens properly.

Tests for user_logged_in?

Valid Token Test:

  • Input: Valid token with all required claims.
  • Expected Output: true.
  • Validation: Verify that the method identifies logged-in users correctly.

Invalid Token Test:

  • Input: Tampered or expired token.
  • Expected Output: false.
  • Validation: Ensure the method flags invalid tokens and denies access.

Missing Token Test:

  • Input: nil token.
  • Expected Output: false.
  • Validation: Confirm that the method handles missing tokens gracefully.

Tests for current_user_can?

Permission Granted Test:

  • Input: Token with id matching a user who has submit permission.
  • Expected Output: true.
  • Validation: Verify that the method allows users with the required permission.

Permission Denied Test:

  • Input: Token with id matching a user without review permission.
  • Expected Output: false.
  • Validation: Ensure that unauthorized users are denied access.

Invalid User Test:

  • Input: Token with id that does not match any user in the system.
  • Expected Output: false.
  • Validation: Confirm that the method denies access to nonexistent users.


  • Integration Tests:
    • Simulate API requests with valid and invalid JWT tokens.
    • Test behavior of endpoints using the updated AuthorizationHelper methods.
  • Edge Cases:
    • Tokens with missing claims.
    • Users with conflicting roles or privileges.

Team

Mentor

  • Kashika Mallick (kmallick@ncsu.edu)

Members

  • Shafa Hassan (shassa22@ncsu.edu)
  • Archit Gupta (agupta85@ncsu.edu)
  • Ansh Ganatra (aganatr@ncsu.edu)