Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Aug 18, 2025

Part of ENG-200

Issues:

Dependencies

Description

  • Gotta set gateways to [] for the initiator-only flow to work

Testing

  • Local
    • Create/get/update a test initiator-only org on CW cert runner

Release Plan

  • Merge this

Summary by CodeRabbit

  • Refactor

    • Simplified initiator-only organization flow: create, fetch by returned ID, then update in a single path.
    • Removed dependency on pre-known organization IDs.
  • Bug Fixes

    • More consistent handling of security token key type and authorization information to avoid null-related issues.
    • Standardized payload defaults (e.g., empty gateways list).
  • Chores

    • Improved logs with clearer transaction and organization IDs.
  • New Features

    • Organization data models now accept a broader set of token key types and include gateways where applicable.

Part of ENG-200

Signed-off-by: RamilGaripov <ramil@metriport.com>
Copy link

linear bot commented Aug 18, 2025

Copy link

coderabbitai bot commented Aug 18, 2025

Walkthrough

Refactors initiator-only org flow to create an org, fetch it by returned ID, and perform a single update, with streamlined logging and error handling. Adjusts Organization model schemas: broadens securityTokenKeyType to string/nullish and includes securityTokenKeyType and gateways in OrganizationWithoutNetworkInfo.

Changes

Cohort / File(s) Summary of changes
Runner flow refactor
packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts
Removed dependency on existing OID; create → get-by-ID → single update flow; payload tweaks (gateways [] , securityTokenKeyType "", delete authorizationInformation); simplified logs; removed legacy multi-path updates and verbose error capture.
SDK organization schema updates
packages/commonwell-sdk/src/models/organization.ts
securityTokenKeyType widened to z.string().nullish(); organizationSchemaWithoutNetworkInfo now omits only networks and authorizationInformation; OrganizationWithoutNetworkInfo now includes securityTokenKeyType and gateways.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Flow as InitiatorOnlyOrgFlow
  participant OrgAPI as Org Service

  User->>Flow: Start initiator-only org flow
  Flow->>OrgAPI: createOrg(payload: gateways=[], securityTokenKeyType="")
  OrgAPI-->>Flow: organizationId
  Flow->>OrgAPI: getOneOrg(organizationId)
  OrgAPI-->>Flow: organization
  Note over Flow: Prepare update: ensure securityTokenKeyType=""<br/>delete authorizationInformation
  Flow->>OrgAPI: updateOrg(organization)
  OrgAPI-->>Flow: update result
  Flow-->>User: Log success or errors
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch eng-200-cert-runner-init-only-fix

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@RamilGaripov RamilGaripov changed the title fix(commonwell-cert-runner): minor fixes for initiator only org test ENG-200: minor fixes for initiator only org test Aug 18, 2025
Part of ENG-200

Signed-off-by: RamilGaripov <ramil@metriport.com>
@RamilGaripov RamilGaripov changed the title ENG-200: minor fixes for initiator only org test ENG-200: cw cert runner fixes Aug 20, 2025
@RamilGaripov RamilGaripov changed the base branch from eng-200-cert-runner-updated to develop August 20, 2025 17:42
@RamilGaripov RamilGaripov changed the base branch from develop to eng-200-cert-runner-updated August 20, 2025 17:43
@RamilGaripov RamilGaripov mentioned this pull request Aug 20, 2025
1 task
@RamilGaripov RamilGaripov marked this pull request as ready for review August 20, 2025 17:58
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)
packages/commonwell-sdk/src/models/organization.ts (1)

60-60: Constrain securityTokenKeyType and normalize empty-string inputs

Broadening to z.string().nullish() weakens validation and allows arbitrary/empty values. If the CW API occasionally sends/accepts empty strings, preprocess them to undefined and keep a constrained enum otherwise. This preserves schema safety while still supporting the runner’s current behavior.

Apply this diff:

-  securityTokenKeyType: z.string().nullish(),
+  securityTokenKeyType: z.preprocess(
+    val => (val === "" ? undefined : val),
+    z.union([
+      z.literal("JWT"),
+      z.literal("BEARER"),
+      z.literal("HOLDER-OF-KEY"),
+    ]).optional()
+  ),
packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts (3)

30-33: Prefer omitting fields over sending empty/sentinel values

  • gateways: setting to [] is fine if CW accepts an empty list; otherwise prefer leaving it undefined.
  • securityTokenKeyType: sending an empty string is a weak sentinel. Prefer omitting the field instead.

This reduces payload ambiguity and aligns better with API semantics.

Apply this diff:

-    initiatorOnlyOrgCreate.gateways = [];
-    initiatorOnlyOrgCreate.securityTokenKeyType = "";
-    delete initiatorOnlyOrgCreate.authorizationInformation;
+    initiatorOnlyOrgCreate.gateways = [];
+    delete initiatorOnlyOrgCreate.securityTokenKeyType;
+    delete initiatorOnlyOrgCreate.authorizationInformation;

Please confirm whether CommonWell requires the property to be present (even if empty). If so, we can keep the property but normalize empty strings to undefined at the schema layer (see suggested preprocess in the SDK).


40-43: Nit: add a space after the colon; also consider redacting secrets in logs

  • Minor formatting: add a space after "Transaction ID:" for consistency.
  • Response logs may include authorizationInformation.clientSecret. Consider redacting before logging to avoid accidental secret exposure even in tooling.

Apply this diff for spacing:

-    console.log(">>> Transaction ID:" + commonWellMember.lastTransactionId);
+    console.log(">>> Transaction ID: " + commonWellMember.lastTransactionId);

