Skip to content

Created at test #3460

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

Conversation

nnadidan360
Copy link

@nnadidan360 nnadidan360 commented Apr 26, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling and access control for viewing fund creation dates, ensuring only authorized users can access this information.
  • Tests
    • Added comprehensive tests to verify authentication, authorization, and error handling for fund creation date access.

Copy link

coderabbitai bot commented Apr 26, 2025

Walkthrough

The changes extract the resolver logic for the createdAt field of the Fund GraphQL type into a standalone asynchronous function, createdAtResolver, which enforces authentication and role-based authorization. The complexity value for the resolver is also extracted as a constant. A comprehensive test suite is added to validate the resolver’s access control, error handling, and correct data retrieval. Additionally, a minor update is made to the environment variable schema in the GraphQL utilities, duplicating a key in the list of picked environment variables.

Changes

File(s) Change Summary
src/graphql/types/Fund/createdAt.ts Extracted the createdAt field resolver into an exported async function createdAtResolver with explicit authentication and authorization checks. Exported a complexity constant. Updated the field implementation to use these.
test/graphql/types/Fund/createdAt.test.ts Added a comprehensive test suite for createdAtResolver, covering schema validation, authentication/authorization, error handling, and concurrent access scenarios.
src/utilities/graphqLimits.ts Duplicated the "API_GRAPHQL_SCALAR_RESOLVER_FIELD_COST" key in the list of environment variables picked for validation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GraphQLServer
    participant createdAtResolver
    participant Database

    Client->>GraphQLServer: Query Fund.createdAt
    GraphQLServer->>createdAtResolver: Call with Fund, args, ctx
    createdAtResolver->>createdAtResolver: Check authentication
    alt Not authenticated
        createdAtResolver-->>GraphQLServer: Throw "unauthenticated" error
        GraphQLServer-->>Client: Error response
    else Authenticated
        createdAtResolver->>Database: Fetch user and membership roles
        alt User not found
            createdAtResolver-->>GraphQLServer: Throw "unauthenticated" error
            GraphQLServer-->>Client: Error response
        else Not admin
            createdAtResolver-->>GraphQLServer: Throw "unauthorized_action" error
            GraphQLServer-->>Client: Error response
        else Authorized
            createdAtResolver-->>GraphQLServer: Return createdAt date
            GraphQLServer-->>Client: createdAt date
        end
    end
Loading

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes
  • disha1202
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 docstrings to generate docstrings for this 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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33d5b7b and 6e19598.

📒 Files selected for processing (3)
  • src/graphql/types/Fund/createdAt.ts (1 hunks)
  • src/utilities/graphqLimits.ts (1 hunks)
  • test/graphql/types/Fund/createdAt.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/graphql/types/Fund/createdAt.ts (2)
src/graphql/context.ts (1)
  • GraphQLContext (55-55)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (8)
src/graphql/types/Fund/createdAt.ts (2)

7-8: LGTM! Great use of environment configuration for complexity.

The extraction of the complexity value as a named constant improves code readability and maintainability.


66-72: LGTM! Effective use of extracted components.

The implementation nicely leverages the extracted resolver function and complexity constant, making the code more maintainable and easier to test independently.

test/graphql/types/Fund/createdAt.test.ts (6)

1-50: Well-structured test setup with comprehensive mocking.

The test file has a clear organization with proper mocking of the GraphQL context and fund object. Good use of TypeScript types for mock data and proper isolation of tests using beforeEach.


51-65: Good test coverage for schema complexity validation.

This test ensures that the complexity value is correctly applied in the GraphQL schema, which is important for preventing abuse through overly complex queries.


67-137: Excellent authentication and authorization test coverage.

Comprehensive tests covering all access control scenarios:

  • Unauthenticated users
  • Non-admin users without organization membership
  • Non-admin users with member-level organization membership
  • System administrators
  • Organization administrators

This ensures the resolver properly enforces the security boundaries.


139-155: LGTM! Proper verification of data retrieval.

The test confirms that the resolver correctly returns the fund's createdAt value when accessed by authorized users.


157-185: Thorough error handling test coverage.

Good tests for different types of database errors, ensuring they're properly caught, logged, and converted to appropriate GraphQL errors.


187-255: Excellent concurrent access testing.

