Skip to content

List contexts in an org#19

Merged
nadilas merged 2 commits intomainfrom
feature/bre-58-add-listing-contexts-to-organization
Jul 20, 2025
Merged

List contexts in an org#19
nadilas merged 2 commits intomainfrom
feature/bre-58-add-listing-contexts-to-organization

Conversation

@nadilas
Copy link
Copy Markdown
Member

@nadilas nadilas commented Jul 20, 2025

We'd love to see more contributions

Read how you can contribute to the project.

Please attach an issue link which your PR solves otherwise your work may be rejected.

Summary by CodeRabbit

  • New Features

    • Added a new API endpoint to retrieve a list of context IDs within an organization.
    • Introduced a new permission for listing contexts.
    • Updated API documentation and OpenAPI schema to include the new endpoint and response format.
  • Documentation

    • Enhanced endpoint descriptions in the API documentation for improved clarity.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 20, 2025

Walkthrough

A new "List Contexts" feature was introduced, enabling the retrieval of all context IDs for an organization via a new API endpoint. This involved backend storage updates, a new permission, protocol buffer changes, OpenAPI documentation, and a new handler method. Logging and permission management were also updated accordingly.

Changes

File(s) Change Summary
apps/api/api/context.go Added ListContexts handler method to serve context listing requests with permission checks.
apps/api/auth/middleware.go Introduced PermissionListContext and updated logging to include user permissions.
apps/api/go.mod Upgraded two buf.build dependencies to newer versions.
apps/api/openapi/assets/openapi.yaml Added GET /v1/context endpoint, new ListContextsResponse schema, and updated schema endpoint description.
apps/api/storage/buntdb/db.go
apps/api/storage/redis/db.go
Added ListContexts method to both BuntDB and Redis storage backends for context ID retrieval.
apps/api/storage/interface.go Declared ListContexts in the Database interface.
apps/api/storage/keys.go Added SplitContextKey function to extract org and context IDs from keys.
proto/brease/context/v1/models.proto Added ListContextsReqeust (typo) and ListContextsResponse messages.
proto/brease/context/v1/service.proto Added ListContexts RPC to ContextService with HTTP GET binding.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Auth
    participant Storage

    Client->>API: GET /v1/context
    API->>Auth: permissionCheck("context.list")
    Auth-->>API: Permission granted/denied
    alt Permission granted
        API->>Storage: ListContexts(orgID)
        Storage-->>API: [contextID1, contextID2, ...]
        API-->>Client: ListContextsResponse(contextIds)
    else Permission denied
        API-->>Client: Error (permission denied)
    end
Loading

Poem

🐰
A hop, a skip, a context list—
Now all IDs are in the gist!
With storage tuned and proto neat,
The API’s new trick’s complete.
Permissions checked, responses bright—
The future’s looking context-right!
—Rabbit

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

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
Copy Markdown
Member Author

nadilas commented Jul 20, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@github-actions
Copy link
Copy Markdown

🤖 API structural change detected:

Added (1)

  • GET /v1/context

Preview documentation

Powered by Bump.sh

@socket-security
Copy link
Copy Markdown

@nadilas nadilas merged commit b02465c into main Jul 20, 2025
10 checks passed
@nadilas nadilas deleted the feature/bre-58-add-listing-contexts-to-organization branch July 20, 2025 14:09
Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bdeeedb and 71c4a79.

