CSC/ECE 517 Fall 2024 - E2487. Reimplement authorization helper.rb: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
Line 104: Line 104:


== Design Principles ==
== 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:
The redesign of the `AuthorizationHelper` module for JWT-based authentication follows well-established design principles to ensure the solution is secure, maintainable, and scalable. Below are the key principles applied and how they shape this redesign:


1. Single Responsibility Principle (SRP)
1. '''Single Responsibility Principle (SRP)'''
Definition: Each module or class should have one and only one reason to change.
* '''Definition''': Each module or class should have one clear responsibility.
Application:
* '''How It’s Applied''': The `AuthorizationHelper` module focuses only on managing authentication and authorization, separating these concerns into distinct methods. For instance, `jwt_verify_and_decode` handles token verification, while `check_user_privileges` focuses on role-based checks. This keeps the code clean and easier to maintain.
* 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
2. '''Separation of Concerns'''
Definition: Different concerns of a system should be managed in distinct parts of the codebase.
* '''Definition''': Different aspects of the system should be handled independently.
Application:
* '''How It’s Applied''': JWT-related tasks like token creation and decoding are delegated to the `JsonWebToken` class, while privilege checking and user role management remain within `AuthorizationHelper`. This modular approach ensures changes in one area don’t unnecessarily affect the other.
* 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
3. '''Security by Design'''
Definition: Security considerations should be integral to the system's design from the outset.
* '''Definition''': Security should be built into the system from the start, not as an afterthought.
Application:
* '''How It’s Applied''': JWT tokens are validated for expiry and tampering before any actions are authorized. Sensitive data like secret keys is securely stored in environment variables, and communication involving tokens is secured using HTTPS. The system also uses role-based access control (RBAC) to enforce fine-grained permissions.
* 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
4. '''Statelessness'''
Definition: The system should not store client-specific data on the server between requests.
* '''Definition''': The system should not depend on maintaining user-specific data on the server.
Application:
* '''How It’s Applied''': By using JWT, all necessary information about the user is encoded in the token itself. This removes the dependency on server-side session storage, making the system scalable and suitable for distributed architectures.
* 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)
5. '''Testability'''
Definition: Avoid duplication of code by abstracting reusable logic.
* '''Definition''': Code should be designed to make testing straightforward and effective.
Application:
* '''How It’s Applied''': Each method has a single responsibility, making it easier to write focused tests. The modular design allows us to test components like token verification and privilege checking independently, while mock tokens can simulate various scenarios (valid, expired, tampered).
* 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 ==
== Test Plan ==


=== Unit Tests ===
=== Unit Tests ===
'''Definition''': Unit tests focus on testing individual methods in isolation to ensure they function correctly under various conditions.
'''Definition''': Unit tests verify that individual methods work correctly in isolation under different scenarios.


=== Tests for jwt_verify_and_decode ===
==== Tests for jwt_verify_and_decode ====
'''Valid Token Test:'''
'''Valid Token Test:'''
* '''Input''': A valid JWT token with claims such as ''id'', ''role'', and ''exp''.
* '''Input''': A valid JWT token with claims like `id`, `role`, and `exp`.
* '''Expected Output''': Decoded payload as a ''HashWithIndifferentAccess''.
* '''Expected Output''': Decoded payload as a `HashWithIndifferentAccess`.
* '''Validation''': Verify that the returned hash matches the expected payload.
* '''Validation''': Ensure the returned payload matches the expected data.


'''Expired Token Test:'''
'''Expired Token Test:'''
* '''Input''': A token with an ''exp'' claim set to a past timestamp.
* '''Input''': A token with an `exp` claim that has already passed.
* '''Expected Output''': ''nil'' with an appropriate error logged.
* '''Expected Output''': `nil` with an appropriate error logged.
* '''Validation''': Confirm that the method gracefully handles expired tokens without crashing.
* '''Validation''': Confirm that the method gracefully handles expired tokens.


'''Invalid Token Test:'''
'''Invalid Token Test:'''
* '''Input''': A tampered JWT token (e.g., signature mismatch).
* '''Input''': A tampered JWT token with an invalid signature.
* '''Expected Output''': ''nil''.
* '''Expected Output''': `nil`.
* '''Validation''': Ensure an appropriate error message is logged, and no sensitive information is exposed.
* '''Validation''': Ensure an appropriate error message is logged, and sensitive information is not exposed.


