Skip to content

[HCMPRE-2735] Fixed schema migration for encryption service #744

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

holashchand
Copy link
Collaborator

@holashchand holashchand commented May 20, 2025

Summary by CodeRabbit

  • New Features
    • Introduced new database tables to manage symmetric and asymmetric encryption keys for each tenant, ensuring only one active key per tenant is allowed.
  • Chores
    • Updated database migration scripts to support enhanced key management for multi-tenant environments.

Issue & Resolution Summary

To fix flyway migration issue with new breaking change -

Tables - egov_enc_service_schema

  • Remove a row from the above flyway migration table in public schema
  • There should be only 1 row present currently

Steps -

  • Check for the flyway migration history table for egov_enc_service using devops environment variable SCHEMA_TABLE for the service. ie. egov_enc_service_schema
  • Confirm if there is only 1 table row SELECT * FROM public.egov_enc_service_schema
  • Delete the table row DELETE FROM public.egov_enc_service_schema

Why it needs to be done?

  • Currently flyway migration contains hardcoded schema name as public , which is removed to allow migration to run on given database schema not just public schema.
  • This caused change in the existing schema migration script.
  • To resolve this, we need to remove the migration history row (given above).

What if you deploy this in production environment?

  • If deployed earlier (without the fix): Will cause CrashLoopBackOff due to DB migration failure.
  • If deployed fresh: No issue.
  • With this fix applied: Service runs as expected with no side effects on existing data.

Summary by CodeRabbit

  • Documentation
    • Updated the changelog and README to provide guidance on Flyway migration changes, including a manual fix for schema migration issues when upgrading to version 2.10.0.
  • Chores
    • Incremented the service version to 2.10.0-SNAPSHOT.
  • Bug Fixes
    • Resolved Flyway migration issues by removing hardcoded schema references, supporting schema-based deployments.
  • Refactor
    • Replaced the previous encryption key table migration with a new version that improves multi-tenant key management.

Copy link

coderabbitai bot commented May 20, 2025

Walkthrough

A SQL migration script defining tables for symmetric and asymmetric encryption key management was deleted and replaced with a new migration script that recreates these tables with the same schema and constraints. Additionally, a Flyway migration fix was introduced to remove hardcoded references to the public schema, requiring a manual cleanup step during upgrades.

Changes

File(s) Change Summary
core-services/egov-enc-service/src/main/resources/db/migration/main/V20180607185601__eg_enc.sql Deleted SQL migration script that created and managed encryption key tables and their indexes.
core-services/egov-enc-service/src/main/resources/db/migration/main/V20250519185601__eg_enc.sql Added new SQL migration script recreating encryption key tables and unique indexes with the same structure.
core-services/egov-enc-service/CHANGELOG.md Added changelog entry for version 2.10.0 documenting Flyway migration fix removing hardcoded public schema.
core-services/egov-enc-service/README.md Updated README with "Flyway Migration Note" explaining manual fix for schema-based Flyway migration upgrade.
core-services/egov-enc-service/pom.xml Updated project version from 2.9.1-SNAPSHOT to 2.10.0-SNAPSHOT.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Admin as DB Migration Tool
    participant DB as Database

    Admin->>DB: Drop eg_enc_symmetric_keys if exists
    Admin->>DB: Drop eg_enc_asymmetric_keys if exists
    Admin->>DB: Create eg_enc_symmetric_keys table
    Admin->>DB: Create unique index on symmetric key_id
    Admin->>DB: Create partial unique index on tenant_id where active is true
    Admin->>DB: Create eg_enc_asymmetric_keys table
    Admin->>DB: Create unique index on asymmetric key_id
    Admin->>DB: Create partial unique index on tenant_id where active is true

Poem

In the warren where secrets sleep,
New tables for keys, both wide and deep.
Symmetric and asymmetric, all in a row,
With tenants and indexes, ready to go!
One active per burrow, that’s the rule—
Encryption’s safe in this rabbit-run school. 🐇🔑

Now migrations hop with schema free,
No public binds, just harmony! 🎉🐰


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e27c61 and e346023.

📒 Files selected for processing (2)
  • core-services/egov-enc-service/CHANGELOG.md (1 hunks)
  • core-services/egov-enc-service/pom.xml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • core-services/egov-enc-service/CHANGELOG.md
  • core-services/egov-enc-service/pom.xml

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.

@holashchand holashchand changed the title [HCMPRE-2741] Fixed schema migration for encryption service [HCMPRE-2735] Fixed schema migration for encryption service May 20, 2025
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: 0