The tests thoroughly validate the database query filters for both user ID and organization ID, ensuring that the resolver uses the correct filters even under concurrent access scenarios. Also includes proper error handling tests for database failures during concurrent access.

@@ -9,6 +9,7 @@ const schema = Type.Pick(envConfigSchema, [
"API_GRAPHQL_LIST_FIELD_COST",
"API_GRAPHQL_NON_PAGINATED_LIST_FIELD_COST",
"API_GRAPHQL_MUTATION_BASE_COST",
"API_GRAPHQL_SCALAR_RESOLVER_FIELD_COST",
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove duplicate environment variable key.

The environment variable key "API_GRAPHQL_SCALAR_RESOLVER_FIELD_COST" is already included at line 7, making this entry redundant. Duplicating keys in the schema can lead to confusion and potential maintenance issues.

- "API_GRAPHQL_SCALAR_RESOLVER_FIELD_COST",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"API_GRAPHQL_SCALAR_RESOLVER_FIELD_COST",

Comment on lines +10 to +64
export const createdAtResolver = async (
parent: FundType,
_args: Record<string, never>,
ctx: GraphQLContext,
) => {
if (!ctx.currentClient.isAuthenticated) {
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}

const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
columns: {
role: true,
},
with: {
organizationMembershipsWhereMember: {
columns: {
role: true,
},
where: (fields, operators) =>
operators.eq(fields.organizationId, parent.organizationId),
},
},
where: (fields, operators) => operators.eq(fields.id, currentUserId),
});
try {
const currentUserId = ctx.currentClient.user.id;

if (currentUser === undefined) {
throw new TalawaGraphQLError({
extensions: {
code: "unauthenticated",
},
});
}
const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
columns: { role: true },
with: {
organizationMembershipsWhereMember: {
columns: { role: true },
where: (fields, operators) =>
operators.eq(fields.organizationId, parent.organizationId),
},
},
where: (fields, operators) => operators.eq(fields.id, currentUserId),
});

const currentUserOrganizationMembership =
currentUser.organizationMembershipsWhereMember[0];
if (currentUser === undefined) {
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}

if (
currentUser.role !== "administrator" &&
(currentUserOrganizationMembership === undefined ||
currentUserOrganizationMembership.role !== "administrator")
) {
throw new TalawaGraphQLError({
extensions: {
code: "unauthorized_action",
},
});
}
const currentUserOrganizationMembership =
currentUser.organizationMembershipsWhereMember[0];

return parent.createdAt;
},
if (
currentUser.role !== "administrator" &&
(!currentUserOrganizationMembership ||
currentUserOrganizationMembership.role !== "administrator")
) {
throw new TalawaGraphQLError({
extensions: { code: "unauthorized_action" },
});
}