'''Missing Claims Test:'''
'''Missing Claims Test:'''
* '''Input''': A valid token missing required claims like ''role''.
* '''Input''': A valid token missing critical claims like `role`.
* '''Expected Output''': ''nil''.
* '''Expected Output''': `nil`.
* '''Validation''': Confirm that the method flags the token as invalid due to incomplete data.
* '''Validation''': Ensure the method flags the token as invalid due to missing data.


=== Tests for check_user_privileges ===
==== Tests for check_user_privileges ====
'''Sufficient Privileges Test:'''
'''Sufficient Privileges Test:'''
* '''Input''': User info with a ''role'' claim as ''Admin'' and a ''required_privilege'' of ''Student''.
* '''Input''': User info with `role` as `Admin` and a `required_privilege` of `Student`.
* '''Expected Output''': ''true''.
* '''Expected Output''': `true`.
* '''Validation''': Confirm that the method correctly evaluates hierarchical roles.
* '''Validation''': Verify the method correctly interprets hierarchical roles.


'''Insufficient Privileges Test:'''
'''Insufficient Privileges Test:'''
* '''Input''': User info with a ''role'' claim as ''Student'' and a ''required_privilege'' of ''Instructor''.
* '''Input''': User info with `role` as `Student` and a `required_privilege` of `Instructor`.
* '''Expected Output''': ''false''.
* '''Expected Output''': `false`.
* '''Validation''': Verify that the method denies access when privileges are insufficient.
* '''Validation''': Ensure the method denies access for insufficient privileges.


'''Missing Role Test:'''
'''Missing Role Test:'''
* '''Input''': User info with no ''role'' claim.
* '''Input''': User info without a `role` claim.
* '''Expected Output''': ''false''.
* '''Expected Output''': `false`.
* '''Validation''': Ensure the method handles missing data gracefully.
* '''Validation''': Ensure the method handles missing roles gracefully.


'''Invalid Privilege Test:'''
==== Tests for current_user_is_a? ====
* '''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:'''
'''Correct Role Test:'''
* '''Input''': Token with ''role'' claim as ''Instructor'' and ''role_name'' as ''Instructor''.
* '''Input''': Token with `role` as `Instructor` and `role_name` as `Instructor`.
* '''Expected Output''': ''true''.
* '''Expected Output''': `true`.
* '''Validation''': Verify that the method returns ''true'' when roles match exactly.
* '''Validation''': Verify the method returns `true` when roles match exactly.


'''Incorrect Role Test:'''
'''Incorrect Role Test:'''
* '''Input''': Token with ''role'' claim as ''TA'' and ''role_name'' as ''Instructor''.
* '''Input''': Token with `role` as `TA` and `role_name` as `Instructor`.
* '''Expected Output''': ''false''.
* '''Expected Output''': `false`.
* '''Validation''': Ensure the method denies access when roles don’t match.
* '''Validation''': Ensure the method denies access when roles don’t match.


'''Missing Token Test:'''
'''Missing Token Test:'''
* '''Input''': ''nil'' token.
* '''Input''': `nil` token.
* '''Expected Output''': ''false''.
* '''Expected Output''': `false`.
* '''Validation''': Confirm that the method handles missing tokens properly.
* '''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 ===
=== Integration Tests ===
'''Definition''': Integration tests validate the end-to-end behavior of the system, ensuring that the `AuthorizationHelper` module interacts correctly with other components.
'''Definition''': Integration tests validate that the `AuthorizationHelper` module functions correctly within the context of the overall system.
 
=== Approach Options ===
There are two main approaches available for testing the integration of `AuthorizationHelper`:


1. Creating a Dummy API:
==== Approach Options ====
* This involves setting up a lightweight API endpoint specifically for testing purposes.
1. '''Creating a Dummy API''':
* The dummy API would use the authentication and authorization helpers to validate tokens and determine user privileges.
* A lightweight API will be created specifically for testing the `AuthorizationHelper` methods.
* This option provides full control over the test scenarios without interfering with the existing system.
* This API will simulate requests requiring token authentication and privilege checks.
* '''Advantages''':
* '''Advantages''':
** Isolated and clean testing environment.
** Fully isolated testing environment.
** Allows for simulation of various roles and scenarios without impacting real application logic.
** Flexibility to simulate different roles, tokens, and scenarios.
* '''Disadvantages''':
* '''Disadvantages''':
** May not fully capture integration with the actual application workflow.
** Requires additional setup and may not reflect real-world behavior perfectly.
** Additional setup required to mimic real-world interactions.


2. Implementing a New Controller in the Old Expertiza:
2. '''Implementing a New Controller in Expertiza''':
* A new controller is created in the existing Expertiza application, leveraging the redesigned `AuthorizationHelper` methods.
* A controller will be added to the existing Expertiza application that uses the refactored `AuthorizationHelper`.
* This approach ensures that the integration tests occur in the real application context, using actual routes and controllers.
* This ensures that tests occur in a real-world context, validating interactions with the actual system.
* '''Advantages''':
* '''Advantages''':
** Captures real-world behavior and potential side effects.
** Validates the actual behavior of the module within the system.
** Easier to validate that the refactored module functions seamlessly with the existing system.
** Reflects real application workflows and edge cases.
* ''Disadvantages''':
* '''Disadvantages''':
** Potentially impacts other parts of the application during testing.
** Potentially affects other parts of the application during testing.
** Requires more effort to ensure test isolation and rollback.
** Requires effort to ensure test isolation.
 