🧹 Nitpick comments (4)
core-services/egov-enc-service/src/main/resources/db/migration/main/V20250519185601__eg_enc.sql (4)

1-10: Consider strengthening the eg_enc_symmetric_keys table schema
The current DDL is functional but could be enhanced for data integrity and future scalability:

  • Use BIGSERIAL instead of SERIAL for id to avoid integer overflow on large key volumes.
  • Add created_at/updated_at timestamp columns for auditing key lifecycle changes.
  • If you have a tenants table, add a foreign key constraint on tenant_id to enforce referential integrity.

Proposed diff for this segment (please confirm the actual tenants table and PK column name before applying):

--- a/V20250519185601__eg_enc.sql
+++ b/V20250519185601__eg_enc.sql
-CREATE TABLE IF NOT EXISTS eg_enc_symmetric_keys
-(
-  id SERIAL,
-  key_id integer NOT NULL,
-  secret_key text NOT NULL,
-  initial_vector text NOT NULL,
-  active boolean NOT NULL DEFAULT true,
-  tenant_id text NOT NULL,
-  PRIMARY KEY (id)
-);
+CREATE TABLE IF NOT EXISTS eg_enc_symmetric_keys
+(
+  id BIGSERIAL PRIMARY KEY,
+  key_id INTEGER NOT NULL,
+  secret_key TEXT NOT NULL,
+  initial_vector TEXT NOT NULL,
+  active BOOLEAN NOT NULL DEFAULT true,
+  tenant_id TEXT NOT NULL,
+  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+  CONSTRAINT fk_enc_sym_tenant FOREIGN KEY (tenant_id)
+    REFERENCES tenant(tenant_id) ON DELETE CASCADE
+);

Please verify the target table and column for the FK and adjust names accordingly.


12-13: Consider using concurrent index creation for large tables
If these tables already contain a significant number of rows in production, creating unique indexes without CONCURRENTLY will block writes. To minimize downtime, consider:

CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS eg_symmetric_key_id
  ON eg_enc_symmetric_keys (key_id);

CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS active_tenant_symmetric_keys
  ON eg_enc_symmetric_keys (tenant_id)
  WHERE active IS TRUE;

Note: concurrent index creation must run outside of an explicit transaction; confirm your Flyway configuration supports this.


15-24: Apply similar table enhancements to eg_enc_asymmetric_keys
For consistency and auditability, mirror the suggestions above on the asymmetric key table:

  • Switch to BIGSERIAL.
  • Add created_at/updated_at.
  • Enforce a foreign key on tenant_id.

Example diff:

--- a/V20250519185601__eg_enc.sql
+++ b/V20250519185601__eg_enc.sql
-CREATE TABLE IF NOT EXISTS eg_enc_asymmetric_keys
-(
-  id SERIAL,
-  key_id integer NOT NULL,
-  public_key text NOT NULL,
-  private_key text NOT NULL,
-  active boolean NOT NULL DEFAULT true,
-  tenant_id text NOT NULL,
-  PRIMARY KEY (id)
-);
+CREATE TABLE IF NOT EXISTS eg_enc_asymmetric_keys
+(
+  id BIGSERIAL PRIMARY KEY,
+  key_id INTEGER NOT NULL,
+  public_key TEXT NOT NULL,
+  private_key TEXT NOT NULL,
+  active BOOLEAN NOT NULL DEFAULT true,
+  tenant_id TEXT NOT NULL,
+  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+  CONSTRAINT fk_enc_asym_tenant FOREIGN KEY (tenant_id)
+    REFERENCES tenant(tenant_id) ON DELETE CASCADE
+);

26-27: Also use concurrent index creation for asymmetric keys
Apply the same index strategy here to avoid write locks on the eg_enc_asymmetric_keys table:

CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS eg_asymmetric_key_id
  ON eg_enc_asymmetric_keys (key_id);

CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS active_tenant_asymmetric_keys
  ON eg_enc_asymmetric_keys (tenant_id)
  WHERE active IS TRUE;

Ensure your migration runner allows non-transactional scripts when using CONCURRENTLY.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between aa563a9 and 570422f.

📒 Files selected for processing (2)
  • core-services/egov-enc-service/src/main/resources/db/migration/main/V20180607185601__eg_enc.sql (0 hunks)
  • core-services/egov-enc-service/src/main/resources/db/migration/main/V20250519185601__eg_enc.sql (1 hunks)
💤 Files with no reviewable changes (1)
  • core-services/egov-enc-service/src/main/resources/db/migration/main/V20180607185601__eg_enc.sql

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.

2 participants