Skip to content

feat: extract compute_hash function #928

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

Merged
merged 1 commit into from
May 19, 2025

Conversation

gfyrag
Copy link
Collaborator

@gfyrag gfyrag commented May 19, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner May 19, 2025 10:28
Copy link

coderabbitai bot commented May 19, 2025

Walkthrough

This change adds two PostgreSQL functions: compute_hash, which calculates a SHA-256 hash for a log entry based on its fields and the previous hash, and set_log_hash, a trigger function that sets the computed hash for new log records. Both functions are defined within a schema placeholder.

Changes

File(s) Change Summary
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql Added compute_hash function for SHA-256 hash calculation and set_log_hash trigger function for logs table.

Sequence Diagram(s)

sequenceDiagram
    participant DB as PostgreSQL
    participant Trigger as set_log_hash (trigger)
    participant Func as compute_hash (function)

    Note over Trigger: On new log insertion
    Trigger->>DB: Query previous hash from logs table
    Trigger->>Func: Call compute_hash(previous_hash, new_record)
    Func-->>Trigger: Return computed hash
    Trigger->>DB: Assign new hash to inserted log record
Loading

Possibly related PRs

Suggested reviewers

  • paul-nicolas

Poem

In the schema where hashes now dance,
New functions give logs a fresh chance.
With triggers and bytes,
And hashes so right,
The ledger’s integrity will enhance!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch hotfix/v2.2/compute-hash-fn
  • Post Copyable Unit Tests in Comment

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 generate unit tests to generate unit tests 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.

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.

@gfyrag gfyrag force-pushed the hotfix/v2.2/compute-hash-fn branch from 192f849 to 57cbcd2 Compare May 19, 2025 10:41
Base automatically changed from hotfix/v2.2/fix-memento-format to release/v2.2 May 19, 2025 11:56
@gfyrag gfyrag force-pushed the hotfix/v2.2/compute-hash-fn branch from 57cbcd2 to 62106f4 Compare May 19, 2025 11:57
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: 1

🧹 Nitpick comments (4)
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (4)

1-7: Declare function immutability and use TEXT for JSON
compute_hash is a pure, deterministic function: consider marking it IMMUTABLE so Postgres can optimize calls. Also prefer TEXT over VARCHAR without length for potentially large JSON strings. For example:

 create or replace function compute_hash(previous_hash bytea, r logs)
  returns bytea
- language plpgsql
+ language plpgsql
+ immutable
 as
 $$
-declare
-  marshalledAsJSON varchar;
+declare
+  marshalledAsJSON text;
 begin

19-25: Use convert_to for reliable encoding
Casting text to bytea with ::bytea depends on server encoding and can vary. Replace it with convert_to(..., 'UTF8') for deterministic UTF-8 byte conversion. For example:

-return (select public.digest(
-  case
-    when previous_hash is null
-      then marshalledAsJSON::bytea
-    else '"' || encode(previous_hash, 'base64')::bytea || E'"\n' || marshalledAsJSON::bytea
-  end || E'\n', 'sha256'
-));
+return public.digest(
+  case
+    when previous_hash is null
+      then convert_to(marshalledAsJSON || E'\n', 'UTF8')
+    else convert_to('"' || encode(previous_hash, 'base64') || '"' || E'\n' || marshalledAsJSON || E'\n', 'UTF8')
+  end,
+  'sha256'
+);

27-27: Avoid relying on search_path for schema resolution
SET search_path can be overridden and introduce ambiguity. It’s safer to schema-qualify object names (e.g., {{ .Schema }}.logs) in function bodies so you’re always referencing the intended schema.

Also applies to: 48-48


38-42: Add index for optimized lookup
Every insert queries the latest hash by ledger ordered by seq DESC. On a large logs table, this can lead to full scans. Consider creating a b-tree index on (ledger, seq DESC) or a covering index to speed up this lookup.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fa461c4 and 62106f4.

⛔ Files ignored due to path filters (1)
  • internal/storage/bucket/migrations/35-create-compute-hash-function/notes.yaml is excluded by !**/*.yaml
📒 Files selected for processing (1)
  • internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (3)
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (3)

29-33: Verify trigger attachment and security definer usage
You’ve defined set_log_hash() as a security definer trigger function. Please confirm:

  1. A CREATE TRIGGER ... BEFORE INSERT ON {{ .Schema }}.logs exists in a separate migration to invoke this function.
  2. The function owner and search_path are locked down to prevent privilege escalation.

35-37: Declaring previousHash bytea is straightforward and requires no changes.


44-44: Verify behavior on first record
When there’s no previous log for a ledger, previousHash is NULL and you rely on compute_hash’s branch for NULL. Please confirm this is the intended behavior for the genesis log entry.

Comment on lines +10 to +17
select '{' ||
'"type":"' || r.type || '",' ||
'"data":' || encode(r.memento, 'escape') || ',' ||
'"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
'"idempotencyKey":"' || coalesce(r.idempotency_key, '') || '",' ||
'"id":0,' ||
'"hash":null' ||
'}' into marshalledAsJSON;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use JSONB constructors to build JSON safely
Manual string concatenation can produce invalid or insecure JSON if any field contains quotes, backslashes, or other special characters. Leverage jsonb_build_object (or row_to_json) to serialize the record reliably.

Example refactor:

-declare
-  marshalledAsJSON varchar;
+declare
+  marshalledAsJSON text;
 begin
-  select '{' ||
-         '"type":"' || r.type || '",' ||
-         '"data":' || encode(r.memento, 'escape') || ',' ||
-         '"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
-         '"idempotencyKey":"' || coalesce(r.idempotency_key, '') || '",' ||
-         '"id":0,' ||
-         '"hash":null' ||
-         '}' into marshalledAsJSON;
+  marshalledAsJSON := to_jsonb(
+    jsonb_build_object(
+      'type',             r.type,
+      'data',             encode(r.memento, 'escape'),
+      'date',             to_char(r.date, 'YYYY-MM-DD"T"HH24:MI:SS"Z"'),
+      'idempotencyKey',   coalesce(r.idempotency_key, ''),
+      'id',               0,
+      'hash',             null
+    )
+  )::text;
🤖 Prompt for AI Agents
In internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql
around lines 10 to 17, the JSON string is built using manual string
concatenation, which risks invalid or insecure JSON if fields contain special
characters. Replace the concatenation with a call to jsonb_build_object (or
row_to_json) to construct the JSON object safely and correctly serialize all
fields, ensuring proper escaping and formatting.

@gfyrag gfyrag merged commit da1c21f into release/v2.2 May 19, 2025
8 checks passed
@gfyrag gfyrag deleted the hotfix/v2.2/compute-hash-fn branch May 19, 2025 13:56
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.

3 participants