jackson/npm/src/controller/utils.ts

388 lines
11 KiB
TypeScript
Raw Normal View History

2022-12-16 15:38:59 +00:00
import crypto from 'crypto';
import * as jose from 'jose';
import { Client, TokenSet } from 'openid-client';
import saml from '@boxyhq/saml20';
2022-12-16 15:38:59 +00:00
import * as dbutils from '../db/utils';
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
import type {
ConnectionType,
OAuthErrorHandlerParams,
SAMLSSOConnectionWithEncodedMetadata,
SAMLSSOConnectionWithRawMetadata,
Fallback for OIDC discovery (#926) * Support `metadata` in `OIDCSSORecord` * Helper to create oidc issuer instance * Use helper to create `Issuer` * Sync lock file * Support `oidcMetadata` in pre-loaded connections * Augment typings for OIDC SSO Connections * Use helper and pass metadata * Update validation to consider metadata * Support for OIDC metadata * Test fixes for types and error message * Fix swagger array type * Update swagger spec * Util to transform OIDC metadata JSON * Fix typings * Augment validation for oidc metadata fields * Add `oidcMetadataParse` to admin apis * Add `oidcMetadataParse` to setup link apis * Remove previously set discoveryUrl or metadata if any * Type updates admin portal * initialState seeding for `object` type * Add and place at bottom of the form * Type the catalog list * use to set the fields for the object type * Type updates * Gaurd against parentKey value * Add missing guard to `formatForDisplay` * Link like button * Support for fallback field * Util function to check if value is `{}` * Fix premature setting of metadata * Exclude fallback from form display Activate fallback on switch interaction * Fix settings view state setting * Sync lock file * Tweak error message * Add e2e for SSO connection add via metadata * Tweak switch * Refactor - Parameterize the e2e test * Cleanup * text tweaks * fixed test * Update comments * Use `data-testid` instead of button name * Source `data-testid`s from catalog * Refactor `hidden` className setting * Switch from `locator` to `getByTestId` * Apply hidden className to checkbox input --------- Co-authored-by: Kiran K <kiran@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2023-02-24 07:13:58 +00:00
OIDCSSOConnectionWithDiscoveryUrl,
OIDCSSOConnectionWithMetadata,
2022-12-16 15:38:59 +00:00
Profile,
SAMLSSORecord,
2023-03-16 21:42:36 +00:00
OIDCSSORecord,
Directory,
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
} from '../typings';
import { JacksonError } from './error';
import * as redirect from './oauth/redirect';
2021-12-23 11:33:26 +00:00
export enum IndexNames {
EntityID = 'entityID',
TenantProduct = 'tenantProduct',
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
OIDCProviderClientID = 'OIDCProviderClientID',
SAML Tracer (#945) * `SAMLTracer` bootstrap * Pass `db` handle * Expect `null` when license is void * Skeleton - WIP * Add `Trace` type * Hook into `samlTracer` * Secondary index and other changes * Remove secondary index, support pagination * Remove TTL on tracer store, add secondary indices * Add `traceId` alongside payload value * Implement `cleanUpStaleTraces` * Trace any error in response parsing stage * Move `setInterval` to constructor, also run at start * Use arithmetic * Make method `public` * `await` on delete op * Fix logic: store `concat` result in `traces` * Unit tests * Switch `randomUUID` to `generateMnemonic` * Tweak const name * Typo fix * SAML Tracer to the sidebar * Api routes and pages * i18n * SAML Tracer instance and type updates * Page and api route for admin portal * Update comment * Rename variable * Enhance types, make `timestamp` optional * prefix `traceId` to error_description * Assert traceId pattern and return value * Add translations for traces list table * Updates for SAML Tracer viewer * Format the `error_description` * Implement `getByTraceId` * keycheck instead of falsiness check * Use status `403` and minor tweaks * Api route for getting single trace by `traceId` * Trace Inspector view * Move SAMLTracer out of `ee` * Remove license check * Placeholder for parsing rawResponse * Trace inspect page * Tweak description * Wrap `samlResponse` in try catch * Refactor and style changes, display more context * Rethrow error for SAMLFederation without redirecting * Add `issuer`,`profile` to context * Switch to `<span>` inside `<p>` * Format profile display and fix issuer term * Add TODO comment * Use empty string if `issuer` turns out to be empty * Package lock changes * Tweak the comment * Handle error with no op within saveTrace * Wrap SAML error points in `authorize` with tracer * Sync lock file * Redirect to jackson error page for federated sso * Pass `samlTracer` to Federated SSO class * Trace the error and rethrow to caller * Refactor * Expand `context` type * Gaurd for absent context fields * Disable word-wrap for timestamp * Display additional context * `await` to catch errors inside promise * Use tenant/product from app instead of connection * Use translation and minor fix * More translations * More translations * Remove "unlikely request" capturing * Copy to clipboard button * `await` inside try catch block * cleanup * Expand `try` to include jackson init * Add `requestedOIDCFlow` * Filter out empty indices * Make `samlTracer` internal to jackson * Use `AdminController` to get trace data * Default to 0 for pagination * Add comment * Add IdP login flag to context * Move the assignment before IdP flow check to populate context * Add `relayState` to context * Add `redirectUri` to context
2023-03-07 22:36:13 +00:00
SSOClientID = 'SSOClientID',
Product = 'product',
// For Setup link
Service = 'service',
SetupToken = 'token',
ProductService = 'productService',
TenantProductService = 'tenantProductService',
}
Directory Sync (#202) * SCIM Config API - / POST * SCIM wip * Add SCIM Webhook * Send webhoo event, and add signature * SCIM Group wip * wip * SCIM wip * User store wip * wip * wip * SCIM - Groups management * Add the params validation * Cleanup * Create user API, return the created user * Replace the nanoid with crypto .randomBytes * Improve the transform methods * Fix the events APIs * Fix * Wip - Testing with OneLogin SCIM * wip * Make changes to SCIM APIs * wip * Add the method createRandomSecret * wip * wip * wip * wip * wip * wip * wip * refactor wip * refactor wip * wip * Users finished * Group finished * Group fix * Fix the types * Fix the types * wip webhook events * Fix the config API * wip * wip * wip * wip * Improve the methods * wip * wip * wip webhook * Refactor the code * Add some comments * Fix the API * wip SCIM * Fix the pk * Return the all the groups * Fix * Improve the code * Final changes * wip APIs * Rename variables * Rename the classes * Fix the APIs * wip * Admin UI - wip * Add SCIM config screen * Admin UI wip * Admin UI wip * Admin UI wip * Fix the Admin UI * Add tabs * Add tabs * Add user screens * Add EmptyState * Add users, groups info screen * Add JSON syntax highlighter * Fix the config details screen * Add authentication to the APIs * wip * Add types * Add webhook event logs * Add type to directory * Display the event log details * Fix the missing arg * Ability to configure the logging enable/disable * Display alert if webhook logging is disabled * Fix the SCIM * Applied prettier * Search users by userName * Fix the section width * Add pagination for /users /groups in admin UI * Add pagination for directory listing * Fix the issues with list() * Add APIs * Add Next.js middleware for authentication * Fix the TS issue * Add pagination for SCIM /users * Add pagination for SCIM /users * Moved the tests into sub folders * Add unit tests for directories, users * wip * wip - unit tests * wip - unit tests * Some improvments * wip * Finished the SCIM unit tests * Some fixes * Fixes * Rename methods * Fix the TS * Many fixes * Fixes * Fixes * SCIM Fixes * SCIM updates * Fix the unit tests * Fix the unit tests * Fix the unit tests * Improve the unit tests * A fix * File renamed as per JS standard * Fix * Updates * Fix the SCIM APIs * Fix the tests * Added the Base class * Some fixes * Some fixes * Some fixes * Fix the events * Renamed to directorySyncController for consistency * Moved the createId to Base class * Moved the createId to Base class * Remove the Next.js middleware and add authentication to each routes * Change the text * Merged * Revert the changes * Improved the response of the SDK and APIs * Fix the return value * Azure related changes * Add the middleware back * Infer the types from getServerSideProps * givenName and familyName can be empty depends on the mapping * Fix the issue with update * API changes * Fixes * Fix the types * Revert the change * Improving the Webhooks and Callback * Added the event callback and changed the implementation for Webhook * Fix the SCIM API * Fix the events.ts file * wip * Cleanup and improve the request handler * Revert the package.json changes * Make the directory name optional. * Add a generic scim provider to the type * wip * Remove supabase UI * Update package-lock.json * Update the UI with DaisyUI * UI fixes * Final changes to the UI * Standardize the Input theme Co-authored-by: Kiran <kiran@Kirans-MacBook-Pro.local> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2022-09-08 14:36:18 +00:00
// The namespace prefix for the database store
export const storeNamespacePrefix = {
dsync: {
config: 'dsync:config',
logs: 'dsync:logs',
users: 'dsync:users',
groups: 'dsync:groups',
members: 'dsync:members',
Google Directory API Integration (#1158) * Add Google Group API * Restructure the Group interface * Rename the methods * wip * temp change * Revert the changes * Fix the groups from Google * wip fetch users * Skip directory check * Convert to SCIM schema * Updates to users sync * Fix the unit test * Rename folder and merge the files * add raw to the user payload * Fix the unit tests * Optimize the Group sync create ops * Reorder import * Remove unused imports * Add type safety to SCIM Schema * Fix the users and groups update * try fixing unit tests * Fix the file extension * Delete groups that are not in the directory anymore * Fix the group update * Compare and find the delete users * Add and update group members * cleanup the test * Fix the test (temp) * dont throw error * Add secondary index if the directory type is `google` * Rename the file * wip * Export functions inline * Hide the SCIM endpoint and token for non-scim provider * Update the `dsync` option key to allow multiple providers * Restructure the folders * Update folder structure * Cleanup * Revert the callback changes * Fix the type * Fix the type * Fix existing unit tests * add callback * Fix the internal callback * Fix the method call * merge the type files * add console.info for testing * Fix the Google OAuth client usage * Reactor the update method * Handle no users or group cases * Refactor the sync method * Fix the pagination * Cleanup * Finish the pagination * Fix the unit tests * Fix the lint errors * Fix the build issues * Pass directory id to the method * Pass directoryId while fetching * apply changes to the UI * display the Google auth URL * Fix the type * add unit tests * add unit test for syncing users * add unit tests * Pass operation to SCIM payload * unit tests wip 1 * updated * Test the events deleted * Test group.user_added events * Finish the tests * Revert and cleanup * update map.js * Revert * update the e2e test * Cleanup * Revert * label tweak * Remove unused import * Protect the cron job using apiKey --------- Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2023-06-15 13:31:38 +00:00
providers: 'dsync:providers',
events: 'dsync:events',
lock: 'dsync:lock',
Directory Sync (#202) * SCIM Config API - / POST * SCIM wip * Add SCIM Webhook * Send webhoo event, and add signature * SCIM Group wip * wip * SCIM wip * User store wip * wip * wip * SCIM - Groups management * Add the params validation * Cleanup * Create user API, return the created user * Replace the nanoid with crypto .randomBytes * Improve the transform methods * Fix the events APIs * Fix * Wip - Testing with OneLogin SCIM * wip * Make changes to SCIM APIs * wip * Add the method createRandomSecret * wip * wip * wip * wip * wip * wip * wip * refactor wip * refactor wip * wip * Users finished * Group finished * Group fix * Fix the types * Fix the types * wip webhook events * Fix the config API * wip * wip * wip * wip * Improve the methods * wip * wip * wip webhook * Refactor the code * Add some comments * Fix the API * wip SCIM * Fix the pk * Return the all the groups * Fix * Improve the code * Final changes * wip APIs * Rename variables * Rename the classes * Fix the APIs * wip * Admin UI - wip * Add SCIM config screen * Admin UI wip * Admin UI wip * Admin UI wip * Fix the Admin UI * Add tabs * Add tabs * Add user screens * Add EmptyState * Add users, groups info screen * Add JSON syntax highlighter * Fix the config details screen * Add authentication to the APIs * wip * Add types * Add webhook event logs * Add type to directory * Display the event log details * Fix the missing arg * Ability to configure the logging enable/disable * Display alert if webhook logging is disabled * Fix the SCIM * Applied prettier * Search users by userName * Fix the section width * Add pagination for /users /groups in admin UI * Add pagination for directory listing * Fix the issues with list() * Add APIs * Add Next.js middleware for authentication * Fix the TS issue * Add pagination for SCIM /users * Add pagination for SCIM /users * Moved the tests into sub folders * Add unit tests for directories, users * wip * wip - unit tests * wip - unit tests * Some improvments * wip * Finished the SCIM unit tests * Some fixes * Fixes * Rename methods * Fix the TS * Many fixes * Fixes * Fixes * SCIM Fixes * SCIM updates * Fix the unit tests * Fix the unit tests * Fix the unit tests * Improve the unit tests * A fix * File renamed as per JS standard * Fix * Updates * Fix the SCIM APIs * Fix the tests * Added the Base class * Some fixes * Some fixes * Some fixes * Fix the events * Renamed to directorySyncController for consistency * Moved the createId to Base class * Moved the createId to Base class * Remove the Next.js middleware and add authentication to each routes * Change the text * Merged * Revert the changes * Improved the response of the SDK and APIs * Fix the return value * Azure related changes * Add the middleware back * Infer the types from getServerSideProps * givenName and familyName can be empty depends on the mapping * Fix the issue with update * API changes * Fixes * Fix the types * Revert the change * Improving the Webhooks and Callback * Added the event callback and changed the implementation for Webhook * Fix the SCIM API * Fix the events.ts file * wip * Cleanup and improve the request handler * Revert the package.json changes * Make the directory name optional. * Add a generic scim provider to the type * wip * Remove supabase UI * Update package-lock.json * Update the UI with DaisyUI * UI fixes * Final changes to the UI * Standardize the Input theme Co-authored-by: Kiran <kiran@Kirans-MacBook-Pro.local> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2022-09-08 14:36:18 +00:00
},
saml: {
config: 'saml:config',
},
};
export const relayStatePrefix = 'boxyhq_jackson_';
New OIDC fed (#2336) * add WellKnownURLs * Fix translation keys * Update dependencies and add IdP Configuration * Update common.json with new translations * wip * Update @boxyhq/internal-ui version to 0.0.5 * add internal ui folder * Fix imports and build * Refactor internal-ui package structure * wip shared UI * Fix the build * WIP * Add new components and hooks for directory sync * WIP * lint fix * updated swr * WIP * users * Refactor shared components and fix API endpoints*** ***Update directory user page and add new federated SAML app * Fix lint * wip * Add new files and update existing files * Refactor DirectoryGroups and DirectoryInfo components * Update localization strings for directory UI * Update Google Auth URL description in common.json * Refactor directory tab and add delete functionality to webhook logs * IdP selection screen changes * Delete unused files and update dependencies * Fix column declaration * Add internal-ui/dist to .gitignore * Update page limit and add new dependencies * wip * Refactor directory search in user API endpoint * wip * Refactor directory retrieval logic in user and group API handlers * Add API endpoints for retrieving webhook events * check app's redirectUrl, TODO: save app info into session to read later * Add query parameters to API URLs in DirectoryGroups * working saml login via IdP select. TODO: oidc login via IdP select and saml + oidc login with 1 connection * oidc IdP working with selection * working oidc fed -> saml flow * Add Google authorization status badge and handle pagination in FederatedSAMLApps * Add router prop to AppsList component and update page header titles * UI changes * updated peer-deps * Add new files and export functions * Remove unused router prop * Add PencilIcon to FederatedSAMLApps * updated federated app creation page * updated federated app edit page * Refactor FederatedSAMLApps and NewFederatedSAMLApp components * lint fix * lint fix * updated package-lock * add jose npm to dev dep * added missing strings * added missing strings * locale strings fix * locale strings cleanup * tweaks to icon imports * replaced textarea with list of inputs for Federated Apps redirect url * update package-lock * Add prepublish step * Build and publish npm and internal ui * Refactor install step * Run npm install (for local) inside internal ui automatically using prepare * Remove eslint setup for internal-ui * updated package-lock * Add `--legacy-peer-deps` to prevent installing peer dependencies * Fix the types import path * wip * wip * Fix the types * Format * Update package-lock * Cleanup * Try adding jose library version 5.2.2 * allow selective subdomain globbing * removed duplicate jose lib * updated package-lock * updated swagger doc * SAML Federation -> Identity Federation * fixed locale strings * turn off autocomplete for tags input --------- Co-authored-by: Kiran K <mailtokirankk@gmail.com> Co-authored-by: Aswin V <vaswin91@gmail.com>
2024-03-05 16:57:02 +00:00
export const clientIDFederatedPrefix = 'fed_';
export const clientIDOIDCPrefix = 'oidc_';
export const validateAbsoluteUrl = (url, message) => {
try {
new URL(url);
} catch (err) {
throw new JacksonError(message ? message : 'Invalid url', 400);
}
};
export const OAuthErrorResponse = ({
error,
error_description,
redirect_uri,
state,
}: OAuthErrorHandlerParams) => {
return redirect.success(redirect_uri, { error, error_description, state });
};
// https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
export function getErrorMessage(error: unknown) {
if (error instanceof saml.WrapError) {
return error.message + ' ' + error.inner.message;
}
if (error instanceof Error) {
return error.message;
}
return String(error);
}
Support for OIDC flow (#306) * Support 'POST' at authorization endpoint * handle additional scope params * handle additional claims param * Try with `legacy-peer-deps` true * Fix logic * Set legacy-peer-deps to `true` * Remove `.npmrc` files and sync packages from main * Resolve conflicts * Load jwtSigningKeys into env * Return id_token for OIDC flow * Support `nonce` * Add type for `nonce` * Set `nonce` only if present in request * Expose OpenId provider metadata * Update metadata * Tweak path remove dot, map jwks * Add jwsAlg and source keys using base64 * Source jose from root package.json too * JWS utils * Serve jwks_uri * Load private key for signing * Fix authz endpoint * Format example env * Fix claims * Format discovery and add missing metadata * Include the basic profile in id_token * Fix claims access * Remove console log * Sync package lock * Cleanup * Support for claims is optional * cleanup type * Set `Content-Type` header * Remove default from env * Handle jwt env * oidc fixture * Test for oidc flow, check id_token in response * Add jwt envs * Fix for undefined * Remove keys check in controller init * Runtime check for JWS keys * check if id_token is absent * Check for claims and verify signature * Snapshot test oidc discovery page * Add snapshot for linux to work in CI * Test with a fontless screenshot * test with this one * add a debug step * Get the entire dir for snapshot * Test with this * Comment out debug step * snapshot test jwks * Update env * Upload screenshot for linux * Add debug step * Update snapshot * Sync package lock * Remove local testing snapshots * Assert using api request * Update to use api test for jwks endpoint * Set `JWS_ALG` env * Prefix openid vars * Fix env access * Fix e2e test * Fix options in tests * Fix env var access * Use ttl from env * Simplify exp value setting * oidc discovery controller * Fix typing * Handle case where signing keys are not set * return `oidcDiscoveryController` * Throw a JacksonError like object * Use controllers and cleanup * throw JacksonError like object * Minor formatting * Fix typing and add check for undefined * Keep order of packages same as in main * Update key generation comment * Initialise `openid` correctly in npm * Cleanup * Set `sub` claim * Set 'sub' only for oidc flow
2022-07-23 17:04:55 +00:00
Directory Sync (#202) * SCIM Config API - / POST * SCIM wip * Add SCIM Webhook * Send webhoo event, and add signature * SCIM Group wip * wip * SCIM wip * User store wip * wip * wip * SCIM - Groups management * Add the params validation * Cleanup * Create user API, return the created user * Replace the nanoid with crypto .randomBytes * Improve the transform methods * Fix the events APIs * Fix * Wip - Testing with OneLogin SCIM * wip * Make changes to SCIM APIs * wip * Add the method createRandomSecret * wip * wip * wip * wip * wip * wip * wip * refactor wip * refactor wip * wip * Users finished * Group finished * Group fix * Fix the types * Fix the types * wip webhook events * Fix the config API * wip * wip * wip * wip * Improve the methods * wip * wip * wip webhook * Refactor the code * Add some comments * Fix the API * wip SCIM * Fix the pk * Return the all the groups * Fix * Improve the code * Final changes * wip APIs * Rename variables * Rename the classes * Fix the APIs * wip * Admin UI - wip * Add SCIM config screen * Admin UI wip * Admin UI wip * Admin UI wip * Fix the Admin UI * Add tabs * Add tabs * Add user screens * Add EmptyState * Add users, groups info screen * Add JSON syntax highlighter * Fix the config details screen * Add authentication to the APIs * wip * Add types * Add webhook event logs * Add type to directory * Display the event log details * Fix the missing arg * Ability to configure the logging enable/disable * Display alert if webhook logging is disabled * Fix the SCIM * Applied prettier * Search users by userName * Fix the section width * Add pagination for /users /groups in admin UI * Add pagination for directory listing * Fix the issues with list() * Add APIs * Add Next.js middleware for authentication * Fix the TS issue * Add pagination for SCIM /users * Add pagination for SCIM /users * Moved the tests into sub folders * Add unit tests for directories, users * wip * wip - unit tests * wip - unit tests * Some improvments * wip * Finished the SCIM unit tests * Some fixes * Fixes * Rename methods * Fix the TS * Many fixes * Fixes * Fixes * SCIM Fixes * SCIM updates * Fix the unit tests * Fix the unit tests * Fix the unit tests * Improve the unit tests * A fix * File renamed as per JS standard * Fix * Updates * Fix the SCIM APIs * Fix the tests * Added the Base class * Some fixes * Some fixes * Some fixes * Fix the events * Renamed to directorySyncController for consistency * Moved the createId to Base class * Moved the createId to Base class * Remove the Next.js middleware and add authentication to each routes * Change the text * Merged * Revert the changes * Improved the response of the SDK and APIs * Fix the return value * Azure related changes * Add the middleware back * Infer the types from getServerSideProps * givenName and familyName can be empty depends on the mapping * Fix the issue with update * API changes * Fixes * Fix the types * Revert the change * Improving the Webhooks and Callback * Added the event callback and changed the implementation for Webhook * Fix the SCIM API * Fix the events.ts file * wip * Cleanup and improve the request handler * Revert the package.json changes * Make the directory name optional. * Add a generic scim provider to the type * wip * Remove supabase UI * Update package-lock.json * Update the UI with DaisyUI * UI fixes * Final changes to the UI * Standardize the Input theme Co-authored-by: Kiran <kiran@Kirans-MacBook-Pro.local> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2022-09-08 14:36:18 +00:00
export const createRandomSecret = async (length: number) => {
return crypto
.randomBytes(length)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
Support for OIDC flow (#306) * Support 'POST' at authorization endpoint * handle additional scope params * handle additional claims param * Try with `legacy-peer-deps` true * Fix logic * Set legacy-peer-deps to `true` * Remove `.npmrc` files and sync packages from main * Resolve conflicts * Load jwtSigningKeys into env * Return id_token for OIDC flow * Support `nonce` * Add type for `nonce` * Set `nonce` only if present in request * Expose OpenId provider metadata * Update metadata * Tweak path remove dot, map jwks * Add jwsAlg and source keys using base64 * Source jose from root package.json too * JWS utils * Serve jwks_uri * Load private key for signing * Fix authz endpoint * Format example env * Fix claims * Format discovery and add missing metadata * Include the basic profile in id_token * Fix claims access * Remove console log * Sync package lock * Cleanup * Support for claims is optional * cleanup type * Set `Content-Type` header * Remove default from env * Handle jwt env * oidc fixture * Test for oidc flow, check id_token in response * Add jwt envs * Fix for undefined * Remove keys check in controller init * Runtime check for JWS keys * check if id_token is absent * Check for claims and verify signature * Snapshot test oidc discovery page * Add snapshot for linux to work in CI * Test with a fontless screenshot * test with this one * add a debug step * Get the entire dir for snapshot * Test with this * Comment out debug step * snapshot test jwks * Update env * Upload screenshot for linux * Add debug step * Update snapshot * Sync package lock * Remove local testing snapshots * Assert using api request * Update to use api test for jwks endpoint * Set `JWS_ALG` env * Prefix openid vars * Fix env access * Fix e2e test * Fix options in tests * Fix env var access * Use ttl from env * Simplify exp value setting * oidc discovery controller * Fix typing * Handle case where signing keys are not set * return `oidcDiscoveryController` * Throw a JacksonError like object * Use controllers and cleanup * throw JacksonError like object * Minor formatting * Fix typing and add check for undefined * Keep order of packages same as in main * Update key generation comment * Initialise `openid` correctly in npm * Cleanup * Set `sub` claim * Set 'sub' only for oidc flow
2022-07-23 17:04:55 +00:00
export async function loadJWSPrivateKey(key: string, alg: string): Promise<jose.KeyLike> {
const pkcs8 = Buffer.from(key, 'base64').toString('ascii');
const privateKey = await jose.importPKCS8(pkcs8, alg);
return privateKey;
}
export function isJWSKeyPairLoaded(jwsKeyPair: { private: string; public: string }) {
if (!jwsKeyPair.private || !jwsKeyPair.public) {
return false;
}
return true;
}
export const importJWTPublicKey = async (key: string, jwsAlg: string): Promise<jose.KeyLike> => {
const spki = Buffer.from(key, 'base64').toString('ascii');
const publicKey = await jose.importSPKI(spki, jwsAlg);
return publicKey;
};
export const exportPublicKeyJWK = async (key: jose.KeyLike): Promise<jose.JWK> => {
const publicJWK = await jose.exportJWK(key);
return publicJWK;
};
export const generateJwkThumbprint = async (jwk: jose.JWK): Promise<string> => {
const thumbprint = await jose.calculateJwkThumbprint(jwk);
return thumbprint;
};
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
export const validateSSOConnection = (
Fallback for OIDC discovery (#926) * Support `metadata` in `OIDCSSORecord` * Helper to create oidc issuer instance * Use helper to create `Issuer` * Sync lock file * Support `oidcMetadata` in pre-loaded connections * Augment typings for OIDC SSO Connections * Use helper and pass metadata * Update validation to consider metadata * Support for OIDC metadata * Test fixes for types and error message * Fix swagger array type * Update swagger spec * Util to transform OIDC metadata JSON * Fix typings * Augment validation for oidc metadata fields * Add `oidcMetadataParse` to admin apis * Add `oidcMetadataParse` to setup link apis * Remove previously set discoveryUrl or metadata if any * Type updates admin portal * initialState seeding for `object` type * Add and place at bottom of the form * Type the catalog list * use to set the fields for the object type * Type updates * Gaurd against parentKey value * Add missing guard to `formatForDisplay` * Link like button * Support for fallback field * Util function to check if value is `{}` * Fix premature setting of metadata * Exclude fallback from form display Activate fallback on switch interaction * Fix settings view state setting * Sync lock file * Tweak error message * Add e2e for SSO connection add via metadata * Tweak switch * Refactor - Parameterize the e2e test * Cleanup * text tweaks * fixed test * Update comments * Use `data-testid` instead of button name * Source `data-testid`s from catalog * Refactor `hidden` className setting * Switch from `locator` to `getByTestId` * Apply hidden className to checkbox input --------- Co-authored-by: Kiran K <kiran@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2023-02-24 07:13:58 +00:00
body:
| SAMLSSOConnectionWithRawMetadata
| SAMLSSOConnectionWithEncodedMetadata
| OIDCSSOConnectionWithDiscoveryUrl
| OIDCSSOConnectionWithMetadata,
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
strategy: ConnectionType
): void => {
const { defaultRedirectUrl, redirectUrl, tenant, product, description } = body;
const encodedRawMetadata = 'encodedRawMetadata' in body ? body.encodedRawMetadata : undefined;
const rawMetadata = 'rawMetadata' in body ? body.rawMetadata : undefined;
const oidcDiscoveryUrl = 'oidcDiscoveryUrl' in body ? body.oidcDiscoveryUrl : undefined;
Fallback for OIDC discovery (#926) * Support `metadata` in `OIDCSSORecord` * Helper to create oidc issuer instance * Use helper to create `Issuer` * Sync lock file * Support `oidcMetadata` in pre-loaded connections * Augment typings for OIDC SSO Connections * Use helper and pass metadata * Update validation to consider metadata * Support for OIDC metadata * Test fixes for types and error message * Fix swagger array type * Update swagger spec * Util to transform OIDC metadata JSON * Fix typings * Augment validation for oidc metadata fields * Add `oidcMetadataParse` to admin apis * Add `oidcMetadataParse` to setup link apis * Remove previously set discoveryUrl or metadata if any * Type updates admin portal * initialState seeding for `object` type * Add and place at bottom of the form * Type the catalog list * use to set the fields for the object type * Type updates * Gaurd against parentKey value * Add missing guard to `formatForDisplay` * Link like button * Support for fallback field * Util function to check if value is `{}` * Fix premature setting of metadata * Exclude fallback from form display Activate fallback on switch interaction * Fix settings view state setting * Sync lock file * Tweak error message * Add e2e for SSO connection add via metadata * Tweak switch * Refactor - Parameterize the e2e test * Cleanup * text tweaks * fixed test * Update comments * Use `data-testid` instead of button name * Source `data-testid`s from catalog * Refactor `hidden` className setting * Switch from `locator` to `getByTestId` * Apply hidden className to checkbox input --------- Co-authored-by: Kiran K <kiran@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2023-02-24 07:13:58 +00:00
const oidcMetadata = 'oidcMetadata' in body ? body.oidcMetadata : undefined;
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
const oidcClientId = 'oidcClientId' in body ? body.oidcClientId : undefined;
const oidcClientSecret = 'oidcClientSecret' in body ? body.oidcClientSecret : undefined;
const metadataUrl = 'metadataUrl' in body ? body.metadataUrl : undefined;
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
if (strategy !== 'saml' && strategy !== 'oidc') {
throw new JacksonError(`Strategy: ${strategy} not supported`, 400);
}
if (strategy === 'saml') {
if (!rawMetadata && !encodedRawMetadata && !metadataUrl) {
throw new JacksonError('Please provide rawMetadata or encodedRawMetadata or metadataUrl', 400);
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
}
}
if (strategy === 'oidc') {
if (!oidcClientId) {
throw new JacksonError('Please provide the clientId from OpenID Provider', 400);
}
if (!oidcClientSecret) {
throw new JacksonError('Please provide the clientSecret from OpenID Provider', 400);
}
Fallback for OIDC discovery (#926) * Support `metadata` in `OIDCSSORecord` * Helper to create oidc issuer instance * Use helper to create `Issuer` * Sync lock file * Support `oidcMetadata` in pre-loaded connections * Augment typings for OIDC SSO Connections * Use helper and pass metadata * Update validation to consider metadata * Support for OIDC metadata * Test fixes for types and error message * Fix swagger array type * Update swagger spec * Util to transform OIDC metadata JSON * Fix typings * Augment validation for oidc metadata fields * Add `oidcMetadataParse` to admin apis * Add `oidcMetadataParse` to setup link apis * Remove previously set discoveryUrl or metadata if any * Type updates admin portal * initialState seeding for `object` type * Add and place at bottom of the form * Type the catalog list * use to set the fields for the object type * Type updates * Gaurd against parentKey value * Add missing guard to `formatForDisplay` * Link like button * Support for fallback field * Util function to check if value is `{}` * Fix premature setting of metadata * Exclude fallback from form display Activate fallback on switch interaction * Fix settings view state setting * Sync lock file * Tweak error message * Add e2e for SSO connection add via metadata * Tweak switch * Refactor - Parameterize the e2e test * Cleanup * text tweaks * fixed test * Update comments * Use `data-testid` instead of button name * Source `data-testid`s from catalog * Refactor `hidden` className setting * Switch from `locator` to `getByTestId` * Apply hidden className to checkbox input --------- Co-authored-by: Kiran K <kiran@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2023-02-24 07:13:58 +00:00
if (!oidcDiscoveryUrl && !oidcMetadata) {
throw new JacksonError(
'Please provide the discoveryUrl or issuer metadata for the OpenID Provider',
400
);
}
if (!oidcDiscoveryUrl && oidcMetadata) {
const { issuer, authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri } = oidcMetadata;
if (!issuer) {
throw new JacksonError('"issuer" missing in the metadata for the OpenID Provider', 400);
}
if (!authorization_endpoint) {
throw new JacksonError(
'"authorization_endpoint" missing in the metadata for the OpenID Provider',
400
);
}
if (!token_endpoint) {
throw new JacksonError('"token_endpoint" missing in the metadata for the OpenID Provider', 400);
}
if (!userinfo_endpoint) {
throw new JacksonError('"userinfo_endpoint" missing in the metadata for the OpenID Provider', 400);
}
if (!jwks_uri) {
throw new JacksonError('"jwks_uri" missing in the metadata for the OpenID Provider', 400);
}
Support for OIDC Identity Providers (#385) * Support connection dynamic param in route * Pass `connection` * Fix tests * Accept oidc params and validate the same * Rename `connection` --> `strategy` * Use saml for preLoadedConfig for now * Rename `apiController` --> `apiConfigController` * Flatten the params * Validate passed config * Backward compatibility for embed setup * Impl for oidc config save * index addition for oidc clientId * Remove param, defaults to saml * Validation will be done inside controller * Zap secondary index on clientId, not required * Rename `APIConfigController` --> `ConfigAPIController` * Update swagger * Fix name * Fix name elsewhere * Revert filter * Split `saml` and `oidc` create/update logic * Route `saml` and `oidc` * Test update * Update swagger * Update swagger * Use tenant/product from stored config in lieu of params * Validate passed OIDC clientId using hash * Update swagger annotations * Handlers for getting OIDC/SAML configs * Validate tenant/product in update * Typo fix * Fix test * Default to empty string, validation is done to check if the params are not empty * Extract provider name just like saml * OIDC Connection support *delta for authorize* - Renamed samlConfig(s) → connection(s) - Renamed resolvedSamlConfig -> resolvedConnection - Detect connection is SAML or OIDC - Perform Issuer discovery and oidc client init - Tweak error responses - Persist oidc client metadata in session * Test type fix * Test fix * openid-client dependency * Sync package locks * Fix return type - Remove `undefined` from return type - Return `OAuthErrorResponse` for else case * Handle OIDC Authorization response * Persist OIDC code_verifier * Remove scope check for OIDC connection * Normalize scope before relaying * Method name update * Extract user profile from id token and userinfo * Handle error response from OIDC Provider * Update type * Type update with OIDC specific error codes * Bug fix : typo * Cleanup * OIDC callback route * Bug fix: return profile and parameter fix * Rename `config` -> `connection` * Use `Link` and add oidc connection nav item * Use `strategy` from query param * Delta ↴ - Reorganised api routes - Removed Admin controller filtering methods for saml/oidc * Fix page link in e2e test * Changes: - Handle oidc connection fields - Rename component file path * Remove slug for save/update connection * Fix keyname in update operation * Import path update * Radio select connection type for new connection * Update lock file * Sync lock file * Sync package lock * Fix connectionType detection for new connection * Fix error message * Add comment * Tweak comment * Use the correct state and directly from session * Sync lock file * Remove `provider` from OAuthReqBody * Remove duplicate scopes * Pass recent param additions to idpSelection page * Add badge for Provider type * Style tweak * Style IdP type selection * Add test for oidc provider * Comment * Check for empty state * Add test for oidcAuthzResponse * Add test for oidcAuthzResponse * Add test for error response from OP * Error message tweak * Test the happy path * Remove unused import * Fix assertion * - Fix types - add createOIDCConfig` test for missing params * Test happy path for `createOIDCConfig` * Param validation tests for `createOIDCConfig` * Test for `updateOIDCConfig` * Tests for `updateOIDCConfig` * Male `oidcPath` required like `samlPath` * Bump `openid-client` version * Refactor * Update test coverage map * Tweak label * Split openid/oauth tests * call `t.end` * Fix file name in comment * Add test teardown * Improve coverage and rename test files * For backwards compatibility * Minor formatting * Add api paths for /connection * Zap config path for admin ui * Update swagger spec * Rename `configAPIController` → `connectionAPIController` * Rename `IdPConfig` → `IdPConnection` * Rename `validateIdPConfig` → `validateIdPConnection` * Rename `createSAMLConfig` → `createSAMLConnection` * Rename `createOIDCConfig` → `createOIDCConnection` * Update swagger spec * Rename `updateSAMLConfig` → `updateSAMLConnection`, `updateOIDCConfig` → `updateOIDCConnection` * Make `clientID`/`clientSecret` readOnly * Rename `configStore` → `connectionStore` * Update swagger spec * Add `getConnection` + `deleteConnection` * Remove `/api/v1/oidc/config` and keep `api/v1/saml/config` * Rename `getAllConfig` → `getAllConnection` * Rename `readConfig` → `loadConnection` * Rename `deleteConfiguration` → `deleteConnection` * Add `preLoadedConnection` env * Update map and cli * Refactor api tests and rename config to connection * Rename `configList` → `connectionList` * Rename `samlConfig` → `samlConnection` * Rename config -> connection * Rename `config` → `connection` * Rename counters for otl * Sync package lock * Remove api key validation from api route * Update Admin ui title * Update swagger * Update otl metric descriptions * Update var naming to connection * Add strategy validation * Add tests for invalid strategy * Sync package lock * Upgrade and pin version * Update saml config api with deprecated * Updated swagger spec for deprecated config api * Bump package version * Fix label * - removed strategy for `get` and `delete` - Type update * Type updates * getConnection -> getConnections, deleteConnection -> deleteConnections * Update swagger spec * Use only for saml connection * Remove slug from api routes * API path updates * Type updates * Helper util for api routes to check strategy * Type updates and api changes * `OAuthReq` typings enhancement * Narrowed down types for `OAuthTokenReq` and `OIDCAuthzResponsePayload` * `IdPConnection` -> `SSOConnection` * Update cookie name to avoid clash * Handle the uncaught case to prevent req hanging
2022-09-30 10:37:21 +00:00
}
}
if (!defaultRedirectUrl) {
throw new JacksonError('Please provide a defaultRedirectUrl', 400);
}
if (!redirectUrl) {
throw new JacksonError('Please provide redirectUrl', 400);
}
if (!tenant) {
throw new JacksonError('Please provide tenant', 400);
}
if (!product) {
throw new JacksonError('Please provide product', 400);
}
if (description && description.length > 100) {
throw new JacksonError('Description should not exceed 100 characters', 400);
}
};
export const validateRedirectUrl = ({ redirectUrlList, defaultRedirectUrl }) => {
if (redirectUrlList) {
if (redirectUrlList.length > 100) {
throw new JacksonError('Exceeded maximum number of allowed redirect urls', 400);
}
for (const url of redirectUrlList) {
validateAbsoluteUrl(url, 'redirectUrl is invalid');
}
}
if (defaultRedirectUrl) {
validateAbsoluteUrl(defaultRedirectUrl, 'defaultRedirectUrl is invalid');
}
};
export const extractRedirectUrls = (urls: string[] | string): string[] => {
if (!urls) {
return [];
}
if (typeof urls === 'string') {
if (urls.startsWith('[')) {
// redirectUrl is a stringified array
return JSON.parse(urls);
}
// redirectUrl is a single URL
return [urls];
}
// redirectUrl is an array of URLs
return urls;
};
export const extractHostName = (url: string): string | null => {
try {
const pUrl = new URL(url);
if (pUrl.hostname.startsWith('www.')) {
return pUrl.hostname.substring(4);
}
return pUrl.hostname;
} catch (err) {
return null;
}
};
2022-12-16 15:38:59 +00:00
export const extractOIDCUserProfile = async (tokenSet: TokenSet, oidcClient: Client) => {
const idTokenClaims = tokenSet.claims();
const userinfo = await oidcClient.userinfo(tokenSet);
const profile: { claims: Partial<Profile & { raw: Record<string, unknown> }> } = { claims: {} };
profile.claims.id = idTokenClaims.sub;
profile.claims.email = idTokenClaims.email ?? userinfo.email;
profile.claims.firstName = idTokenClaims.given_name ?? userinfo.given_name;
profile.claims.lastName = idTokenClaims.family_name ?? userinfo.family_name;
profile.claims.roles = idTokenClaims.roles ?? (userinfo.roles as any);
profile.claims.groups = idTokenClaims.groups ?? (userinfo.groups as any);
profile.claims.raw = userinfo;
return profile;
};
export const getScopeValues = (scope?: string): string[] => {
return typeof scope === 'string' ? scope.split(' ').filter((s) => s.length > 0) : [];
};
export const getEncodedTenantProduct = (
param: string
): { tenant: string | null; product: string | null } | null => {
try {
const sp = new URLSearchParams(param);
const tenant = sp.get('tenant');
const product = sp.get('product');
if (tenant && product) {
return {
tenant: sp.get('tenant'),
product: sp.get('product'),
};
}
return null;
} catch (err) {
return null;
}
};
export const validateTenantAndProduct = (tenant: string, product: string) => {
if (tenant.indexOf(':') !== -1) {
throw new JacksonError('tenant cannot contain the character :', 400);
}
if (product.indexOf(':') !== -1) {
throw new JacksonError('product cannot contain the character :', 400);
}
};
2022-12-16 15:38:59 +00:00
export const appID = (tenant: string, product: string) => {
return dbutils.keyDigest(dbutils.keyFromParts(tenant, product));
};
New OIDC fed (#2336) * add WellKnownURLs * Fix translation keys * Update dependencies and add IdP Configuration * Update common.json with new translations * wip * Update @boxyhq/internal-ui version to 0.0.5 * add internal ui folder * Fix imports and build * Refactor internal-ui package structure * wip shared UI * Fix the build * WIP * Add new components and hooks for directory sync * WIP * lint fix * updated swr * WIP * users * Refactor shared components and fix API endpoints*** ***Update directory user page and add new federated SAML app * Fix lint * wip * Add new files and update existing files * Refactor DirectoryGroups and DirectoryInfo components * Update localization strings for directory UI * Update Google Auth URL description in common.json * Refactor directory tab and add delete functionality to webhook logs * IdP selection screen changes * Delete unused files and update dependencies * Fix column declaration * Add internal-ui/dist to .gitignore * Update page limit and add new dependencies * wip * Refactor directory search in user API endpoint * wip * Refactor directory retrieval logic in user and group API handlers * Add API endpoints for retrieving webhook events * check app's redirectUrl, TODO: save app info into session to read later * Add query parameters to API URLs in DirectoryGroups * working saml login via IdP select. TODO: oidc login via IdP select and saml + oidc login with 1 connection * oidc IdP working with selection * working oidc fed -> saml flow * Add Google authorization status badge and handle pagination in FederatedSAMLApps * Add router prop to AppsList component and update page header titles * UI changes * updated peer-deps * Add new files and export functions * Remove unused router prop * Add PencilIcon to FederatedSAMLApps * updated federated app creation page * updated federated app edit page * Refactor FederatedSAMLApps and NewFederatedSAMLApp components * lint fix * lint fix * updated package-lock * add jose npm to dev dep * added missing strings * added missing strings * locale strings fix * locale strings cleanup * tweaks to icon imports * replaced textarea with list of inputs for Federated Apps redirect url * update package-lock * Add prepublish step * Build and publish npm and internal ui * Refactor install step * Run npm install (for local) inside internal ui automatically using prepare * Remove eslint setup for internal-ui * updated package-lock * Add `--legacy-peer-deps` to prevent installing peer dependencies * Fix the types import path * wip * wip * Fix the types * Format * Update package-lock * Cleanup * Try adding jose library version 5.2.2 * allow selective subdomain globbing * removed duplicate jose lib * updated package-lock * updated swagger doc * SAML Federation -> Identity Federation * fixed locale strings * turn off autocomplete for tags input --------- Co-authored-by: Kiran K <mailtokirankk@gmail.com> Co-authored-by: Aswin V <vaswin91@gmail.com>
2024-03-05 16:57:02 +00:00
export const fedAppID = (tenant: string, product: string, type?: string) => {
return (type === 'oidc' ? clientIDOIDCPrefix : '') + appID(tenant, product);
};
// List of well known providers
const wellKnownProviders = {
'okta.com': 'Okta',
'sts.windows.net': 'Azure AD',
'mocksaml.com': 'MockSAML',
'onelogin.com': 'OneLogin',
'keycloak.com': 'Keycloak',
'jumpcloud.com': 'JumpCloud',
'google.com': 'Google',
'auth0.com': 'Auth0',
'pingone.com': 'PingOne',
} as const;
// Find the friendly name of the provider from the entityID
export const findFriendlyProviderName = (providerName: string): keyof typeof wellKnownProviders | 'null' => {
const provider = Object.keys(wellKnownProviders).find((provider) => providerName.includes(provider));
return provider ? wellKnownProviders[provider] : null;
};
2023-03-16 21:42:36 +00:00
export const transformConnections = (connections: Array<SAMLSSORecord | OIDCSSORecord>) => {
if (connections.length === 0) {
return connections;
}
return connections.map(transformConnection);
};
export const transformConnection = (connection: SAMLSSORecord | OIDCSSORecord) => {
if ('idpMetadata' in connection) {
connection.idpMetadata.friendlyProviderName = findFriendlyProviderName(connection.idpMetadata.provider);
}
if ('oidcProvider' in connection) {
connection.oidcProvider.friendlyProviderName = findFriendlyProviderName(connection.oidcProvider.provider);
}
if (!('deactivated' in connection)) {
connection.deactivated = false;
}
return connection;
};
export const isLocalhost = (url: string) => {
let givenURL: URL;
try {
givenURL = new URL(url);
} catch (error) {
return false;
}
return givenURL.hostname === 'localhost' || givenURL.hostname === '127.0.0.1';
};
export const isConnectionActive = (connection: SAMLSSORecord | OIDCSSORecord | Directory) => {
if ('deactivated' in connection) {
return connection.deactivated === false;
}
return true;
};
export const validateSortOrder = (sortOrder: unknown) => {
if (sortOrder === null || sortOrder === '') {
return;
}
const _sortOrder = parseInt(sortOrder as string);
if (isNaN(_sortOrder)) {
throw new JacksonError('The field `sortOrder` must be a number.', 400);
}
if (_sortOrder < 0) {
throw new JacksonError('The field `sortOrder` must be a number greater than or equal to 0.', 400);
}
};