jackson/lib/utils.ts

110 lines
3.0 KiB
TypeScript
Raw Normal View History

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
import type { NextApiRequest, NextApiResponse } from 'next';
Admin interface for Jackson (#71) * NextAuth + users providers * Add a temporary fix for verification token - don't use it in production * Admin ui files * Admin controller * getAll db apis * IdP provider page and api route * Fix padding * Style fixes * middleware to check session * Loading state handling * fetcher better response handling * Add new provider form and api route * Tab panel in client add form * Tab switching plus new fields * Flowbite config * darkMode with flowbite * Save config * Update route path to saml * Reusable component for add/edit * cleanup * Set Secret in NextAuth options * Prettier lint changes * Support for delete operation * Link update * PopUp Modal reusable component * Popup confirm before delete * disable SWR revalidation on focus * Display IdP metadata, clientID,secret * Header fixed positioning and style fixes * Filter raw XML in edit mode * Add name field to config * - Edit/New form delta - Split by newline - Route back after POST * Remove flowbite * Remove flowbite [cleanup] * Add description field * updateConfig implementation * Route PATCH to updateConfig * Naming change * Naming Client -> Connection * AddEdit component updates * Omit provider, returns full config * Destructure session first * Change to domain ACL * Delete unused component * Support glob and list of emails for ACL * Delete unused CSS * Update package lock * Remove flowbite from content source * Redirect to admin route * Check session in Layout and redirect to login * Logout in dropdown * vertical alignment * Show status message on save (edit) * Consolidate fields to one long vertical column * GetAll function for SQL and Add CreationDate and Modification Date for Mongo and SQL * Add name as header * Styling and opacity transition for status * Configure button style fix * overflow for smaller viewports and rounded border * Fallback to default behavior of useSession * Store, use and dispose (after signIn) verification token in db * Remove unused class * Rename Connections ➡ Configurations * Handle getAll and getConfig using slug * Better naming * Update fetch paths * Refactor getAllConfig ➡ getConfig (By Id) * Better naming * Rename saml ➡ samlconf * Use light theme by not defaulting to system theme * Path update /samlconf ➡ /saml/config * Fix path * Revert manual changes * getall funcationality and migration script * message * Updating migration file formating * message * Pull and fix package.json and lock file * correcting the migration script formatting * remove file * add new migration files * e2e with playwright * Better naming * Remove comment * Make headless * Run npm install from root * Add e2e steps in workflow * try with separate npm installs * Move higher in the pipeline to test * Fix quote * Rely on npx * fixed migration script formatting * spelling correction * headless for CI but false for local * Use secret * Type fixes for mongo * [skip ci] Swagger annotation for getConfig * Adding migration scriptis for all db's * added migration script to prettierignore * unformat migration script * removing postgress migration files * generate new migration files * remove wrong migration files * Add new migration files for mysql and mariadb * [skip ci] Swagger annotation for updateConfig * Return empty for update op * Update swagger spec * Fix type * Wait for mongo to start * Fix db_engine * Test with pg * Test with POSTGRES_DB env to auto create db * Swap install-deps with install * Use prod build * enable @ts-ignore * Test some fixes * Can be omitted in next-auth v4, uses secret * Move env to playwright config * authDbSeed script needs the db and other secrets * Typo * Bad typo day 😅 * Again typo * Set NEXTAUTH_URL * Use prod build in CI * Prefix the env for seeding * Try with inline * tidying up migration scripts * fixed migration scripts * Set env in actions yml * Remove comma * Target chromium * Prefix the env * Try inline in playwright * print env * Move build to action step * Remove console log * Let env sit on the job level * Add ACL * Fix attribute check * Add name field * add name in metadata preload config * Use postgres * Remove unneeded secret * Remove env/options from mongo service * Fix swagger * Update swagger spec * [skip ci] Fix eslint warning * Add updateConfig test * Add description to preloaded config * [skip ci] cleanup * minor fix * Update comment * Expose PATCH in config api * Added missing validation for clientSecret * Update swagger spec * updated example postgres url, updated deps * Redirect to saml config route * Remove unused pages/routes * Update in package lock * Add primary and secondary colors to tailwind * Swap icon * Remove text-color and apply default theme * Use the primary color from theme * Reusable custom class for btn-primary * Add link-primary reusable class * Use primary secondary colors for main logo * Show error status & color align with primary color * Show product if name is absent * Simplify required attribute setting, 'description' is not required * Make description optional * Fix placeholder text * Swagger updates * Add validation for description * Swagger - add missing status codes & descriptions * Update swagger artifact * Fix styling for status message * revalidate config on successful save * style text highlight globally * Fix cancel button style * Set the main height to 100%-headerHeight, add overflow * removed default ACL, if someone forgets to change it then we might have Tony Stark logging into everyones instances :) * print the arch/platform * Collect platform info * Disable swc and remove platform query steps * Try with custom babel config to disable swc * Add next.js build cache * Refactor step * trying swc * Make name parameter optional * Update form state from backend after save * port 5000 -> 5225 * Handle empty value case for ACL * bumped up version Co-authored-by: Kiran <kiran@boxyhq.com> Co-authored-by: Vishal Lodha <vishal@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com> Co-authored-by: Utkarsh Mehta <ukrocks.mehta@gmail.com>
2022-02-22 19:03:21 +00:00
import micromatch from 'micromatch';
import type { OIDCSSOConnectionWithDiscoveryUrl, OIDCSSOConnectionWithMetadata } from '@boxyhq/saml-jackson';
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
import { JacksonError } from 'npm/src/controller/error';
Pagination fixes (#2347) * `offset` -> `pageOffset`, `limit`-> `pageLimit` * Be backward compatible in API * Cleanup types and handle pagination qs * Cleanup unused code * Import type * Cleanup and fix lint error * Align params for sso-tracer * Move parsing to a common util function * pageLimit shouldn't be optional * Cap pageLimit to max value, split the boolean * Revert typings and assert non null * Refactor var name * Use util function to normalize pagination params across getAll and getByIndex * Normalize offset/limit for dynamo/mongo * Update query params in `FederatedSAMLApps` * Cap to max limit if passed limit is 0 * Sync lock file * Add a 3rd record and supply opts.pageLimit * Normalize offset/limit for mem/redis * Save the 3rd record in the store * Fix getAll tests * Give precedence to standard params over legacy * Use util function * Parse using util function * Refactor * Standardise pagination for `api/v1/dsync/events` * Standardise pagination for api/admin/connections * Standardise pagination for api/admin/directory-sync * Standardise pagination for `api/v1/dsync/groups` * Standardise pagination for `v1/dsync/users`, `v1/dsync/product` * Standardise pagination in fetchByProduct APIs * Update swagger for groups * Fix pagination params definition, add the params for users api * More swagger updates * Swagger spec update for dsync events * Add pagination params to apis fetching by product * Update qs in internal-ui * Remove type assertion * [Swagger WIP] Fix response format for paginated APIs * Add dsync events to swagger spec * Fix swagger spec for sso tracer * Fix swagger spec for federated-saml apps of a product * Update pageLimit to 50 * Use pageLimit value from internal-ui * Update UI SDK * Cleanup local pagination component * Update swagger version * Remove unused keys from locale * Fix tag for trace api spec * Fix param name for swagger * Fix swagger tag for trace * updated package-lock * updated package-lock --------- Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2024-03-06 20:14:14 +00:00
import type { PaginateApiParams } from 'types';
2022-01-08 01:00:06 +00:00
export const validateEmailWithACL = (email: string) => {
Admin interface for Jackson (#71) * NextAuth + users providers * Add a temporary fix for verification token - don't use it in production * Admin ui files * Admin controller * getAll db apis * IdP provider page and api route * Fix padding * Style fixes * middleware to check session * Loading state handling * fetcher better response handling * Add new provider form and api route * Tab panel in client add form * Tab switching plus new fields * Flowbite config * darkMode with flowbite * Save config * Update route path to saml * Reusable component for add/edit * cleanup * Set Secret in NextAuth options * Prettier lint changes * Support for delete operation * Link update * PopUp Modal reusable component * Popup confirm before delete * disable SWR revalidation on focus * Display IdP metadata, clientID,secret * Header fixed positioning and style fixes * Filter raw XML in edit mode * Add name field to config * - Edit/New form delta - Split by newline - Route back after POST * Remove flowbite * Remove flowbite [cleanup] * Add description field * updateConfig implementation * Route PATCH to updateConfig * Naming change * Naming Client -> Connection * AddEdit component updates * Omit provider, returns full config * Destructure session first * Change to domain ACL * Delete unused component * Support glob and list of emails for ACL * Delete unused CSS * Update package lock * Remove flowbite from content source * Redirect to admin route * Check session in Layout and redirect to login * Logout in dropdown * vertical alignment * Show status message on save (edit) * Consolidate fields to one long vertical column * GetAll function for SQL and Add CreationDate and Modification Date for Mongo and SQL * Add name as header * Styling and opacity transition for status * Configure button style fix * overflow for smaller viewports and rounded border * Fallback to default behavior of useSession * Store, use and dispose (after signIn) verification token in db * Remove unused class * Rename Connections ➡ Configurations * Handle getAll and getConfig using slug * Better naming * Update fetch paths * Refactor getAllConfig ➡ getConfig (By Id) * Better naming * Rename saml ➡ samlconf * Use light theme by not defaulting to system theme * Path update /samlconf ➡ /saml/config * Fix path * Revert manual changes * getall funcationality and migration script * message * Updating migration file formating * message * Pull and fix package.json and lock file * correcting the migration script formatting * remove file * add new migration files * e2e with playwright * Better naming * Remove comment * Make headless * Run npm install from root * Add e2e steps in workflow * try with separate npm installs * Move higher in the pipeline to test * Fix quote * Rely on npx * fixed migration script formatting * spelling correction * headless for CI but false for local * Use secret * Type fixes for mongo * [skip ci] Swagger annotation for getConfig * Adding migration scriptis for all db's * added migration script to prettierignore * unformat migration script * removing postgress migration files * generate new migration files * remove wrong migration files * Add new migration files for mysql and mariadb * [skip ci] Swagger annotation for updateConfig * Return empty for update op * Update swagger spec * Fix type * Wait for mongo to start * Fix db_engine * Test with pg * Test with POSTGRES_DB env to auto create db * Swap install-deps with install * Use prod build * enable @ts-ignore * Test some fixes * Can be omitted in next-auth v4, uses secret * Move env to playwright config * authDbSeed script needs the db and other secrets * Typo * Bad typo day 😅 * Again typo * Set NEXTAUTH_URL * Use prod build in CI * Prefix the env for seeding * Try with inline * tidying up migration scripts * fixed migration scripts * Set env in actions yml * Remove comma * Target chromium * Prefix the env * Try inline in playwright * print env * Move build to action step * Remove console log * Let env sit on the job level * Add ACL * Fix attribute check * Add name field * add name in metadata preload config * Use postgres * Remove unneeded secret * Remove env/options from mongo service * Fix swagger * Update swagger spec * [skip ci] Fix eslint warning * Add updateConfig test * Add description to preloaded config * [skip ci] cleanup * minor fix * Update comment * Expose PATCH in config api * Added missing validation for clientSecret * Update swagger spec * updated example postgres url, updated deps * Redirect to saml config route * Remove unused pages/routes * Update in package lock * Add primary and secondary colors to tailwind * Swap icon * Remove text-color and apply default theme * Use the primary color from theme * Reusable custom class for btn-primary * Add link-primary reusable class * Use primary secondary colors for main logo * Show error status & color align with primary color * Show product if name is absent * Simplify required attribute setting, 'description' is not required * Make description optional * Fix placeholder text * Swagger updates * Add validation for description * Swagger - add missing status codes & descriptions * Update swagger artifact * Fix styling for status message * revalidate config on successful save * style text highlight globally * Fix cancel button style * Set the main height to 100%-headerHeight, add overflow * removed default ACL, if someone forgets to change it then we might have Tony Stark logging into everyones instances :) * print the arch/platform * Collect platform info * Disable swc and remove platform query steps * Try with custom babel config to disable swc * Add next.js build cache * Refactor step * trying swc * Make name parameter optional * Update form state from backend after save * port 5000 -> 5225 * Handle empty value case for ACL * bumped up version Co-authored-by: Kiran <kiran@boxyhq.com> Co-authored-by: Vishal Lodha <vishal@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com> Co-authored-by: Utkarsh Mehta <ukrocks.mehta@gmail.com>
2022-02-22 19:03:21 +00:00
const NEXTAUTH_ACL = process.env.NEXTAUTH_ACL || undefined;
if (!NEXTAUTH_ACL) {
return false;
Admin interface for Jackson (#71) * NextAuth + users providers * Add a temporary fix for verification token - don't use it in production * Admin ui files * Admin controller * getAll db apis * IdP provider page and api route * Fix padding * Style fixes * middleware to check session * Loading state handling * fetcher better response handling * Add new provider form and api route * Tab panel in client add form * Tab switching plus new fields * Flowbite config * darkMode with flowbite * Save config * Update route path to saml * Reusable component for add/edit * cleanup * Set Secret in NextAuth options * Prettier lint changes * Support for delete operation * Link update * PopUp Modal reusable component * Popup confirm before delete * disable SWR revalidation on focus * Display IdP metadata, clientID,secret * Header fixed positioning and style fixes * Filter raw XML in edit mode * Add name field to config * - Edit/New form delta - Split by newline - Route back after POST * Remove flowbite * Remove flowbite [cleanup] * Add description field * updateConfig implementation * Route PATCH to updateConfig * Naming change * Naming Client -> Connection * AddEdit component updates * Omit provider, returns full config * Destructure session first * Change to domain ACL * Delete unused component * Support glob and list of emails for ACL * Delete unused CSS * Update package lock * Remove flowbite from content source * Redirect to admin route * Check session in Layout and redirect to login * Logout in dropdown * vertical alignment * Show status message on save (edit) * Consolidate fields to one long vertical column * GetAll function for SQL and Add CreationDate and Modification Date for Mongo and SQL * Add name as header * Styling and opacity transition for status * Configure button style fix * overflow for smaller viewports and rounded border * Fallback to default behavior of useSession * Store, use and dispose (after signIn) verification token in db * Remove unused class * Rename Connections ➡ Configurations * Handle getAll and getConfig using slug * Better naming * Update fetch paths * Refactor getAllConfig ➡ getConfig (By Id) * Better naming * Rename saml ➡ samlconf * Use light theme by not defaulting to system theme * Path update /samlconf ➡ /saml/config * Fix path * Revert manual changes * getall funcationality and migration script * message * Updating migration file formating * message * Pull and fix package.json and lock file * correcting the migration script formatting * remove file * add new migration files * e2e with playwright * Better naming * Remove comment * Make headless * Run npm install from root * Add e2e steps in workflow * try with separate npm installs * Move higher in the pipeline to test * Fix quote * Rely on npx * fixed migration script formatting * spelling correction * headless for CI but false for local * Use secret * Type fixes for mongo * [skip ci] Swagger annotation for getConfig * Adding migration scriptis for all db's * added migration script to prettierignore * unformat migration script * removing postgress migration files * generate new migration files * remove wrong migration files * Add new migration files for mysql and mariadb * [skip ci] Swagger annotation for updateConfig * Return empty for update op * Update swagger spec * Fix type * Wait for mongo to start * Fix db_engine * Test with pg * Test with POSTGRES_DB env to auto create db * Swap install-deps with install * Use prod build * enable @ts-ignore * Test some fixes * Can be omitted in next-auth v4, uses secret * Move env to playwright config * authDbSeed script needs the db and other secrets * Typo * Bad typo day 😅 * Again typo * Set NEXTAUTH_URL * Use prod build in CI * Prefix the env for seeding * Try with inline * tidying up migration scripts * fixed migration scripts * Set env in actions yml * Remove comma * Target chromium * Prefix the env * Try inline in playwright * print env * Move build to action step * Remove console log * Let env sit on the job level * Add ACL * Fix attribute check * Add name field * add name in metadata preload config * Use postgres * Remove unneeded secret * Remove env/options from mongo service * Fix swagger * Update swagger spec * [skip ci] Fix eslint warning * Add updateConfig test * Add description to preloaded config * [skip ci] cleanup * minor fix * Update comment * Expose PATCH in config api * Added missing validation for clientSecret * Update swagger spec * updated example postgres url, updated deps * Redirect to saml config route * Remove unused pages/routes * Update in package lock * Add primary and secondary colors to tailwind * Swap icon * Remove text-color and apply default theme * Use the primary color from theme * Reusable custom class for btn-primary * Add link-primary reusable class * Use primary secondary colors for main logo * Show error status & color align with primary color * Show product if name is absent * Simplify required attribute setting, 'description' is not required * Make description optional * Fix placeholder text * Swagger updates * Add validation for description * Swagger - add missing status codes & descriptions * Update swagger artifact * Fix styling for status message * revalidate config on successful save * style text highlight globally * Fix cancel button style * Set the main height to 100%-headerHeight, add overflow * removed default ACL, if someone forgets to change it then we might have Tony Stark logging into everyones instances :) * print the arch/platform * Collect platform info * Disable swc and remove platform query steps * Try with custom babel config to disable swc * Add next.js build cache * Refactor step * trying swc * Make name parameter optional * Update form state from backend after save * port 5000 -> 5225 * Handle empty value case for ACL * bumped up version Co-authored-by: Kiran <kiran@boxyhq.com> Co-authored-by: Vishal Lodha <vishal@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com> Co-authored-by: Utkarsh Mehta <ukrocks.mehta@gmail.com>
2022-02-22 19:03:21 +00:00
}
const acl = NEXTAUTH_ACL.split(',');
return micromatch.isMatch(email, acl);
Admin interface for Jackson (#71) * NextAuth + users providers * Add a temporary fix for verification token - don't use it in production * Admin ui files * Admin controller * getAll db apis * IdP provider page and api route * Fix padding * Style fixes * middleware to check session * Loading state handling * fetcher better response handling * Add new provider form and api route * Tab panel in client add form * Tab switching plus new fields * Flowbite config * darkMode with flowbite * Save config * Update route path to saml * Reusable component for add/edit * cleanup * Set Secret in NextAuth options * Prettier lint changes * Support for delete operation * Link update * PopUp Modal reusable component * Popup confirm before delete * disable SWR revalidation on focus * Display IdP metadata, clientID,secret * Header fixed positioning and style fixes * Filter raw XML in edit mode * Add name field to config * - Edit/New form delta - Split by newline - Route back after POST * Remove flowbite * Remove flowbite [cleanup] * Add description field * updateConfig implementation * Route PATCH to updateConfig * Naming change * Naming Client -> Connection * AddEdit component updates * Omit provider, returns full config * Destructure session first * Change to domain ACL * Delete unused component * Support glob and list of emails for ACL * Delete unused CSS * Update package lock * Remove flowbite from content source * Redirect to admin route * Check session in Layout and redirect to login * Logout in dropdown * vertical alignment * Show status message on save (edit) * Consolidate fields to one long vertical column * GetAll function for SQL and Add CreationDate and Modification Date for Mongo and SQL * Add name as header * Styling and opacity transition for status * Configure button style fix * overflow for smaller viewports and rounded border * Fallback to default behavior of useSession * Store, use and dispose (after signIn) verification token in db * Remove unused class * Rename Connections ➡ Configurations * Handle getAll and getConfig using slug * Better naming * Update fetch paths * Refactor getAllConfig ➡ getConfig (By Id) * Better naming * Rename saml ➡ samlconf * Use light theme by not defaulting to system theme * Path update /samlconf ➡ /saml/config * Fix path * Revert manual changes * getall funcationality and migration script * message * Updating migration file formating * message * Pull and fix package.json and lock file * correcting the migration script formatting * remove file * add new migration files * e2e with playwright * Better naming * Remove comment * Make headless * Run npm install from root * Add e2e steps in workflow * try with separate npm installs * Move higher in the pipeline to test * Fix quote * Rely on npx * fixed migration script formatting * spelling correction * headless for CI but false for local * Use secret * Type fixes for mongo * [skip ci] Swagger annotation for getConfig * Adding migration scriptis for all db's * added migration script to prettierignore * unformat migration script * removing postgress migration files * generate new migration files * remove wrong migration files * Add new migration files for mysql and mariadb * [skip ci] Swagger annotation for updateConfig * Return empty for update op * Update swagger spec * Fix type * Wait for mongo to start * Fix db_engine * Test with pg * Test with POSTGRES_DB env to auto create db * Swap install-deps with install * Use prod build * enable @ts-ignore * Test some fixes * Can be omitted in next-auth v4, uses secret * Move env to playwright config * authDbSeed script needs the db and other secrets * Typo * Bad typo day 😅 * Again typo * Set NEXTAUTH_URL * Use prod build in CI * Prefix the env for seeding * Try with inline * tidying up migration scripts * fixed migration scripts * Set env in actions yml * Remove comma * Target chromium * Prefix the env * Try inline in playwright * print env * Move build to action step * Remove console log * Let env sit on the job level * Add ACL * Fix attribute check * Add name field * add name in metadata preload config * Use postgres * Remove unneeded secret * Remove env/options from mongo service * Fix swagger * Update swagger spec * [skip ci] Fix eslint warning * Add updateConfig test * Add description to preloaded config * [skip ci] cleanup * minor fix * Update comment * Expose PATCH in config api * Added missing validation for clientSecret * Update swagger spec * updated example postgres url, updated deps * Redirect to saml config route * Remove unused pages/routes * Update in package lock * Add primary and secondary colors to tailwind * Swap icon * Remove text-color and apply default theme * Use the primary color from theme * Reusable custom class for btn-primary * Add link-primary reusable class * Use primary secondary colors for main logo * Show error status & color align with primary color * Show product if name is absent * Simplify required attribute setting, 'description' is not required * Make description optional * Fix placeholder text * Swagger updates * Add validation for description * Swagger - add missing status codes & descriptions * Update swagger artifact * Fix styling for status message * revalidate config on successful save * style text highlight globally * Fix cancel button style * Set the main height to 100%-headerHeight, add overflow * removed default ACL, if someone forgets to change it then we might have Tony Stark logging into everyones instances :) * print the arch/platform * Collect platform info * Disable swc and remove platform query steps * Try with custom babel config to disable swc * Add next.js build cache * Refactor step * trying swc * Make name parameter optional * Update form state from backend after save * port 5000 -> 5225 * Handle empty value case for ACL * bumped up version Co-authored-by: Kiran <kiran@boxyhq.com> Co-authored-by: Vishal Lodha <vishal@boxyhq.com> Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com> Co-authored-by: Utkarsh Mehta <ukrocks.mehta@gmail.com>
2022-02-22 19:03:21 +00:00
};
/**
* This sets `cookie` using the `res` object
*/
export const setErrorCookie = (res: NextApiResponse, value: unknown, options: { path?: string } = {}) => {
const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
let cookieContents = 'jackson_error' + '=' + stringValue;
if (options.path) {
cookieContents += '; Path=' + options.path;
}
res.setHeader('Set-Cookie', cookieContents);
};
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
const IsJsonString = (body: any): boolean => {
try {
const json = JSON.parse(body);
return typeof json === 'object';
} catch (e) {
return false;
}
};
export const bodyParser = (req: NextApiRequest): any => {
return IsJsonString(req.body) ? JSON.parse(req.body) : req.body;
};
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 strategyChecker = (req: NextApiRequest): { isSAML: boolean; isOIDC: boolean } => {
const isSAML =
'rawMetadata' in req.body ||
'encodedRawMetadata' in req.body ||
'metadataUrl' in req.body ||
'isSAML' in req.body;
const isOIDC = 'oidcDiscoveryUrl' in req.body || 'oidcMetadata' in req.body || 'isOIDC' in req.body;
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
return { isSAML, isOIDC };
};
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
// The oidcMetadata JSON will be parsed here
export const oidcMetadataParse = (
body: (
| OIDCSSOConnectionWithDiscoveryUrl
| (Omit<OIDCSSOConnectionWithMetadata, 'oidcMetadata'> & { oidcMetadata: string })
) & {
clientID: string;
clientSecret: string;
}
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 (!body.oidcDiscoveryUrl && typeof body.oidcMetadata === 'string') {
try {
const oidcMetadata = JSON.parse(body.oidcMetadata);
return { ...body, oidcMetadata };
} catch (err) {
throw new JacksonError('Could not parse OIDC Provider metadata, expected a valid JSON string', 400);
}
}
return body;
};
Pagination fixes (#2347) * `offset` -> `pageOffset`, `limit`-> `pageLimit` * Be backward compatible in API * Cleanup types and handle pagination qs * Cleanup unused code * Import type * Cleanup and fix lint error * Align params for sso-tracer * Move parsing to a common util function * pageLimit shouldn't be optional * Cap pageLimit to max value, split the boolean * Revert typings and assert non null * Refactor var name * Use util function to normalize pagination params across getAll and getByIndex * Normalize offset/limit for dynamo/mongo * Update query params in `FederatedSAMLApps` * Cap to max limit if passed limit is 0 * Sync lock file * Add a 3rd record and supply opts.pageLimit * Normalize offset/limit for mem/redis * Save the 3rd record in the store * Fix getAll tests * Give precedence to standard params over legacy * Use util function * Parse using util function * Refactor * Standardise pagination for `api/v1/dsync/events` * Standardise pagination for api/admin/connections * Standardise pagination for api/admin/directory-sync * Standardise pagination for `api/v1/dsync/groups` * Standardise pagination for `v1/dsync/users`, `v1/dsync/product` * Standardise pagination in fetchByProduct APIs * Update swagger for groups * Fix pagination params definition, add the params for users api * More swagger updates * Swagger spec update for dsync events * Add pagination params to apis fetching by product * Update qs in internal-ui * Remove type assertion * [Swagger WIP] Fix response format for paginated APIs * Add dsync events to swagger spec * Fix swagger spec for sso tracer * Fix swagger spec for federated-saml apps of a product * Update pageLimit to 50 * Use pageLimit value from internal-ui * Update UI SDK * Cleanup local pagination component * Update swagger version * Remove unused keys from locale * Fix tag for trace api spec * Fix param name for swagger * Fix swagger tag for trace * updated package-lock * updated package-lock --------- Co-authored-by: Deepak Prabhakara <deepak@boxyhq.com>
2024-03-06 20:14:14 +00:00
export const parsePaginateApiParams = (params: NextApiRequest['query']): PaginateApiParams => {
let pageOffset, pageLimit;
if ('pageOffset' in params) {
pageOffset = params.pageOffset;
} else if ('offset' in params) {
pageOffset = params.offset;
}
if ('pageLimit' in params) {
pageLimit = params.pageLimit;
} else if ('limit' in params) {
pageLimit = params.limit;
}
pageOffset = parseInt(pageOffset);
pageLimit = parseInt(pageLimit);
const pageToken = params.pageToken as string;
return {
pageOffset,
pageLimit,
pageToken,
};
};
export type AdminPortalSSODefaults = {
tenant: string;
product: string;
redirectUrl: string[];
defaultRedirectUrl: string;
};