Skip to content
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

add policies api endpoints #1897

Merged
merged 1 commit into from
Mar 9, 2025
Merged

add policies api endpoints #1897

merged 1 commit into from
Mar 9, 2025

Conversation

motatoes
Copy link
Contributor

@motatoes motatoes commented Mar 8, 2025

Summary by CodeRabbit

  • New Features
    • Added new API endpoints to manage organization policies.
    • Users can now retrieve policy details based on a specified type.
    • Provided functionality to create or update policy information.
    • Enhanced error handling ensures more reliable interactions.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here: app.greptile.com/review/github.

2 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings | Greptile

Copy link
Contributor

coderabbitai bot commented Mar 8, 2025

Walkthrough

The changes introduce a new API group within the backend's bootstrap process, adding endpoints to manage policy data. In the backend/bootstrap/main.go file, a new policyApiGroup is set up with two endpoints: one to retrieve policy details based on a given type and another to upsert (update or insert) policy data. Complementary controller functions in backend/controllers/policies_api.go handle request validations, database interactions, and error responses for these operations.

Changes

File(s) Change Summary
backend/bootstrap/main.go Added a new route group policyApiGroup under the existing API group, including a GET("/:policy_type", controllers.PolicyOrgGetApi) endpoint and a PUT("/", controllers.PolicyOrgUpsertApi) endpoint.
backend/controllers/policies_api.go Introduced PolicyOrgGetApi and PolicyOrgUpsertApi functions to handle policy retrieval and upsert logic. This includes input validation, database lookups, and appropriate error handling.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as Router
    participant PC as PolicyController
    participant DB as Database

    C->>R: GET /policy/{policy_type}
    R->>PC: Invoke PolicyOrgGetApi
    PC->>DB: Query Organization
    DB-->>PC: Return organization details or error
    PC->>DB: Query Policy by type
    DB-->>PC: Return policy details or error
    PC-->>C: Return policy details or error response
Loading
sequenceDiagram
    participant C as Client
    participant R as Router
    participant PC as PolicyController
    participant DB as Database

    C->>R: PUT /policy with JSON {policy_type, text}
    R->>PC: Invoke PolicyOrgUpsertApi
    PC->>DB: Query Organization
    DB-->>PC: Return organization details or error
    PC->>DB: Check for existing policy
    DB-->>PC: Return policy exists status or not found
    alt Policy exists
      PC->>DB: Update policy with new text
    else Policy not found
      PC->>DB: Insert new policy entry
    end
    DB-->>PC: Confirmation or error
    PC-->>C: Return success response or error
Loading

Poem

I hopped through lines of code with glee,
Adding routes like a sassy decree.
GET and PUT now dance in sync,
Policies updated quicker than you think.
A happy rabbit cheers each sprint—oh so spry! 🥕
Code and carrots, together we fly!

✨ 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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Contributor

@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: 1

🧹 Nitpick comments (3)
backend/bootstrap/main.go (1)

235-237: Harmonize route structure for policy endpoints.
While using a GET route that includes policy_type as a URL path parameter is consistent, the PUT route uses the request body for specifying policy_type. Consider adding /:policy_type to the PUT route for a more uniform REST design, unless there is a specific reason for this difference.

- policyApiGroup.PUT("/", controllers.PolicyOrgUpsertApi)
+ policyApiGroup.PUT("/:policy_type", controllers.PolicyOrgUpsertApi)
backend/controllers/policies_api.go (2)

16-19: Centralize policy type validation for reuse.
In PolicyOrgGetApi, the policy type corresponds only to "plan" or "access". This assumption may appear again in PolicyOrgUpsertApi. Consider creating a helper or constants to define valid policy types, ensuring consistent handling.


53-57: Mirror policy type checks to prevent invalid types.
Unlike PolicyOrgGetApi, PolicyOrgUpsertApi does not block invalid policy_type. To maintain consistency, consider validating against the same set of allowed values ("plan" or "access") when upserting.

+ if request.PolicyType != "plan" && request.PolicyType != "access" {
+   c.JSON(http.StatusBadRequest, gin.H{"error": "invalid policy type requested: " + request.PolicyType})
+   return
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84f1c0e and b2adef7.

📒 Files selected for processing (2)
  • backend/bootstrap/main.go (1 hunks)
  • backend/controllers/policies_api.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
🔇 Additional comments (2)
backend/bootstrap/main.go (1)

234-234: Confirm authorization checks for VCS deletion.
The DELETE("/:id", controllers.DeleteVCSConnection) endpoint is newly added and presumably protected by internal and header-based auth. Ensure that only authorized roles or accounts can delete VCS connections to prevent inadvertent resource removal.

Please confirm that appropriate role-based logic is enforced. If necessary, we can create or extend a permission check to ensure only privileged users can trigger this endpoint.

backend/controllers/policies_api.go (1)

36-48: Confirm correctness of joined query for organization-level policies.
You're using JoinedOrganisationRepoProjectQuery() to ensure repos.id IS NULL AND projects.id IS NULL for pure org-level policies. Confirm that the intended logic is to strictly match org-level policies without any associated repo or project. Otherwise, partial matches or unexpected records might slip through.

Do you want a script to search across the codebase for how JoinedOrganisationRepoProjectQuery() is generally used to confirm that it only retrieves purely org-scoped policies?

Comment on lines +90 to +110
if policyResult.RowsAffected == 0 {
err := models.DB.GormDB.Create(&models.Policy{
OrganisationID: org.ID,
Type: policyType,
Policy: policyData,
}).Error

if err != nil {
log.Printf("Error creating policy: %v", err)
c.String(http.StatusInternalServerError, "Error creating policy")
return
}
} else {
policy.Policy = policyData
err := models.DB.GormDB.Save(policy).Error
if err != nil {
log.Printf("Error updating policy: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error updating policy"})
return
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent race conditions or duplicates for upserted policies.
Two parallel requests with different payloads might cause conflicting updates. Ensure there's a unique constraint on (organisation_id, repo_id, project_id, type) or wrap this logic into a transactional approach to avoid inconsistent states.

@motatoes motatoes merged commit be4f65a into develop Mar 9, 2025
12 checks passed
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