For both approaches, robust testing frameworks (e.g., RSpec) will be used to simulate requests and validate the behavior of endpoints utilizing the `AuthorizationHelper` methods.
 
---
 
=== Integration Test Cases ===


==== **API Endpoint Authentication** ====
==== Integration Test Cases ====
'''Valid Token Test:'''
'''API Endpoint Authentication'''
* '''Scenario''': A valid JWT token is sent to a protected endpoint.
* '''Valid Token Test''':
* '''Expected Outcome''': The request is authenticated, and the user is granted access.
** '''Scenario''': Send a valid JWT token to a protected endpoint.
* '''Validation''': Verify the response status is HTTP 200 OK and the user receives the requested resource.
** '''Expected Outcome''': HTTP 200 OK with access granted.
** '''Validation''': Confirm the user is authenticated and receives the correct resource.


'''Expired Token Test:'''
* '''Expired Token Test''':
* '''Scenario''': An expired JWT token is sent to a protected endpoint.
** '''Scenario''': Send an expired JWT token to a protected endpoint.
* '''Expected Outcome''': The request is denied with an HTTP 401 Unauthorized response.
** '''Expected Outcome''': HTTP 401 Unauthorized.
* '''Validation''': Confirm that the system blocks access and includes an appropriate error message in the response.
** '''Validation''': Ensure the system blocks access and provides a proper error message.


'''Tampered Token Test:'''
* '''Tampered Token Test''':
* '''Scenario''': A JWT token with a modified signature is sent to a protected endpoint.
** '''Scenario''': Send a tampered token with an invalid signature.
* '''Expected Outcome''': The request is denied with an HTTP 401 Unauthorized response.
** '''Expected Outcome''': HTTP 401 Unauthorized.
* '''Validation''': Ensure no sensitive information is exposed and the invalid token is logged for auditing.
** '''Validation''': Confirm the system denies access and logs the attempt securely.


'''Missing Token Test:'''
* '''Missing Token Test''':
* '''Scenario''': No token is provided with the request to a protected endpoint.
** '''Scenario''': Make a request without providing a token.
* '''Expected Outcome''': The request is denied with an HTTP 401 Unauthorized response.
** '''Expected Outcome''': HTTP 401 Unauthorized.
* '''Validation''': Verify that token-based authentication is enforced, and the response includes an appropriate error message.
** '''Validation''': Verify that token authentication is strictly enforced.


== Team ==
== Team ==

Revision as of 00:48, 13 November 2024

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 follows well-established design principles to ensure the solution is secure, maintainable, and scalable. Below are the key principles applied and how they shape this redesign:

1. Single Responsibility Principle (SRP)

  • Definition: Each module or class should have one clear responsibility.
  • How It’s Applied: The `AuthorizationHelper` module focuses only on managing authentication and authorization, separating these concerns into distinct methods. For instance, `jwt_verify_and_decode` handles token verification, while `check_user_privileges` focuses on role-based checks. This keeps the code clean and easier to maintain.

2. Separation of Concerns

  • Definition: Different aspects of the system should be handled independently.
  • How It’s Applied: JWT-related tasks like token creation and decoding are delegated to the `JsonWebToken` class, while privilege checking and user role management remain within `AuthorizationHelper`. This modular approach ensures changes in one area don’t unnecessarily affect the other.