⛔ Files ignored due to path filters (1)
  • apps/api/go.sum is excluded by !**/*.sum
📒 Files selected for processing (10)
  • apps/api/api/context.go (1 hunks)
  • apps/api/auth/middleware.go (2 hunks)
  • apps/api/go.mod (1 hunks)
  • apps/api/openapi/assets/openapi.yaml (3 hunks)
  • apps/api/storage/buntdb/db.go (1 hunks)
  • apps/api/storage/interface.go (1 hunks)
  • apps/api/storage/keys.go (1 hunks)
  • apps/api/storage/redis/db.go (1 hunks)
  • proto/brease/context/v1/models.proto (1 hunks)
  • proto/brease/context/v1/service.proto (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/api/storage/redis/db.go (2)
apps/api/storage/buntdb/db.go (1)
  • Container (51-55)
apps/api/storage/keys.go (2)
  • ContextKey (11-13)
  • SplitContextKey (15-18)
apps/api/storage/buntdb/db.go (2)
apps/api/storage/redis/db.go (1)
  • Container (58-62)
apps/api/storage/keys.go (1)
  • ContextKey (11-13)
apps/api/api/context.go (2)
apps/api/api/handler.go (1)
  • BreaseHandler (19-27)
apps/api/auth/middleware.go (1)
  • PermissionListContext (39-39)
🪛 Buf (1.55.1)
proto/brease/context/v1/service.proto

12-12: RPC request type "ListContextsReqeust" should be named "ListContextsRequest" or "ContextServiceListContextsRequest".

(RPC_REQUEST_STANDARD_NAME)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (12)
apps/api/storage/interface.go (1)

21-21: LGTM! Well-designed interface method.

The new ListContexts method follows consistent patterns with other interface methods, properly uses context for cancellation, and has an appropriate signature for returning context IDs scoped to an owner.

apps/api/go.mod (1)

8-10: LGTM! Necessary dependency updates for new protocol buffer definitions.

The version updates for the generated protocol buffer and connectrpc dependencies are appropriate and required to support the new ListContexts RPC method.

proto/brease/context/v1/service.proto (1)

11-16: LGTM! Well-designed RPC with appropriate HTTP binding.

The RPC definition follows good practices with a descriptive comment, appropriate GET method for listing, and clean URL path that fits the REST API design.

proto/brease/context/v1/models.proto (1)

135-137: LGTM: Response message structure is appropriate.

The ListContextsResponse message correctly defines a repeated string field for context IDs.

apps/api/api/context.go (2)

10-14: LGTM: Proper permission checking and error handling.

The permission check using auth.PermissionListContext and error handling are implemented correctly.


17-22: No action required: Context IDs are already sanitized

The Redis ListContexts implementation in apps/api/storage/redis/db.go uses storage.SplitContextKey to strip the "org:123:context:" prefix and return only the raw IDs. Since b.db.ListContexts already returns clean IDs, there’s no risk of leaking internal key formats to API consumers.

apps/api/openapi/assets/openapi.yaml (3)

79-97: LGTM: Well-structured OpenAPI endpoint definition.

The new GET /v1/context endpoint is properly defined with appropriate HTTP method, description, and response schema. The endpoint structure follows existing API patterns.


543-549: LGTM: Correct response schema definition.

The ListContextsResponse schema correctly defines contextIds as an array of strings, matching the protobuf definition and using appropriate JSON naming conventions.


374-374: LGTM: Helpful description addition.

The description "Updates the schema definition of the context" clarifies the purpose of the POST endpoint.

apps/api/auth/middleware.go (3)

39-39: LGTM: Consistent permission naming.

The new PermissionListContext = "context.list" follows the established naming pattern and clearly represents the operation.


43-50: LGTM: Proper integration with permissions system.

The new permission is correctly added to allPermissions slice, maintaining the complete list of available permissions.


260-260: LGTM: Enhanced debug logging.

Adding permissions to the debug log will improve troubleshooting capabilities for authentication issues.

Comment on lines +353 to +365
func (b *Container) ListContexts(ctx context.Context, ownerID string) ([]string, error) {
var contexts []string
err := b.db.View(func(tx *buntdb.Tx) error {
return tx.AscendKeys(storage.ContextKey(ownerID, "*"), func(key, val string) bool {
contexts = append(contexts, key)
return true
})
})
if err != nil {
return nil, err
}
return contexts, nil
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify if full keys or context IDs should be returned.

The implementation correctly queries for contexts using a wildcard pattern, but it returns the full storage keys (e.g., "org:123:context:abc") rather than just the context IDs ("abc").

Based on the ContextKey function from apps/api/storage/keys.go (lines 11-13), keys are formatted as "org:<orgID>:context:<contextID>". The API response expects just the context IDs.


🏁 Script executed:

#!/bin/bash
# Description: Check how context keys are processed in the API layer and Redis implementation
# Expected: Find if keys are parsed to extract context IDs or used as-is

# Search for usage of ListContexts method
rg -A 10 -B 5 "ListContexts.*ctx.*ownerID"

# Check if there's a helper function to extract context ID from full key
rg -A 5 "SplitContextKey\|ParseContextKey\|ExtractContextID"

Length of output: 2803


Extract and return only context IDs in BuntDB’s ListContexts

The Redis implementation in apps/api/storage/redis/db.go uses storage.SplitContextKey to strip the prefix and return only the context IDs. The BuntDB version currently returns full keys (e.g. "org:123:context:abc"), which doesn’t match the API contract.

Please update the BuntDB ListContexts method in apps/api/storage/buntdb/db.go:

  • File: apps/api/storage/buntdb/db.go
  • Method: func (b *Container) ListContexts(...)

Change the AscendKeys callback to split the key and append only the contextID:

-	err := b.db.View(func(tx *buntdb.Tx) error {
-		return tx.AscendKeys(storage.ContextKey(ownerID, "*"), func(key, val string) bool {
-			contexts = append(contexts, key)
-			return true
-		})
-	})
+	err := b.db.View(func(tx *buntdb.Tx) error {
+		return tx.AscendKeys(storage.ContextKey(ownerID, "*"), func(key, val string) bool {
+			_, ctxID := storage.SplitContextKey(key)
+			contexts = append(contexts, ctxID)
+			return true
+		})
+	})

This will align BuntDB’s behavior with the Redis backend and the API’s expected output.

📝 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
func (b *Container) ListContexts(ctx context.Context, ownerID string) ([]string, error) {
var contexts []string
err := b.db.View(func(tx *buntdb.Tx) error {
return tx.AscendKeys(storage.ContextKey(ownerID, "*"), func(key, val string) bool {
contexts = append(contexts, key)
return true
})
})
if err != nil {
return nil, err
}
return contexts, nil
}
func (b *Container) ListContexts(ctx context.Context, ownerID string) ([]string, error) {
var contexts []string
err := b.db.View(func(tx *buntdb.Tx) error {
return tx.AscendKeys(storage.ContextKey(ownerID, "*"), func(key, val string) bool {
_, ctxID := storage.SplitContextKey(key)
contexts = append(contexts, ctxID)
return true
})
})
if err != nil {
return nil, err
}
return contexts, nil
}
🤖 Prompt for AI Agents
In apps/api/storage/buntdb/db.go around lines 353 to 365, the ListContexts
method currently appends full keys to the contexts slice, which includes
prefixes. Modify the AscendKeys callback to use storage.SplitContextKey on each
key and append only the extracted contextID to the contexts slice. This change
will ensure the method returns only context IDs, matching the Redis
implementation and API expectations.

Comment on lines +15 to +18
func SplitContextKey(key string) (orgID, contextID string) {
parts := strings.Split(key, ":")
return parts[2], parts[3]
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds checking to prevent runtime panics.

The function assumes the key has at least 4 colon-separated parts but doesn't validate this, which could cause an index out of bounds panic with malformed keys.

-func SplitContextKey(key string) (orgID, contextID string) {
+func SplitContextKey(key string) (orgID, contextID string, err error) {
 	parts := strings.Split(key, ":")
+	if len(parts) < 4 {
+		return "", "", fmt.Errorf("invalid context key format: %s", key)
+	}
 	return parts[2], parts[3]
 }

Alternatively, if you prefer to keep the current signature and assume valid input, add a comment documenting this assumption and consider adding validation in the calling code.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/api/storage/keys.go around lines 15 to 18, the SplitContextKey function
accesses parts[2] and parts[3] without checking if the split result has enough
elements, risking a runtime panic. Fix this by adding a check on the length of
parts before accessing these indices; if the length is insufficient, return
empty strings or an error as appropriate. Alternatively, document the assumption
that the input key must have at least 4 colon-separated parts and ensure
validation occurs before calling this function.

Comment on lines +372 to +385
func (r *Container) ListContexts(ctx context.Context, ownerID string) ([]string, error) {
ck := storage.ContextKey(ownerID, "*")
list, err := r.db.Keys(ctx, ck).Result()
if err != nil {
return nil, err
}
// slice up key
res := make([]string, len(list))
for i, k := range list {
_, ctxID := storage.SplitContextKey(k)
res[i] = ctxID
}
return res, nil
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address performance and error handling concerns.

This implementation has several issues:

  1. Performance concern: The Redis KEYS command blocks the server and can be slow with large datasets. Consider using SCAN for production environments.

  2. Missing error handling: The SplitContextKey function can panic with malformed keys, but no error handling is present.

Consider this safer implementation:

 func (r *Container) ListContexts(ctx context.Context, ownerID string) ([]string, error) {
 	ck := storage.ContextKey(ownerID, "*")
-	list, err := r.db.Keys(ctx, ck).Result()
+	// Use SCAN instead of KEYS for better performance
+	var list []string
+	iter := r.db.Scan(ctx, 0, ck, 0).Iterator()
+	for iter.Next(ctx) {
+		list = append(list, iter.Val())
+	}
+	if err := iter.Err(); err != nil {
+		return nil, err
+	}
-	if err != nil {
-		return nil, err
-	}
-	// slice up key
 	res := make([]string, len(list))
 	for i, k := range list {
-		_, ctxID := storage.SplitContextKey(k)
+		_, ctxID, err := storage.SplitContextKey(k)
+		if err != nil {
+			r.logger.Warn("Invalid context key format", zap.String("key", k))
+			continue
+		}
 		res[i] = ctxID
 	}
 	return res, nil
 }

Note: This assumes the SplitContextKey function is updated to return an error as suggested in the previous review.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/api/storage/redis/db.go around lines 372 to 385, replace the use of the
Redis KEYS command with the SCAN command to avoid blocking the server on large
datasets. Implement iteration over the SCAN cursor to collect keys matching the
pattern. Additionally, update the code to handle errors returned by the
SplitContextKey function instead of assuming it always succeeds, skipping or
logging malformed keys as appropriate. This will improve performance and
robustness in production environments.

Comment on lines +131 to +133
message ListContextsReqeust {

}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in message name.

The message name ListContextsReqeust has a typo - it should be ListContextsRequest (missing 't' in "Request").

-message ListContextsReqeust {
+message ListContextsRequest {

This typo will propagate through all generated code and needs to be fixed before merging.

📝 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
message ListContextsReqeust {
}
message ListContextsRequest {
}
🤖 Prompt for AI Agents
In proto/brease/context/v1/models.proto around lines 131 to 133, the message
name `ListContextsReqeust` contains a typo and should be corrected to
`ListContextsRequest`. Rename the message to fix the spelling error to prevent
the typo from propagating into all generated code.


service ContextService {
// Returns a list of the contexts within the organization
rpc ListContexts(ListContextsReqeust) returns (ListContextsResponse) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in request message name.

The request message name has a typo: ListContextsReqeust should be ListContextsRequest.

-  rpc ListContexts(ListContextsReqeust) returns (ListContextsResponse) {
+  rpc ListContexts(ListContextsRequest) returns (ListContextsResponse) {

This typo will cause compilation errors and breaks naming conventions.

📝 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
rpc ListContexts(ListContextsReqeust) returns (ListContextsResponse) {
rpc ListContexts(ListContextsRequest) returns (ListContextsResponse) {
🧰 Tools
🪛 Buf (1.55.1)

12-12: RPC request type "ListContextsReqeust" should be named "ListContextsRequest" or "ContextServiceListContextsRequest".

(RPC_REQUEST_STANDARD_NAME)

🤖 Prompt for AI Agents
In proto/brease/context/v1/service.proto at line 12, fix the typo in the RPC
request message name by changing `ListContextsReqeust` to `ListContextsRequest`
to ensure correct compilation and adherence to naming conventions.

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