return parent.createdAt;
} catch (error) {
ctx.log.error("An unexpected error occurred in createdAtResolver", {
error,
});
throw new TalawaGraphQLError({
extensions: { code: "unexpected" },
});
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Excellent implementation of the resolver function with proper access control.

The resolver logic has been nicely extracted into a standalone function with comprehensive authentication and authorization checks. The error handling is robust, using try-catch to capture unexpected errors.

However, there appears to be some redundancy in the authentication checks:

  1. First check at lines 15-19
  2. Second check at lines 36-40 after fetching the user

Consider consolidating these checks for cleaner code flow.

export const createdAtResolver = async (
	parent: FundType,
	_args: Record<string, never>,
	ctx: GraphQLContext,
) => {
	if (!ctx.currentClient.isAuthenticated) {
		throw new TalawaGraphQLError({
			extensions: { code: "unauthenticated" },
		});
	}

	try {
		const currentUserId = ctx.currentClient.user.id;

		const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
			columns: { role: true },
			with: {
				organizationMembershipsWhereMember: {
					columns: { role: true },
					where: (fields, operators) =>
						operators.eq(fields.organizationId, parent.organizationId),
				},
			},
			where: (fields, operators) => operators.eq(fields.id, currentUserId),
		});

-		if (currentUser === undefined) {
-			throw new TalawaGraphQLError({
-				extensions: { code: "unauthenticated" },
-			});
-		}
+		if (currentUser === undefined) {
+			ctx.log.warn(`User ${currentUserId} not found in database despite being authenticated`);
+			throw new TalawaGraphQLError({
+				extensions: { code: "unauthenticated" },
+			});
+		}

		const currentUserOrganizationMembership =
			currentUser.organizationMembershipsWhereMember[0];

		if (
			currentUser.role !== "administrator" &&
			(!currentUserOrganizationMembership ||
				currentUserOrganizationMembership.role !== "administrator")
		) {
			throw new TalawaGraphQLError({
				extensions: { code: "unauthorized_action" },
			});
		}

		return parent.createdAt;
	} catch (error) {
-		ctx.log.error("An unexpected error occurred in createdAtResolver", {
+		ctx.log.error(`An unexpected error occurred in createdAtResolver for fund ${parent.id}`, {
			error,
		});
		throw new TalawaGraphQLError({
			extensions: { code: "unexpected" },
		});
	}
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const createdAtResolver = async (
parent: FundType,
_args: Record<string, never>,
ctx: GraphQLContext,
) => {
if (!ctx.currentClient.isAuthenticated) {
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}
const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
columns: {
role: true,
},
with: {
organizationMembershipsWhereMember: {
columns: {
role: true,
},
where: (fields, operators) =>
operators.eq(fields.organizationId, parent.organizationId),
},
},
where: (fields, operators) => operators.eq(fields.id, currentUserId),
});
try {
const currentUserId = ctx.currentClient.user.id;
if (currentUser === undefined) {
throw new TalawaGraphQLError({
extensions: {
code: "unauthenticated",
},
});
}
const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
columns: { role: true },
with: {
organizationMembershipsWhereMember: {
columns: { role: true },
where: (fields, operators) =>
operators.eq(fields.organizationId, parent.organizationId),
},
},
where: (fields, operators) => operators.eq(fields.id, currentUserId),
});
const currentUserOrganizationMembership =
currentUser.organizationMembershipsWhereMember[0];
if (currentUser === undefined) {
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}
if (
currentUser.role !== "administrator" &&
(currentUserOrganizationMembership === undefined ||
currentUserOrganizationMembership.role !== "administrator")
) {
throw new TalawaGraphQLError({
extensions: {
code: "unauthorized_action",
},
});
}
const currentUserOrganizationMembership =
currentUser.organizationMembershipsWhereMember[0];
return parent.createdAt;
},
if (
currentUser.role !== "administrator" &&
(!currentUserOrganizationMembership ||
currentUserOrganizationMembership.role !== "administrator")
) {
throw new TalawaGraphQLError({
extensions: { code: "unauthorized_action" },
});
}
return parent.createdAt;
} catch (error) {
ctx.log.error("An unexpected error occurred in createdAtResolver", {
error,
});
throw new TalawaGraphQLError({
extensions: { code: "unexpected" },
});
}
};
export const createdAtResolver = async (
parent: FundType,
_args: Record<string, never>,
ctx: GraphQLContext,
) => {
if (!ctx.currentClient.isAuthenticated) {
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}
try {
const currentUserId = ctx.currentClient.user.id;
const currentUser = await ctx.drizzleClient.query.usersTable.findFirst({
columns: { role: true },
with: {
organizationMembershipsWhereMember: {
columns: { role: true },
where: (fields, operators) =>
operators.eq(fields.organizationId, parent.organizationId),
},
},
where: (fields, operators) => operators.eq(fields.id, currentUserId),
});
if (currentUser === undefined) {
ctx.log.warn(`User ${currentUserId} not found in database despite being authenticated`);
throw new TalawaGraphQLError({
extensions: { code: "unauthenticated" },
});
}
const currentUserOrganizationMembership =
currentUser.organizationMembershipsWhereMember[0];
if (
currentUser.role !== "administrator" &&
(!currentUserOrganizationMembership ||
currentUserOrganizationMembership.role !== "administrator")
) {
throw new TalawaGraphQLError({
extensions: { code: "unauthorized_action" },
});
}
return parent.createdAt;
} catch (error) {
ctx.log.error(
`An unexpected error occurred in createdAtResolver for fund ${parent.id}`,
{ error }
);
throw new TalawaGraphQLError({
extensions: { code: "unexpected" },
});
}
};

@nnadidan360 nnadidan360 deleted the createdAtTest branch April 26, 2025 17:47
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