Optionally, add a small helper to sanitize logs (example):

function safeStringifyOrg(org: unknown): string {
  try {
    const clone = JSON.parse(JSON.stringify(org));
    if (clone && typeof clone === "object" && "authorizationInformation" in clone) {
      // @ts-expect-error runtime guard
      const ai = clone.authorizationInformation;
      if (ai && typeof ai === "object" && "clientSecret" in ai) {
        ai.clientSecret = "***redacted***";
      }
    }
    return JSON.stringify(clone, null, 2);
  } catch {
    return String(org);
  }
}

Then use:

  • console.log(">>> Response: " + safeStringifyOrg(respCreateInitiatorOnly));
  • console.log(">>> Response: " + safeStringifyOrg(respGetInitiatorOnly));
  • console.log(">>> Response: " + safeStringifyOrg(respUpdateInitiatorOnly));

51-53: Avoid empty-string sentinels and prefer truthy checks over in

  • Prefer omitting securityTokenKeyType rather than setting it to an empty string.
  • Align with our guideline to use truthy syntax instead of in.

Apply this diff:

-    initiatorOnlyOrg.securityTokenKeyType = "";
-    if ("authorizationInformation" in initiatorOnlyOrg) {
-      delete initiatorOnlyOrg.authorizationInformation;
-    }
+    delete initiatorOnlyOrg.securityTokenKeyType;
+    if (initiatorOnlyOrg.authorizationInformation) {
+      delete initiatorOnlyOrg.authorizationInformation;
+    }
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cccad59 and 2ef4e9a.

📒 Files selected for processing (2)
  • packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts (2 hunks)
  • packages/commonwell-sdk/src/models/organization.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursorrules)

**/*.{js,jsx,ts,tsx}: Don’t use null inside the app, only on code interacting with external interfaces/services, like DB and HTTP; convert to undefined before sending inwards into the code
Use const whenever possible
Use async/await instead of .then()
Naming: classes, enums: PascalCase
Naming: constants, variables, functions: camelCase
Naming: file names: kebab-case
Naming: Don’t use negative names, like notEnabled, prefer isDisabled
If possible, use decomposing objects for function parameters
Prefer Nullish Coalesce (??) than the OR operator (||) when you want to provide a default value
Avoid creating arrow functions
Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
While handling errors, keep the stack trace around: if you create a new Error (e.g., MetriportError), make sure to pass the original error as the new one’s cause so the stack trace is available upstream.
max column length is 100 chars
multi-line comments use /** */
top-level comments go after the import (save pre-import to basic file header, like license)
move literals to constants declared after imports when possible

Files:

  • packages/commonwell-sdk/src/models/organization.ts
  • packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursorrules)

Use types whenever possible

Files:

  • packages/commonwell-sdk/src/models/organization.ts
  • packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts
**/*.ts

⚙️ CodeRabbit Configuration File

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • U...

Files:

  • packages/commonwell-sdk/src/models/organization.ts
  • packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: RamilGaripov
PR: metriport/metriport#4176
File: packages/fhir-converter/src/lib/handlebars-converter/handlebars-helpers.js:296-320
Timestamp: 2025-07-17T21:24:37.077Z
Learning: RamilGaripov prefers to maintain consistency with existing patterns in a file rather than making isolated fixes to coding guideline violations like var vs const declarations, when the pattern is already established throughout the codebase.
📚 Learning: 2025-07-16T19:02:26.395Z
Learnt from: leite08
PR: metriport/metriport#4095
File: packages/commonwell-cert-runner/src/flows/org-management.ts:79-85
Timestamp: 2025-07-16T19:02:26.395Z
Learning: In packages/commonwell-cert-runner/src/flows/org-management.ts, the silent error handling in the certificate retrieval catch block is intentional to allow the certification flow to continue processing even when certificate operations fail, as this is a testing tool rather than production code.

Applied to files:

  • packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts
🔇 Additional comments (4)
packages/commonwell-sdk/src/models/organization.ts (1)

60-60: Verify downstream assumptions after broadening securityTokenKeyType and adding gateways

Please manually confirm that no downstream code breaks due to:

• Call sites comparing securityTokenKeyType against specific literals (e.g. "JWT", "BEARER", "HOLDER-OF-KEY"), empty string, null, or undefined.
• Any logic assuming OrganizationWithoutNetworkInfo lacks a gateways property now that it’s included.

packages/commonwell-cert-runner/src/flows/org-management-initiator-only.ts (3)

4-4: Import changes LGTM

Removing reliance on a static OID and keeping only member creds is a good simplification for the initiator-only flow.


34-34: Good call commenting out verbose request payload logs

This avoids multi-line logs and reduces risk of leaking sensitive request details during local runs.


49-49: Good to keep the updated payload log commented

Stays consistent with avoiding verbose/multi-line logs while still handy for quick toggling during local debugging.

Base automatically changed from eng-200-cert-runner-updated to develop August 21, 2025 16:30
@RamilGaripov RamilGaripov added this pull request to the merge queue Aug 21, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Aug 21, 2025
@RamilGaripov RamilGaripov added this pull request to the merge queue Aug 21, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to no response for status checks Aug 21, 2025
@RamilGaripov RamilGaripov added this pull request to the merge queue Aug 21, 2025
Merged via the queue into develop with commit e6af631 Aug 21, 2025
18 of 19 checks passed
@RamilGaripov RamilGaripov deleted the eng-200-cert-runner-init-only-fix branch August 21, 2025 18:31
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