diff --git a/.changeset/source-connectors.md b/.changeset/source-connectors.md new file mode 100644 index 0000000..99f5306 --- /dev/null +++ b/.changeset/source-connectors.md @@ -0,0 +1,5 @@ +--- +'@open-iga/aws': patch +--- + +Differentiate source and sink connector to support onboarding HR systems \ No newline at end of file diff --git a/README.md b/README.md index c4e5d66..f0fe5da 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,19 @@ bun run typecheck # type-check app and test sources ## Writing a connector A connector is plain TypeScript that defines its capabilities against `@open-iga/connector-sdk` and -is compiled to WASM by the same toolchain. It declares: +is compiled to WASM by the same toolchain. Its `type` is either `sink` (a system OpenIGA provisions +into) or `source` (a system of record OpenIGA reads people from). + +A `sink` connector declares: - **Account actions** — lifecycle operations on a managed resource (`create`, `read`, `update`, `enable`, `disable`, `delete`). - **Entitlements** — `discover`, `grant`, `revoke` and `read` for assignable permissions (e.g. IAM groups). +A `source` connector declares: + +- **Identities** — a paged `list` of people (e.g. employees). + See `connectors/aws` for a complete reference implementation. ## Roadmap diff --git a/connectors/aws/src/aws-connector.ts b/connectors/aws/src/aws-connector.ts index 83c7cce..d528c6f 100644 --- a/connectors/aws/src/aws-connector.ts +++ b/connectors/aws/src/aws-connector.ts @@ -10,6 +10,7 @@ import { registerIamUserGroupsRevoke } from './entitlements/iam-user-groups/revo import { registerIamUserGroupsRead } from './entitlements/iam-user-groups/read.ts'; export const awsConnector = new OpenIgaConnector({ + type: 'sink', name: 'AWS', description: 'AWS plugin for OpenIGA core', config: [ diff --git a/packages/connector-sdk/lib/bun-plugin/validation/manifest.test.ts b/packages/connector-sdk/lib/bun-plugin/validation/manifest.test.ts index c9e6115..b38c264 100644 --- a/packages/connector-sdk/lib/bun-plugin/validation/manifest.test.ts +++ b/packages/connector-sdk/lib/bun-plugin/validation/manifest.test.ts @@ -2,12 +2,12 @@ import { describe, it, expect } from 'bun:test'; import { validateConfigPlaceHolder, validateAndGenerateConnectorManifest } from './manifest.ts'; import { OpenIgaConnector } from '../../iga/connector/builder.ts'; import type { ConnectorConfig } from '../../iga/connector/validation-schema/connector.config.schema.ts'; -import type { ConnectorAccountAction } from '../../iga/connector/validation-schema/connector.account-action.schema.ts'; +import type { ConnectorOperation } from '../../iga/connector/validation-schema/connector.operation.schema.ts'; const config = (entries: { name: string; required: boolean }[]): ConnectorConfig => entries.map(({ name, required }) => ({ name, description: name, required })); -const endpoints = (urls: string[]): ConnectorAccountAction['endpoints'] => +const endpoints = (urls: string[]): ConnectorOperation['endpoints'] => urls.map((url) => ({ method: 'GET', url, description: 'endpoint' })); describe('validateConfigPlaceHolder', () => { @@ -55,6 +55,7 @@ describe('validateAndGenerateConnectorManifest', () => { it('should throw error when connector settings is invalid', () => { const connector = new OpenIgaConnector({ + type: 'sink', // Invalid: name must be a non-empty string name: '', description: 'desc', @@ -62,11 +63,14 @@ describe('validateAndGenerateConnectorManifest', () => { allowedDomains: ['domain.com'], }); - expect(() => validateAndGenerateConnectorManifest(connector)).toThrow(/Validation Failed for connector setting/); + expect(() => validateAndGenerateConnectorManifest(connector)).toThrow( + /Validation Failed for connector setting/, + ); }); it('should throw error when connector action details are invalid', () => { const connector = new OpenIgaConnector({ + type: 'sink', name: 'connector', description: 'desc', config: [{ name: 'REGION', description: 'region', required: true }], @@ -84,8 +88,49 @@ describe('validateAndGenerateConnectorManifest', () => { ); }); + it('should enforce the operations allowed for each connector type', () => { + const settings = { name: 'connector', description: 'desc', config: [], allowedDomains: ['domain.com'] }; + const operation = { + type: 'list' as const, + description: 'list', + endpoints: endpoints(['https://domain.com']), + handler: () => ({}) as never, + }; + const source = new OpenIgaConnector({ ...settings, type: 'source' }); + const sink = new OpenIgaConnector({ ...settings, type: 'sink' }); + + // @ts-expect-error a source connector cannot register account actions + source.registerAccountActions('employee', operation); + // @ts-expect-error a sink connector cannot register identities + sink.registerIdentities('employee', operation); + + expect(() => validateAndGenerateConnectorManifest(source)).toThrow(/source connector cannot register/); + expect(() => validateAndGenerateConnectorManifest(sink)).toThrow(/sink connector cannot register/); + }); + + it('should list the identities of a source connector in the manifest', () => { + const connector = new OpenIgaConnector({ + type: 'source', + name: 'connector', + description: 'desc', + config: [], + allowedDomains: ['domain.com'], + }).registerIdentities('employee', { + type: 'list', + description: 'list employees', + endpoints: endpoints(['https://domain.com']), + handler: () => ({ identities: [] }), + }); + + const manifest = validateAndGenerateConnectorManifest(connector); + + expect(manifest.type).toBe('source'); + expect(Object.keys(manifest.identities)).toEqual(['employee']); + }); + it('should generate a manifest for a valid connector', () => { const connector = new OpenIgaConnector({ + type: 'sink', name: 'connector', description: 'desc', config: [{ name: 'REGION', description: 'region', required: true }], diff --git a/packages/connector-sdk/lib/bun-plugin/validation/manifest.ts b/packages/connector-sdk/lib/bun-plugin/validation/manifest.ts index 9115832..2e92ffe 100644 --- a/packages/connector-sdk/lib/bun-plugin/validation/manifest.ts +++ b/packages/connector-sdk/lib/bun-plugin/validation/manifest.ts @@ -1,12 +1,17 @@ import { - type ConnectorAccountAction, connectorAccountActionSchema, -} from '../../iga/connector/validation-schema/connector.account-action.schema.ts'; -import { connectorEntitlementSchema } from '../../iga/connector/validation-schema/connector.entitlement.schema.ts'; + connectorEntitlementSchema, + connectorIdentitySchema, + type ConnectorOperation, +} from '../../iga/connector/validation-schema/connector.operation.schema.ts'; import { z } from 'zod/mini'; import type { ConnectorConfig } from '../../iga/connector/validation-schema/connector.config.schema.ts'; import { OpenIgaConnector } from '../../iga/connector/builder.ts'; -import { connectorSettingsSchema } from '../../iga/connector/validation-schema/connector.settings.schema.ts'; +import { + type ConnectorSettings, + type ConnectorType, + connectorSettingsSchema, +} from '../../iga/connector/validation-schema/connector.settings.schema.ts'; /** * Config Template Placeholders regex @@ -15,17 +20,19 @@ const CONFIG_PLACEHOLDERS = /\{\{\s*([A-Za-z0-9_-]+)\s*\}\}/g; // One primitive (create/enable/.../grant/...) as exposed in the manifest. The managed // resource and the operation type are the keys, so they are not repeated inside. -type ManifestOperation = Pick, 'description' | 'endpoints' | 'config'>; +type ManifestOperation = Pick; // Keyed by managed resource, then by operation type: // actions: { "iam-user": { "create": {...}, "enable": {...} } } type Manifest = { + type: ConnectorType; name: string; description: string; config: ConnectorConfig; allowedDomains: string[]; actions: Record>; entitlements: Record>; + identities: Record>; }; /** @@ -36,7 +43,7 @@ export const validateConfigPlaceHolder = ({ endpoints, config, }: { - endpoints: ConnectorAccountAction['endpoints']; + endpoints: ConnectorOperation['endpoints']; config: ConnectorConfig; }) => { const userDefinedConfigSet = new Map(config.map(({ name, required }) => [name, required])); @@ -65,6 +72,41 @@ export const validateConfigPlaceHolder = ({ } }; +// Validates one registry and shapes it as managed resource → operation type → operation. +const buildManifestOperations = ({ + kind, + registry, + schema, + connectorConfig, +}: { + kind: string; + registry: Map>; + schema: typeof connectorAccountActionSchema | typeof connectorEntitlementSchema | typeof connectorIdentitySchema; + connectorConfig: ConnectorSettings['config']; +}): Record> => { + // Null-prototype records: managedResource is an arbitrary key, so `actions["__proto__"]` etc. + // must not resolve to an inherited value (would drop the op and mutate Object.prototype). + const operations: Record> = Object.create(null); + + for (const [managedResource, operationByType] of registry) { + for (const [type, operation] of operationByType) { + const result = schema.safeParse(operation); + if (!result.success) { + throw new Error( + `Validation failed for ${kind} type ${type} in the managed resource ${managedResource}. Reason: ${z.prettifyError(result.error)}`, + ); + } + + const { endpoints, description, config } = result.data; + + validateConfigPlaceHolder({ endpoints, config: [...connectorConfig, ...(config ?? [])] }); + (operations[managedResource] ??= {})[type] = { endpoints, description, config: config ?? [] }; + } + } + + return operations; +}; + /** * There are two levels of validation: build and runtime * Build-time validates the registry. Runtime is part of dispatcher that sits between the host and the connector @@ -79,53 +121,40 @@ export const validateAndGenerateConnectorManifest = (connector: unknown): Manife throw new Error(`Validation Failed for connector setting. Reason: ${z.prettifyError(settingsResult.error)}`); } - const { name, config, description, allowedDomains } = settingsResult.data; - // Null-prototype records: managedResource is an arbitrary key, so `actions["__proto__"]` etc. - // must not resolve to an inherited value (would drop the op and mutate Object.prototype). - const manifest: Manifest = { + const { type, name, config, description, allowedDomains } = settingsResult.data; + + // The register methods are typed per connector type; this catches casts and untyped connectors. + const sinkOperationCount = connector.accountActionsRegistry.size + connector.entitlementRegistry.size; + const mismatchedCount = type === 'source' ? sinkOperationCount : connector.identityRegistry.size; + if (mismatchedCount > 0) { + throw new Error( + `A ${type} connector cannot register ${type === 'source' ? 'account actions or entitlements' : 'identities'}`, + ); + } + + return { + type, name, description, config, allowedDomains, - actions: Object.create(null), - entitlements: Object.create(null), + actions: buildManifestOperations({ + kind: 'action', + registry: connector.accountActionsRegistry, + schema: connectorAccountActionSchema, + connectorConfig: config, + }), + entitlements: buildManifestOperations({ + kind: 'entitlement', + registry: connector.entitlementRegistry, + schema: connectorEntitlementSchema, + connectorConfig: config, + }), + identities: buildManifestOperations({ + kind: 'identity', + registry: connector.identityRegistry, + schema: connectorIdentitySchema, + connectorConfig: config, + }), }; - - for (const [managedResource, accountActionConfig] of connector.accountActionsRegistry) { - for (const [actionType, action] of accountActionConfig) { - const result = connectorAccountActionSchema.safeParse(action); - if (!result.success) { - throw new Error( - `Validation failed for action type ${actionType} in the managed resource ${managedResource}. Reason: ${z.prettifyError(result.error)}`, - ); - } - - const { endpoints, description, config } = result.data; - - validateConfigPlaceHolder({ endpoints, config: [...settingsResult.data.config, ...(config ?? [])] }); - (manifest.actions[managedResource] ??= {})[actionType] = { endpoints, description, config: config ?? [] }; - } - } - - for (const [managedResource, entitlementConfig] of connector.entitlementRegistry) { - for (const [entitlementType, entitlement] of entitlementConfig) { - const result = connectorEntitlementSchema.safeParse(entitlement); - if (!result.success) { - throw new Error( - `Validation failed for entitlement type ${entitlementType} in the managed resource ${managedResource}. Reason: ${z.prettifyError(result.error)}`, - ); - } - - const { endpoints, description, config } = result.data; - - validateConfigPlaceHolder({ endpoints, config: [...settingsResult.data.config, ...(config ?? [])] }); - (manifest.entitlements[managedResource] ??= {})[entitlementType] = { - endpoints, - description, - config: config ?? [], - }; - } - } - - return manifest; }; diff --git a/packages/connector-sdk/lib/iga/connector/builder.ts b/packages/connector-sdk/lib/iga/connector/builder.ts index c1f9a0c..0f6067d 100644 --- a/packages/connector-sdk/lib/iga/connector/builder.ts +++ b/packages/connector-sdk/lib/iga/connector/builder.ts @@ -1,10 +1,15 @@ -import type { ConnectorAccountAction } from './validation-schema/connector.account-action.schema.ts'; +import type { + ConnectorAccountAction, + ConnectorEntitlement, + ConnectorIdentity, + ConnectorOperation, +} from './validation-schema/connector.operation.schema.ts'; import type { ConnectorConfig } from './validation-schema/connector.config.schema.ts'; import type { handlerInputOutputSchema } from './validation-schema/connector.account-action-handler.schema.ts'; -import type { ConnectorEntitlement } from './validation-schema/connector.entitlement.schema.ts'; import type { entitlementHandlerInputOutputSchema } from './validation-schema/connector.entitlement-handler.schema.ts'; import type * as z from 'zod/mini'; -import type { ConnectorSettings } from './validation-schema/connector.settings.schema.ts'; +import type { ConnectorSettings, ConnectorType } from './validation-schema/connector.settings.schema.ts'; +import type { identityHandlerInputOutputSchema } from './validation-schema/connector.identity-handler.schema.ts'; type SimplifiedRuntimeConfig = { [Property in keyof Type]: Type[Property] }; export type RuntimeConfig = SimplifiedRuntimeConfig< @@ -15,55 +20,73 @@ export type RuntimeConfig = Si } >; -export type AccountAction< - Config extends ConnectorConfig = ConnectorConfig, - ActionConfig extends ConnectorConfig = [], - Type extends ConnectorAccountAction['type'] = ConnectorAccountAction['type'], -> = Pick & { +// Shape shared by every operation; the handler is typed by the schemas of its operation type. +type Operation< + Type, + Schema extends { input: z.ZodMiniType; output: z.ZodMiniType }, + Config extends ConnectorConfig, + ActionConfig extends ConnectorConfig, +> = Pick & { type: Type; config?: ActionConfig; handler: (context: { - input: z.infer<(typeof handlerInputOutputSchema)[Type]['input']>; + input: z.infer; config: Readonly & RuntimeConfig>>; - }) => - | z.infer<(typeof handlerInputOutputSchema)[Type]['output']> - | Promise>; + }) => z.infer | Promise>; }; -// Entitlement operation registered on the connector (parallel to an AccountAction). Input/output -// are keyed off the entitlement handler schema by operation type (discover/grant/revoke). +export type AccountAction< + Config extends ConnectorConfig = ConnectorConfig, + ActionConfig extends ConnectorConfig = [], + Type extends ConnectorAccountAction['type'] = ConnectorAccountAction['type'], +> = Operation; + export type Entitlement< Config extends ConnectorConfig = ConnectorConfig, ActionConfig extends ConnectorConfig = [], Type extends ConnectorEntitlement['type'] = ConnectorEntitlement['type'], -> = Pick & { - type: Type; - config?: ActionConfig; - handler: (context: { - input: z.infer<(typeof entitlementHandlerInputOutputSchema)[Type]['input']>; - config: Readonly & RuntimeConfig>>; - }) => - | z.infer<(typeof entitlementHandlerInputOutputSchema)[Type]['output']> - | Promise>; +> = Operation; + +export type Identity< + Config extends ConnectorConfig = ConnectorConfig, + ActionConfig extends ConnectorConfig = [], + Type extends ConnectorIdentity['type'] = ConnectorIdentity['type'], +> = Operation; + +// Keyed managed resource → operation type → operation, mirroring the manifest shape. +type Registry = Map>; + +const addToRegistry = ( + registry: Registry, + managedResource: string, + operation: Registered, +) => { + const operationByType = registry.get(managedResource) ?? new Map(); + operationByType.set(operation.type, operation); + registry.set(managedResource, operationByType); }; -export class OpenIgaConnector { - // Keyed managed resource → operation type → operation, mirroring the manifest shape. - readonly accountActionsRegistry = new Map>>(); - readonly entitlementRegistry = new Map>>(); +export class OpenIgaConnector { + readonly accountActionsRegistry: Registry> = new Map(); + readonly entitlementRegistry: Registry> = new Map(); + readonly identityRegistry: Registry> = new Map(); - constructor(readonly settings: Omit & { config: Config }) {} + constructor(readonly settings: Omit & { type: Kind; config: Config }) {} registerAccountActions< const ActionConfig extends ConnectorConfig = [], const Type extends ConnectorAccountAction['type'] = ConnectorAccountAction['type'], - >(managedResource: string, action: AccountAction) { - // The registry is type-erased over Type/ActionConfig; the dispatcher validates at runtime. - const accountActionConfigByType = - this.accountActionsRegistry.get(managedResource) ?? - new Map>(); - accountActionConfigByType.set(action.type, action as unknown as AccountAction); - this.accountActionsRegistry.set(managedResource, accountActionConfigByType); + >( + this: OpenIgaConnector, + managedResource: string, + action: AccountAction, + ) { + // The registry is type-erased over Type/ActionConfig; the dispatcher validates at runtime + addToRegistry( + this.accountActionsRegistry, + managedResource, + action as unknown as AccountAction, + ); return this; } @@ -71,11 +94,29 @@ export class OpenIgaConnector { registerEntitlements< const ActionConfig extends ConnectorConfig = [], const Type extends ConnectorEntitlement['type'] = ConnectorEntitlement['type'], - >(managedResource: string, entitlement: Entitlement) { - const entitlementConfigByType = - this.entitlementRegistry.get(managedResource) ?? new Map>(); - entitlementConfigByType.set(entitlement.type, entitlement as unknown as Entitlement); - this.entitlementRegistry.set(managedResource, entitlementConfigByType); + >( + this: OpenIgaConnector, + managedResource: string, + entitlement: Entitlement, + ) { + addToRegistry( + this.entitlementRegistry, + managedResource, + entitlement as unknown as Entitlement, + ); + + return this; + } + + registerIdentities< + const ActionConfig extends ConnectorConfig = [], + const Type extends ConnectorIdentity['type'] = ConnectorIdentity['type'], + >( + this: OpenIgaConnector, + managedResource: string, + identity: Identity, + ) { + addToRegistry(this.identityRegistry, managedResource, identity as unknown as Identity); return this; } diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement.schema.ts deleted file mode 100644 index 2787d15..0000000 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.entitlement.schema.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as z from 'zod/mini'; -import { connectorConfigSchema } from './connector.config.schema.ts'; - -// Build-time validation schema for an entitlement operation (parallel to an account action). -export const connectorEntitlementSchema = z.object({ - type: z.enum(['discover', 'grant', 'revoke', 'read']), - description: z.string(), - endpoints: z.array( - z.object({ - method: z.enum(['GET', 'POST', 'PATCH', 'PUT', 'DELETE']), - // If the endpoint depends on the config, template placeholders can be used (e.g.) https://site.{{ REGION }}.domain.com - url: z - .string() - .check( - z.regex(/^https?:\/\//, 'Upstream URL must start with http:// or https:// (allow-listed by Host)'), - ), - description: z.string().check(z.minLength(1)), - }), - ), - config: z.optional(connectorConfigSchema), - handler: z.custom<(...args: unknown[]) => unknown>( - (input) => typeof input === 'function', - 'handler must be a function', - ), -}); - -export type ConnectorEntitlement = z.infer; diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.identity-handler.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.identity-handler.schema.ts new file mode 100644 index 0000000..fa850cc --- /dev/null +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.identity-handler.schema.ts @@ -0,0 +1,31 @@ +import * as z from 'zod/mini'; +import { tenantSchema } from './connector.tenant.schema.ts'; + +const metadataSchema = z.optional(z.record(z.string(), z.json())); + +// Lists the people in the source one page at a time; keep calling with `nextCursor` until it is missing. +const listHandlerSchema = { + input: z.object({ tenant: tenantSchema, cursor: z.optional(z.string()) }), + output: z.object({ + identities: z.array( + z.object({ + // stable id in the source, never the email + identityId: z.string(), + // pending: not started yet + status: z.enum(['pending', 'active', 'inactive']), + // a new hire may not have one yet + email: z.optional(z.email()), + firstname: z.string(), + lastname: z.string(), + // identityId of the manager + managerId: z.optional(z.string()), + metadata: metadataSchema, + }), + ), + nextCursor: z.optional(z.string()), + }), +}; + +export const identityHandlerInputOutputSchema = { + list: listHandlerSchema, +}; diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.operation.schema.ts similarity index 59% rename from packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts rename to packages/connector-sdk/lib/iga/connector/validation-schema/connector.operation.schema.ts index 510161d..c7249ef 100644 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.account-action.schema.ts +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.operation.schema.ts @@ -1,9 +1,8 @@ import * as z from 'zod/mini'; import { connectorConfigSchema } from './connector.config.schema.ts'; -// Build-time validation schema for an account action -export const connectorAccountActionSchema = z.object({ - type: z.enum(['create', 'disable', 'enable', 'delete', 'read', 'list']), +// Build-time validation schema shared by every operation; each kind adds its own `type`. +const operationSchema = z.object({ description: z.string(), endpoints: z.array( z.object({ @@ -24,4 +23,18 @@ export const connectorAccountActionSchema = z.object({ ), }); +export const connectorAccountActionSchema = z.extend(operationSchema, { + type: z.enum(['create', 'disable', 'enable', 'delete', 'read', 'list']), +}); + +export const connectorEntitlementSchema = z.extend(operationSchema, { + type: z.enum(['discover', 'grant', 'revoke', 'read']), +}); + +// Identities are registered by source connectors only +export const connectorIdentitySchema = z.extend(operationSchema, { type: z.enum(['list']) }); + +export type ConnectorOperation = z.infer; export type ConnectorAccountAction = z.infer; +export type ConnectorEntitlement = z.infer; +export type ConnectorIdentity = z.infer; diff --git a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.settings.schema.ts b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.settings.schema.ts index 57a2e09..71e4006 100644 --- a/packages/connector-sdk/lib/iga/connector/validation-schema/connector.settings.schema.ts +++ b/packages/connector-sdk/lib/iga/connector/validation-schema/connector.settings.schema.ts @@ -2,6 +2,8 @@ import { z } from 'zod/mini'; import { connectorConfigSchema } from './connector.config.schema.ts'; export const connectorSettingsSchema = z.object({ + // source: system of record the Host reads people from; sink: system the Host provisions into + type: z.enum(['source', 'sink']), name: z.string().check(z.minLength(1)), description: z.string().check(z.minLength(1)), config: connectorConfigSchema, @@ -9,3 +11,4 @@ export const connectorSettingsSchema = z.object({ }); export type ConnectorSettings = z.infer; +export type ConnectorType = ConnectorSettings['type']; diff --git a/packages/connector-sdk/lib/iga/dispatcher.test.ts b/packages/connector-sdk/lib/iga/dispatcher.test.ts index 8e0b09a..d3d76fb 100644 --- a/packages/connector-sdk/lib/iga/dispatcher.test.ts +++ b/packages/connector-sdk/lib/iga/dispatcher.test.ts @@ -28,6 +28,7 @@ const buildPlugin = ( config: ConnectorConfig = [], ) => new OpenIgaConnector({ + type: 'sink', name: 'connector', description: 'desc', config, @@ -66,7 +67,13 @@ describe('createRuntimeDispatcher', () => { it('should throw error if the routing target is missing in the registry', async () => { const dispatch = createRuntimeDispatcher(buildPlugin()); - setHostInput({ __kind: 'account-action', __managedResource: 'unknown', __type: 'create', config: {}, input: validInput }); + setHostInput({ + __kind: 'account-action', + __managedResource: 'unknown', + __type: 'create', + config: {}, + input: validInput, + }); const code = await dispatch(); @@ -77,7 +84,11 @@ describe('createRuntimeDispatcher', () => { it('should throw error if the input in handler is invalid', async () => { const dispatch = createRuntimeDispatcher(buildPlugin()); // email is not a valid email address - setHostInput({ ...routing, config: {}, input: { tenant: { id: 'tenant-1' }, email: 'not-an-email', firstname: 'test', lastname: 'user' } }); + setHostInput({ + ...routing, + config: {}, + input: { tenant: { id: 'tenant-1' }, email: 'not-an-email', firstname: 'test', lastname: 'user' }, + }); const code = await dispatch(); @@ -87,7 +98,10 @@ describe('createRuntimeDispatcher', () => { it('should throw error if the required config from the connector is missing', async () => { const dispatch = createRuntimeDispatcher( - buildPlugin(() => ({ accountId: 'user-1' }) as never, [{ name: 'REGION', description: 'region', required: true }]), + buildPlugin( + () => ({ accountId: 'user-1' }) as never, + [{ name: 'REGION', description: 'region', required: true }], + ), ); setHostInput({ ...routing, config: {}, input: validInput }); // REGION intentionally left out of the envelope config @@ -115,7 +129,11 @@ describe('createRuntimeDispatcher', () => { ({ config, input }) => { expect(config).toEqual({ REGION: 'us-east-1' }); expect(input.email).toBe(validInput.email); - return { accountId: 'user-1', created: false, metadata: { region: (config as { REGION: string }).REGION } } as never; + return { + accountId: 'user-1', + created: false, + metadata: { region: (config as { REGION: string }).REGION }, + } as never; }, [{ name: 'REGION', description: 'region', required: true }], ), @@ -130,6 +148,7 @@ describe('createRuntimeDispatcher', () => { it('should dispatch a paged account list', async () => { const plugin = new OpenIgaConnector({ + type: 'sink', name: 'connector', description: 'desc', config: [], @@ -156,4 +175,34 @@ describe('createRuntimeDispatcher', () => { expect(code).toBe(0); expect(readHostOutput().nextCursor).toBe('p2'); }); + + it('should dispatch a paged identity list', async () => { + const plugin = new OpenIgaConnector({ + type: 'source', + name: 'connector', + description: 'desc', + config: [], + allowedDomains: ['domain.com'], + }).registerIdentities('employee', { + type: 'list', + description: 'list employees', + endpoints: [{ method: 'GET', url: 'https://domain.com', description: 'endpoint' }], + handler: ({ input }) => ({ + identities: [{ identityId: 'e-1', status: 'pending', firstname: 'test', lastname: 'user' }], + nextCursor: `${input.cursor}-next`, + }), + }); + setHostInput({ + __kind: 'identity', + __managedResource: 'employee', + __type: 'list', + config: {}, + input: { tenant: { id: 'tenant-1' }, cursor: 'p1' }, + }); + + const code = await createRuntimeDispatcher(plugin)(); + + expect(code).toBe(0); + expect(readHostOutput()).toMatchObject({ identities: [{ identityId: 'e-1' }], nextCursor: 'p1-next' }); + }); }); diff --git a/packages/connector-sdk/lib/iga/dispatcher.ts b/packages/connector-sdk/lib/iga/dispatcher.ts index b66416b..e15c287 100644 --- a/packages/connector-sdk/lib/iga/dispatcher.ts +++ b/packages/connector-sdk/lib/iga/dispatcher.ts @@ -2,6 +2,7 @@ import type { OpenIgaConnector } from './connector/builder.ts'; import * as z from 'zod/mini'; import { handlerInputOutputSchema } from './connector/validation-schema/connector.account-action-handler.schema.ts'; import { entitlementHandlerInputOutputSchema } from './connector/validation-schema/connector.entitlement-handler.schema.ts'; +import { identityHandlerInputOutputSchema } from './connector/validation-schema/connector.identity-handler.schema.ts'; import { installRuntimePolyfills } from '../polyfills/installer.ts'; import { buildConfig } from '../utils/config.ts'; import type { ConnectorConfig } from './connector/validation-schema/connector.config.schema.ts'; @@ -10,7 +11,7 @@ import type { ConnectorConfig } from './connector/validation-schema/connector.co // its own slot. `kind` disambiguates `read` (both an account-action and an entitlement). `config` // carries only the keys the Host scoped to this operation — the isolation boundary lives Host-side. const envelopeSchema = z.object({ - __kind: z.enum(['account-action', 'entitlement']), + __kind: z.enum(['account-action', 'entitlement', 'identity']), __managedResource: z.string(), __type: z.string(), config: z.record(z.string(), z.string()), @@ -40,6 +41,16 @@ const resolveOperation = ( return { handler: entitlement.handler, config: entitlement.config, input, output }; } + if (__kind === 'identity') { + const identity = plugin.identityRegistry.get(__managedResource)?.get(__type); + if (!identity) { + return undefined; + } + + const { input, output } = identityHandlerInputOutputSchema[identity.type]; + return { handler: identity.handler, config: identity.config, input, output }; + } + const action = plugin.accountActionsRegistry.get(__managedResource)?.get(__type); if (!action) { return undefined; diff --git a/packages/connector-sdk/lib/index.ts b/packages/connector-sdk/lib/index.ts index a2e3dd0..a72cea0 100644 --- a/packages/connector-sdk/lib/index.ts +++ b/packages/connector-sdk/lib/index.ts @@ -1,2 +1,3 @@ export { OpenIgaConnector } from './iga/connector/builder.ts'; +export type { ConnectorType } from './iga/connector/validation-schema/connector.settings.schema.ts'; export { sendEmail } from './iga/capabilities/email.ts'; diff --git a/packages/connector-sdk/lib/test/mock-fetch.ts b/packages/connector-sdk/lib/test/mock-fetch.ts index e3eff16..422c9dd 100644 --- a/packages/connector-sdk/lib/test/mock-fetch.ts +++ b/packages/connector-sdk/lib/test/mock-fetch.ts @@ -1,4 +1,4 @@ -import type { ConnectorAccountAction } from '../iga/connector/validation-schema/connector.account-action.schema.ts'; +import type { ConnectorOperation } from '../iga/connector/validation-schema/connector.operation.schema.ts'; /** * Config Template Placeholders regex @@ -10,10 +10,10 @@ const CONFIG_PLACEHOLDERS = /\{\{\s*([A-Za-z0-9_-]+)\s*\}\}/g; * The same is applicable for testing * */ export const createFetchProxy = (mockUpstream: string, config: Record) => { - let allowedEndpoints: ConnectorAccountAction['endpoints'] = []; + let allowedEndpoints: ConnectorOperation['endpoints'] = []; return { - setAllowedEndpoint: (newAllowedEndpoints: ConnectorAccountAction['endpoints']) => { + setAllowedEndpoint: (newAllowedEndpoints: ConnectorOperation['endpoints']) => { allowedEndpoints = newAllowedEndpoints.map(({ method, description, url }) => { const replacedUrl = url.replace(CONFIG_PLACEHOLDERS, (substring, key: string) => { if (!config[key]) { diff --git a/packages/connector-sdk/lib/test/mock-host.ts b/packages/connector-sdk/lib/test/mock-host.ts index 8bfdc98..8f9a509 100644 --- a/packages/connector-sdk/lib/test/mock-host.ts +++ b/packages/connector-sdk/lib/test/mock-host.ts @@ -7,11 +7,16 @@ import type { OpenIgaConnector, RuntimeConfig } from '../iga/connector/builder.t import * as path from 'node:path'; import { OUT_DIR } from '../cli/compile.ts'; import type { ConnectorConfig } from '../iga/connector/validation-schema/connector.config.schema.ts'; -import type { ConnectorAccountAction } from '../iga/connector/validation-schema/connector.account-action.schema.ts'; -import type { ConnectorEntitlement } from '../iga/connector/validation-schema/connector.entitlement.schema.ts'; +import type { + ConnectorAccountAction, + ConnectorEntitlement, + ConnectorIdentity, + ConnectorOperation, +} from '../iga/connector/validation-schema/connector.operation.schema.ts'; import { z } from 'zod/mini'; import type { handlerInputOutputSchema } from '../iga/connector/validation-schema/connector.account-action-handler.schema.ts'; import type { entitlementHandlerInputOutputSchema } from '../iga/connector/validation-schema/connector.entitlement-handler.schema.ts'; +import type { identityHandlerInputOutputSchema } from '../iga/connector/validation-schema/connector.identity-handler.schema.ts'; import type { LogLevel } from '@extism/extism'; import { createFetchProxy } from './mock-fetch.ts'; import { emailPayloadSchema, type EmailPayload } from '../iga/capabilities/email.schema.ts'; @@ -24,6 +29,10 @@ export type MockedEntitlementResult = | { ok: true; output: z.infer<(typeof entitlementHandlerInputOutputSchema)[Type]['output']> } | { ok: false; error: string }; +export type MockedIdentityResult = + | { ok: true; output: z.infer<(typeof identityHandlerInputOutputSchema)[Type]['output']> } + | { ok: false; error: string }; + export type MockedHost = { callAccountActions: ( managedResource: string, @@ -38,6 +47,11 @@ export type MockedHost = { type: Type, input?: z.infer<(typeof entitlementHandlerInputOutputSchema)[Type]['input']>, ) => Promise>; + callIdentities: ( + managedResource: string, + type: Type, + input: z.infer<(typeof identityHandlerInputOutputSchema)[Type]['input']>, + ) => Promise>; hostFunctions: { sentEmails: EmailPayload[]; }; @@ -92,10 +106,16 @@ export const createMockedHost = async ({ ...(headers && { headers }), ...(body && { body }), }); - return callContext.store(JSON.stringify({ status: response.status, body: await response.text() })); + return callContext.store( + JSON.stringify({ status: response.status, body: await response.text() }), + ); } catch (err) { return callContext.store( - JSON.stringify({ status: 403, body: '', error: err instanceof Error ? err.message : String(err) }), + JSON.stringify({ + status: 403, + body: '', + error: err instanceof Error ? err.message : String(err), + }), ); } }, @@ -111,48 +131,43 @@ export const createMockedHost = async ({ }, }); - return { - callAccountActions: async (managedResource, type, input) => { - proxy.setAllowedEndpoint(plugin.accountActionsRegistry.get(managedResource)?.get(type)?.endpoints ?? []); - - const out = await wasmPlugin.call( - 'dispatch', - JSON.stringify({ - __kind: 'account-action', - __managedResource: managedResource, - __type: type, - config, - input, - }), - ); - if (!out) { - return { ok: false, error: 'no output' }; - } + const dispatch = async ( + kind: 'account-action' | 'entitlement' | 'identity', + registry: Map>, + managedResource: string, + type: string, + input: unknown, + ) => { + proxy.setAllowedEndpoint(registry.get(managedResource)?.get(type)?.endpoints ?? []); - const parsed = out.json(); - return 'error' in parsed ? { ok: false, error: String(parsed.error) } : { ok: true, output: parsed }; - }, + const out = await wasmPlugin.call( + 'dispatch', + JSON.stringify({ + __kind: kind, + __managedResource: managedResource, + __type: type, + config, + input, + }), + ); + if (!out) { + return { ok: false as const, error: 'no output' }; + } - callEntitlements: async (managedResource, type, input) => { - proxy.setAllowedEndpoint(plugin.entitlementRegistry.get(managedResource)?.get(type)?.endpoints ?? []); + const parsed = out.json(); - const out = await wasmPlugin.call( - 'dispatch', - JSON.stringify({ - __kind: 'entitlement', - __managedResource: managedResource, - __type: type, - config, - input: input ?? {}, - }), - ); - if (!out) { - return { ok: false, error: 'no output' }; - } + return 'error' in parsed + ? { ok: false as const, error: String(parsed.error) } + : { ok: true as const, output: parsed }; + }; - const parsed = out.json(); - return 'error' in parsed ? { ok: false, error: String(parsed.error) } : { ok: true, output: parsed }; - }, + return { + callAccountActions: (managedResource, type, input) => + dispatch('account-action', plugin.accountActionsRegistry, managedResource, type, input), + callEntitlements: (managedResource, type, input) => + dispatch('entitlement', plugin.entitlementRegistry, managedResource, type, input ?? {}), + callIdentities: (managedResource, type, input) => + dispatch('identity', plugin.identityRegistry, managedResource, type, input), hostFunctions: { sentEmails }, close: () => wasmPlugin.close(),