Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extensibility as custom phone provider deploy cli support #1038

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/context/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,21 @@ export function emailProviderDefaults(emailProvider) {

return updated;
}

export function phoneProviderDefaults(phoneProvider) {
// eslint-disable-line
Copy link
Contributor

@kushalshit27 kushalshit27 Feb 27, 2025

Choose a reason for hiding this comment

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

why using @ts-ignore?

const updated = { ...phoneProvider };

const apiKeyProviders = ['twilio'];

// Add placeholder for credentials as they cannot be exported
const { name } = updated;

if (apiKeyProviders.includes(name)) {
updated.credentials = {
auth_token: `##${name.toUpperCase()}_AUTH_TOKEN##`,
...(updated.credentials || {}),
};
}
return updated;
}
2 changes: 2 additions & 0 deletions src/context/directory/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import organizations from './organizations';
import triggers from './triggers';
import attackProtection from './attackProtection';
import branding from './branding';
import phoneProviders from './phoneProvider';
import logStreams from './logStreams';
import prompts from './prompts';
import customDomains from './customDomains';
Expand Down Expand Up @@ -66,6 +67,7 @@ const directoryHandlers: {
triggers,
attackProtection,
branding,
phoneProviders,
logStreams,
prompts,
customDomains,
Expand Down
50 changes: 50 additions & 0 deletions src/context/directory/handlers/phoneProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import path from 'path';
import fs from 'fs-extra';
import { constants } from '../../../tools';

import { existsMustBeDir, isFile, dumpJSON, loadJSON } from '../../../utils';
import { DirectoryHandler } from '.';
import DirectoryContext from '..';
import { ParsedAsset } from '../../../types';
import { PhoneProvider } from '../../../tools/auth0/handlers/phoneProvider';

type ParsedPhoneProvider = ParsedAsset<'phoneProviders', PhoneProvider[]>;

function parse(context: DirectoryContext): ParsedPhoneProvider {
const phoneProvidersFolder = path.join(context.filePath, constants.PHONE_PROVIDER_DIRECTORY);
if (!existsMustBeDir(phoneProvidersFolder)) return { phoneProviders: null }; // Skip

const providerFile = path.join(phoneProvidersFolder, 'provider.json');

if (isFile(providerFile)) {
return {
phoneProviders: loadJSON(providerFile, {
mappings: context.mappings,
disableKeywordReplacement: context.disableKeywordReplacement,
}),
};
}

return { phoneProviders: null };
}

async function dump(context: DirectoryContext): Promise<void> {
const { phoneProviders } = context.assets;
if (!phoneProviders) {
return;
}// Skip, nothing to dump

const phoneProvidersFolder = path.join(context.filePath, constants.PHONE_PROVIDER_DIRECTORY);
fs.ensureDirSync(phoneProvidersFolder);

const phoneProviderFile = path.join(phoneProvidersFolder, 'provider.json');
// @ts-ignore
Copy link
Contributor

@kushalshit27 kushalshit27 Feb 27, 2025

Choose a reason for hiding this comment

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

why using @ts-ignore?

dumpJSON(phoneProviderFile, phoneProviders.map(({ created_at, updated_at, tenant, channel, credentials, ...rest }) => rest));
}

const phoneProvidersHandler: DirectoryHandler<ParsedPhoneProvider> = {
parse,
dump,
};

export default phoneProvidersHandler;
2 changes: 2 additions & 0 deletions src/context/yaml/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import actions from './actions';
import triggers from './triggers';
import attackProtection from './attackProtection';
import branding from './branding';
import phoneProviders from './phoneProvider';
import logStreams from './logStreams';
import prompts from './prompts';
import customDomains from './customDomains';
Expand Down Expand Up @@ -64,6 +65,7 @@ const yamlHandlers: { [key in AssetTypes]: YAMLHandler<{ [key: string]: unknown
triggers,
attackProtection,
branding,
phoneProviders,
logStreams,
prompts,
customDomains,
Expand Down
36 changes: 36 additions & 0 deletions src/context/yaml/handlers/phoneProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { YAMLHandler } from '.';
import YAMLContext from '..';
import { PhoneProvider } from '../../../tools/auth0/handlers/phoneProvider';
import { ParsedAsset } from '../../../types';

type ParsedPhoneProviders = ParsedAsset<'phoneProviders', PhoneProvider[] >;

async function parse(context: YAMLContext): Promise<ParsedPhoneProviders> {
const { phoneProviders } = context.assets;

if (!phoneProviders) return { phoneProviders: null };

console.log(phoneProviders);

return {
phoneProviders,
};
}

async function dump(context: YAMLContext): Promise<ParsedPhoneProviders> {
if (!context.assets.phoneProviders) return { phoneProviders: null };

const { phoneProviders } = context.assets;

return {
// @ts-ignore
phoneProviders: phoneProviders.map(({ created_at, updated_at, tenant, channel, credentials, ...rest }) => rest)
};
}

const phoneProviderHandler: YAMLHandler<ParsedPhoneProviders> = {
parse,
dump,
};

export default phoneProviderHandler;
10 changes: 0 additions & 10 deletions src/tools/auth0/handlers/emailProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { EmailProviderCreate } from 'auth0';
import { isEmpty } from 'lodash';
import DefaultHandler, { order } from './default';
import { Asset, Assets } from '../../../types';
import log from '../../../logger';

export const schema = { type: 'object' };

Expand Down Expand Up @@ -46,7 +45,6 @@ export default class EmailProviderHandler extends DefaultHandler {
if (Object.keys(emailProvider).length === 0) {
if (this.config('AUTH0_ALLOW_DELETE') === true) {
// await this.client.emails.delete(); is not supported
existing.enabled = false;
if (isEmpty(existing.credentials)) {
delete existing.credentials;
}
Expand All @@ -57,14 +55,6 @@ export default class EmailProviderHandler extends DefaultHandler {
return;
}

if (existing.name) {
if (existing.name !== emailProvider.name) {
// Delete the current provider as it's different
// await this.client.emailProvider.delete(); is not supported
existing.enabled = false;
}
}

if (existing.name) {
const updated = await this.client.emails.update(emailProvider);
this.updated += 1;
Expand Down
2 changes: 2 additions & 0 deletions src/tools/auth0/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as guardianPhoneFactorSelectedProvider from './guardianPhoneFactorSelec
import * as guardianPhoneFactorMessageTypes from './guardianPhoneFactorMessageTypes';
import * as roles from './roles';
import * as branding from './branding';
import * as phoneProviders from './phoneProvider';
import * as prompts from './prompts';
import * as actions from './actions';
import * as triggers from './triggers';
Expand Down Expand Up @@ -55,6 +56,7 @@ const auth0ApiHandlers: { [key in AssetTypes]: any } = {
guardianPhoneFactorMessageTypes,
roles,
branding,
phoneProviders,
//@ts-ignore because prompts have not been universally implemented yet
prompts,
actions,
Expand Down
201 changes: 201 additions & 0 deletions src/tools/auth0/handlers/phoneProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import {
CreatePhoneProviderRequest,
DeletePhoneProviderRequest,
GetBrandingPhoneProviders200ResponseProvidersInner,
UpdatePhoneProviderOperationRequest
} from 'auth0';
import DefaultHandler, { order } from './default';
import { Assets } from '../../../types';
import log from '../../../logger';

export type PhoneProvider = GetBrandingPhoneProviders200ResponseProvidersInner;
export default class PhoneProviderHandler extends DefaultHandler {
existing: PhoneProvider[] | null;

constructor(options: DefaultHandler) {
super({
...options,
type: 'phoneProviders',
id: 'id',
});
}

objString(provider: PhoneProvider) : string {
return super.objString({ name: provider.name, disabled: provider.disabled }); //Que
}

async getType(): Promise<PhoneProvider[] | null> {
if (!this.existing) {
this.existing = await this.getPhoneProviders();
}

return this.existing;
}

async getPhoneProviders(): Promise<PhoneProvider[] | null> {
const { data: response } = await this.client.branding.getAllPhoneProviders();
return response.providers ?? [];
}

@order('60')
async processChanges(assets: Assets): Promise<void> {
const { phoneProviders } = assets;

// Non-existing section means themes doesn't need to be processed
if (!phoneProviders) return;

// Empty array means themes should be deleted
if (phoneProviders.length === 0) {
return this.deletePhoneProviders();
}

return this.updatePhoneProviders(phoneProviders);
}

async deletePhoneProviders(): Promise<void> {
if (!this.config('AUTH0_ALLOW_DELETE')) {
return;
}

// if phone providers exists we need to delete it
const currentProviders = await this.getPhoneProviders();
if (currentProviders === null || currentProviders.length === 0) {
return;
}

const currentProvider = currentProviders[0];
await this.client.branding.deletePhoneProvider(<DeletePhoneProviderRequest>{ id: currentProvider.id });
// await this.client.branding.deletePhoneProvider({ 'id': currentProvider.id }); //Quee

this.deleted += 1;
this.didDelete(currentProvider);
}

async updatePhoneProviders(phoneProviders: PhoneProvider[]): Promise<void> {
if (phoneProviders.length > 1) {
log.warn('Currently only one phone provider is supported per tenant');
}

const currentProviders = await this.getPhoneProviders();

const providerReqPayload = ((): Omit<PhoneProvider, 'id'> => {
// Removing id from update and create payloads, otherwise API will error
// id may be required to handle if `--export_ids=true`
const payload = phoneProviders[0];
// @ts-ignore to quell non-optional id property, but we know that it's ok to delete
delete payload.id;
return payload;
})();

if (currentProviders === null || currentProviders.length === 0) {
// if provider does not exist, create it
await this.client.branding.configurePhoneProvider(providerReqPayload as CreatePhoneProviderRequest);
} else {
const currentProvider = currentProviders[0];
// if provider exists, overwrite it
this.created += 1;
await this.client.branding.updatePhoneProvider({ id: currentProvider.id } as UpdatePhoneProviderOperationRequest, providerReqPayload);
}

this.updated += 1;
this.didUpdate(phoneProviders[0]);
}
}

const TwilioCredentialsSchema = {
type: 'object',
required: ['auth_token'],
properties: {
auth_token: {
type: 'string',
minLength: 1,
maxLength: 255,
},
},
additionalProperties: false,
};

const TwilioConfigurationSchema = {
type: 'object',
required: ['sid', 'delivery_methods'],
additionalProperties: false,
properties: {
default_from: {
type: 'string',
},
mssid: {
type: 'string',
},
sid: {
type: 'string',
},
delivery_methods: {
type: 'array',
items: {
type: 'string',
enum: ['text', 'voice'],
},
minItems: 1,
uniqueItems: true,
},
},
};

const CustomCredentialsSchema = {
type: 'object',
additionalProperties: false,
properties: {},
};

const CustomConfigurationSchema = {
type: 'object',
additionalProperties: false,
required: ['delivery_methods'],
properties: {
delivery_methods: {
type: 'array',
items: {
type: 'string',
enum: ['text', 'voice'],
},
minItems: 1,
uniqueItems: true,
},
},
};

export const schema = {
type: 'array',
description: 'List of phone provider configurations',
items: {
type: 'object',
properties: {
id: {
type: 'string',
minLength: 1,
maxLength: 255,
},
name: {
type: 'string',
description: 'Name of the phone notification provider',
enum: ['twilio', 'custom'],
minLength: 1,
maxLength: 100,
},
disabled: {
type: 'boolean',
description: 'Whether the provider is enabled (false) or disabled (true).',
defaultValue: false,
},
configuration: {
type: 'object',
anyOf: [TwilioConfigurationSchema, CustomConfigurationSchema],
},
credentials: {
description: 'Provider credentials required to authenticate to the provider.',
anyOf: [TwilioCredentialsSchema, CustomCredentialsSchema],
},
},
additionalProperties: false,
},
};
1 change: 1 addition & 0 deletions src/tools/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ const constants = {
CLIENTS_DIRECTORY: 'clients',
CLIENTS_GRANTS_DIRECTORY: 'grants',
BRANDING_DIRECTORY: 'branding',
PHONE_PROVIDER_DIRECTORY: 'phone-providers',
BRANDING_TEMPLATES_DIRECTORY: 'templates',
BRANDING_TEMPLATES_YAML_DIRECTORY: 'branding_templates',
CLIENTS_CLIENT_NAME: 'clients',
Expand Down
Loading