3. Security by Design

  • Definition: Security should be built into the system from the start, not as an afterthought.
  • How It’s Applied: JWT tokens are validated for expiry and tampering before any actions are authorized. Sensitive data like secret keys is securely stored in environment variables, and communication involving tokens is secured using HTTPS. The system also uses role-based access control (RBAC) to enforce fine-grained permissions.

4. Statelessness

  • Definition: The system should not depend on maintaining user-specific data on the server.
  • How It’s Applied: By using JWT, all necessary information about the user is encoded in the token itself. This removes the dependency on server-side session storage, making the system scalable and suitable for distributed architectures.

5. Testability

  • Definition: Code should be designed to make testing straightforward and effective.
  • How It’s Applied: Each method has a single responsibility, making it easier to write focused tests. The modular design allows us to test components like token verification and privilege checking independently, while mock tokens can simulate various scenarios (valid, expired, tampered).

---

Test Plan

Unit Tests

Definition: Unit tests verify that individual methods work correctly in isolation under different scenarios.

Tests for jwt_verify_and_decode

Valid Token Test:

  • Input: A valid JWT token with claims like `id`, `role`, and `exp`.
  • Expected Output: Decoded payload as a `HashWithIndifferentAccess`.
  • Validation: Ensure the returned payload matches the expected data.

Expired Token Test:

  • Input: A token with an `exp` claim that has already passed.
  • Expected Output: `nil` with an appropriate error logged.
  • Validation: Confirm that the method gracefully handles expired tokens.

Invalid Token Test:

  • Input: A tampered JWT token with an invalid signature.
  • Expected Output: `nil`.
  • Validation: Ensure an appropriate error message is logged, and sensitive information is not exposed.

Missing Claims Test:

  • Input: A valid token missing critical claims like `role`.
  • Expected Output: `nil`.
  • Validation: Ensure the method flags the token as invalid due to missing data.

Tests for check_user_privileges

Sufficient Privileges Test:

  • Input: User info with `role` as `Admin` and a `required_privilege` of `Student`.
  • Expected Output: `true`.
  • Validation: Verify the method correctly interprets hierarchical roles.

Insufficient Privileges Test:

  • Input: User info with `role` as `Student` and a `required_privilege` of `Instructor`.
  • Expected Output: `false`.
  • Validation: Ensure the method denies access for insufficient privileges.

Missing Role Test:

  • Input: User info without a `role` claim.
  • Expected Output: `false`.
  • Validation: Ensure the method handles missing roles gracefully.

Tests for current_user_is_a?

Correct Role Test:

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

Incorrect Role Test:

  • Input: Token with `role` 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.

---

Integration Tests

Definition: Integration tests validate that the `AuthorizationHelper` module functions correctly within the context of the overall system.

Approach Options

1. Creating a Dummy API:

  • A lightweight API will be created specifically for testing the `AuthorizationHelper` methods.
  • This API will simulate requests requiring token authentication and privilege checks.
  • Advantages:
    • Fully isolated testing environment.
    • Flexibility to simulate different roles, tokens, and scenarios.
  • Disadvantages:
    • Requires additional setup and may not reflect real-world behavior perfectly.

2. Implementing a New Controller in Expertiza:

  • A controller will be added to the existing Expertiza application that uses the refactored `AuthorizationHelper`.
  • This ensures that tests occur in a real-world context, validating interactions with the actual system.
  • Advantages:
    • Validates the actual behavior of the module within the system.
    • Reflects real application workflows and edge cases.
  • Disadvantages:
    • Potentially affects other parts of the application during testing.
    • Requires effort to ensure test isolation.

Integration Test Cases

API Endpoint Authentication

  • Valid Token Test:
    • Scenario: Send a valid JWT token to a protected endpoint.
    • Expected Outcome: HTTP 200 OK with access granted.
    • Validation: Confirm the user is authenticated and receives the correct resource.
  • Expired Token Test:
    • Scenario: Send an expired JWT token to a protected endpoint.
    • Expected Outcome: HTTP 401 Unauthorized.
    • Validation: Ensure the system blocks access and provides a proper error message.
  • Tampered Token Test:
    • Scenario: Send a tampered token with an invalid signature.
    • Expected Outcome: HTTP 401 Unauthorized.
    • Validation: Confirm the system denies access and logs the attempt securely.
  • Missing Token Test:
    • Scenario: Make a request without providing a token.
    • Expected Outcome: HTTP 401 Unauthorized.
    • Validation: Verify that token authentication is strictly enforced.

Team

Mentor

  • Kashika Mallick (kmallick@ncsu.edu)

Members

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