From 5efedf594a8f513e51483a81c6365fcd4357e9dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Thu, 29 Oct 2026 12:24:46 -0300 Subject: [PATCH 01/29] feat(config): add initial structure for API v6 Add versions/v6 skeleton (types, placeholder schemas, process strategy, validators, converter) and register it in the version registry, defineConfig and the public exports. Share what v4 and v6 have in common under versions/shared: the generic ProcessConfigStrategy/ProcessConfigContext and the config validator, manifest validator and JSON config converter factories. v3 is left unchanged. --- packages/config/src/index.ts | 11 +++- packages/config/src/versions/registry.test.ts | 39 ++++++++++++ packages/config/src/versions/registry.ts | 2 + .../versions/shared/converterJsonConfig.ts | 38 ++++++++++++ .../processStrategy/processConfigContext.ts | 47 +++++++++++++++ .../processStrategy/processConfigStrategy.ts | 18 ++++++ .../src/versions/shared/validateConfig.ts | 60 +++++++++++++++++++ .../src/versions/shared/validateManifest.ts | 27 +++++++++ packages/config/src/versions/types.ts | 6 +- .../versions/v4/converterJsonConfig/index.ts | 23 +++---- .../processStrategy/processConfigContext.ts | 44 ++------------ .../processStrategy/processConfigStrategy.ts | 20 ++----- .../src/versions/v4/validateConfig/index.ts | 60 ++----------------- .../src/versions/v4/validateManifest/index.ts | 23 +------ .../versions/v6/converterJsonConfig/index.ts | 18 ++++++ packages/config/src/versions/v6/index.ts | 24 ++++++++ .../src/versions/v6/processStrategy/index.ts | 10 ++++ .../config/src/versions/v6/schemas/schema.ts | 15 +++++ .../src/versions/v6/schemas/schemaManifest.ts | 10 ++++ packages/config/src/versions/v6/types.ts | 12 ++++ .../src/versions/v6/validateConfig/index.ts | 14 +++++ .../src/versions/v6/validateManifest/index.ts | 12 ++++ 22 files changed, 380 insertions(+), 153 deletions(-) create mode 100644 packages/config/src/versions/shared/converterJsonConfig.ts create mode 100644 packages/config/src/versions/shared/processStrategy/processConfigContext.ts create mode 100644 packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts create mode 100644 packages/config/src/versions/shared/validateConfig.ts create mode 100644 packages/config/src/versions/shared/validateManifest.ts create mode 100644 packages/config/src/versions/v6/converterJsonConfig/index.ts create mode 100644 packages/config/src/versions/v6/index.ts create mode 100644 packages/config/src/versions/v6/processStrategy/index.ts create mode 100644 packages/config/src/versions/v6/schemas/schema.ts create mode 100644 packages/config/src/versions/v6/schemas/schemaManifest.ts create mode 100644 packages/config/src/versions/v6/types.ts create mode 100644 packages/config/src/versions/v6/validateConfig/index.ts create mode 100644 packages/config/src/versions/v6/validateManifest/index.ts diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index 5fae08bb..e360a441 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -6,6 +6,7 @@ import { } from './configProcessor/helpers/convertLegacyConfig'; import { AzionConfig } from './types'; import type { AzionConfigV3 } from './versions/v3/types'; +import type { AzionConfigV6 } from './versions/v6/types'; import { getApplicationName, getFirewallReplacedKeys, getStorage } from './versions/accessors'; import { getPresetApiVersions, resolvePresetConfig } from './versions/presetConfig'; import { @@ -20,7 +21,7 @@ import { DEFAULT_API_VERSION } from './versions/types'; * Helper function to provide IntelliSense for Azion configuration. * Similar to Vite's defineConfig - provides type safety without runtime overhead. * - * Declare `version: 3` to get the Azion API v3 types (the remaining v3 types live under the `V3` namespace). + * Declare `version: 3` or `version: 6` to get the types of that Azion API version (the remaining types live under the `V3` and `V6` namespaces). * * @param {AnyAzionConfig} config - The configuration object for the Azion Platform. * @returns {AzionConfig} The same configuration object (no validation or processing) @@ -39,8 +40,11 @@ import { DEFAULT_API_VERSION } from './versions/types'; * }); */ function defineConfig(config: AzionConfigV3): AzionConfigV3; +function defineConfig(config: AzionConfigV6): AzionConfigV6; function defineConfig(config: AzionConfig): AzionConfig; -function defineConfig(config: AzionConfig | AzionConfigV3): AzionConfig | AzionConfigV3 { +function defineConfig( + config: AzionConfig | AzionConfigV3 | AzionConfigV6, +): AzionConfig | AzionConfigV3 | AzionConfigV6 { return config; } @@ -67,5 +71,6 @@ export { export type * from './types'; export type { AnyAzionConfig, ApiVersion, ConfigByVersion, ConfigVersionModule } from './versions/types'; -export type { AzionConfigV3 }; +export type { AzionConfigV3, AzionConfigV6 }; export type * as V3 from './versions/v3/types'; +export type * as V6 from './versions/v6/types'; diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 67725a98..92ab32b9 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -121,3 +121,42 @@ describe('v3 support', () => { expect(v4.version).toBeUndefined(); }); }); + +describe('v6 support', () => { + const v6Config = { version: 6 as const, build: { bundler: 'esbuild' as const } }; + + it('is registered and selected by `version: 6`', () => { + expect(resolveApiVersion(v6Config)).toBe(6); + expect(getVersionModule(6).version).toBe(6); + expect(SUPPORTED_API_VERSIONS).toContain(6); + }); + + it('keeps v4 as the default when version is omitted', () => { + expect(DEFAULT_API_VERSION).toBe(4); + expect(resolveApiVersion({ build: {} })).toBe(4); + }); + + it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { + expect(() => validateConfig(v6Config)).not.toThrow(); + expect(() => validateConfig({ version: 6, applications: [] })).toThrow(); + }); + + it('does not accept v6 on the v4 schema nor the other way around', () => { + expect(() => validateConfig({ version: 4, build: {} })).not.toThrow(); + expect(() => validateConfig({ version: 6, origin: [] })).toThrow(); + }); + + it('processes a v6 config without leaking version into the manifest', () => { + expect(processConfig(v6Config)).not.toHaveProperty('version'); + }); + + it('forwards the version to manifest helpers', () => { + expect(() => validateManifest({}, undefined, { version: 6 })).not.toThrow(); + expect(() => convertJsonConfigToObject('{', { version: 6 })).toThrow('Invalid JSON configuration.'); + expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6 }); + }); + + it('types defineConfig by the declared version', () => { + expect(defineConfig(v6Config).version).toBe(6); + }); +}); diff --git a/packages/config/src/versions/registry.ts b/packages/config/src/versions/registry.ts index f2a4e9e3..8fccd65f 100644 --- a/packages/config/src/versions/registry.ts +++ b/packages/config/src/versions/registry.ts @@ -1,10 +1,12 @@ import { ApiVersion, ConfigVersionModule, DEFAULT_API_VERSION } from './types'; import v3 from './v3'; import v4 from './v4'; +import v6 from './v6'; const registry: Record = { 3: v3, 4: v4, + 6: v6, }; /** diff --git a/packages/config/src/versions/shared/converterJsonConfig.ts b/packages/config/src/versions/shared/converterJsonConfig.ts new file mode 100644 index 00000000..ce5db427 --- /dev/null +++ b/packages/config/src/versions/shared/converterJsonConfig.ts @@ -0,0 +1,38 @@ +import type ProcessConfigContext from './processStrategy/processConfigContext'; + +type JsonConfigConverterOptions = { + /** Validates the parsed manifest. Throws on failure. */ + validate: (manifest: Record) => void; + /** Builds the strategy context of the API version. */ + factoryProcessContext: () => ProcessConfigContext; + /** Builds the config object the strategies fill. */ + createConfig: () => TConfig; +}; + +/** + * Creates the function that converts a JSON manifest string into a config object of an API version. + * @throws {Error} The returned function throws if the provided JSON string is invalid. + */ +function createJsonConfigConverter({ + validate, + factoryProcessContext, + createConfig, +}: JsonConfigConverterOptions) { + return function convertJsonConfigToObject(config: string): TConfig { + let configObject: Record; + try { + configObject = JSON.parse(config); + } catch { + throw new Error('Invalid JSON configuration.'); + } + validate(configObject); + const payloadConfig = createConfig(); + const processConfigContext = factoryProcessContext(); + + processConfigContext.transformToConfig(configObject, payloadConfig); + + return payloadConfig; + }; +} + +export { createJsonConfigConverter }; diff --git a/packages/config/src/versions/shared/processStrategy/processConfigContext.ts b/packages/config/src/versions/shared/processStrategy/processConfigContext.ts new file mode 100644 index 00000000..2e8865ef --- /dev/null +++ b/packages/config/src/versions/shared/processStrategy/processConfigContext.ts @@ -0,0 +1,47 @@ +import ProcessConfigStrategy from './processConfigStrategy'; + +/** + * ProcessConfigContext + * @class + * @description This class is responsible for generating the context of the process config. + * `TConfig` is the config shape of the API version. + */ +class ProcessConfigContext { + strategies: { [key: string]: ProcessConfigStrategy }; + constructor() { + this.strategies = {}; + } + + setStrategy(type: string, strategy: ProcessConfigStrategy): void { + this.strategies[type] = strategy; + } + /** + * Transform to manifest is responsible for transforming the config to the manifest. + * @param config Config of the API version + * @param context manifest object + * @returns + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToManifest(config: TConfig, context: any) { + Object.keys(this.strategies).forEach((key) => { + context[key] = this.strategies[key].transformToManifest(config, context); + }); + return context; + } + + /** + * Transform to config is responsible for transforming the payload to the config. + * @param payload Manifest object + * @param transformedPayload Config object of the API version + * @returns + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: TConfig): TConfig { + Object.keys(this.strategies).forEach((key) => { + payload[key] = this.strategies[key].transformToConfig(payload, transformedPayload); + }); + return payload; + } +} + +export default ProcessConfigContext; diff --git a/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts b/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts new file mode 100644 index 00000000..1b35d8cd --- /dev/null +++ b/packages/config/src/versions/shared/processStrategy/processConfigStrategy.ts @@ -0,0 +1,18 @@ +/** + * ProcessConfigStrategy + * @class ProcessConfigStrategy + * @description Base class of the process config strategies. `TConfig` is the config shape of the API version. + */ +class ProcessConfigStrategy { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToManifest(config: any, context: any) { + return context; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars + transformToConfig(payload: any, transformedPayload: TConfig): TConfig | any { + return payload; + } +} + +export default ProcessConfigStrategy; diff --git a/packages/config/src/versions/shared/validateConfig.ts b/packages/config/src/versions/shared/validateConfig.ts new file mode 100644 index 00000000..af20df11 --- /dev/null +++ b/packages/config/src/versions/shared/validateConfig.ts @@ -0,0 +1,60 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +const MAX_REPORTED_ERRORS = 3; + +function formatErrors(errors: unknown[]) { + const messages = errors + .slice(0, MAX_REPORTED_ERRORS) + .map((error: unknown, index: number) => { + const errorObject = error as { + message: string; + instancePath: string; + params: { missingProperty?: string | undefined }; + }; + + return [ + `📍 Error #${index + 1}:`, + ` Message: ${errorObject.message}`, + errorObject.instancePath ? ` Path: ${errorObject.instancePath}` : null, + errorObject.params?.missingProperty ? ` Missing Property: ${errorObject.params.missingProperty}` : null, + ] + .filter(Boolean) + .join('\n'); + }) + .join('\n\n'); + + const moreErrorsNote = + errors.length > MAX_REPORTED_ERRORS ? `\n\n... and ${errors.length - MAX_REPORTED_ERRORS} more error(s)` : ''; + + return `⛔️ Azion Configuration Validation Failed\n${'-'.repeat(50)}\n${messages}${moreErrorsNote}\n${'-'.repeat(50)}`; +} + +/** + * Creates the config validator of an API version. + * The validator uses AJV (Another JSON Schema Validator) and throws an error that reports the first validation issues. + * @param {object} defaultSchema - JSON Schema of the version's config, used when the caller does not pass one. + * @returns A function that validates a config and throws an error if it fails validation. + */ +function createConfigValidator(defaultSchema: Record) { + return function validateConfig( + config: TConfig | Record, + schema: Record = defaultSchema, + ) { + const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + const validate = ajv.compile(schema); + const valid = validate(config); + + if (!valid) { + if (validate.errors && validate.errors.length > 0) { + throw new Error(formatErrors(validate.errors)); + } + throw new Error('Azion validation failed.'); + } + }; +} + +export { createConfigValidator }; diff --git a/packages/config/src/versions/shared/validateManifest.ts b/packages/config/src/versions/shared/validateManifest.ts new file mode 100644 index 00000000..5cd5333f --- /dev/null +++ b/packages/config/src/versions/shared/validateManifest.ts @@ -0,0 +1,27 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +/** + * Creates the manifest validator of an API version. + * @param {object} defaultSchema - JSON Schema of the version's manifest, used when the caller does not pass one. + * @returns A function that validates a manifest and throws an error if it fails validation. + */ +function createManifestValidator(defaultSchema: Record) { + return function validateManifest(manifest: Record, schema: Record = defaultSchema) { + const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + const validate = ajv.compile(schema); + const valid = validate(manifest); + + if (!valid) { + if (validate.errors && validate.errors.length > 0) { + throw new Error('Azion validation: ' + validate.errors[0].message); + } + throw new Error('Azion validation failed.'); + } + }; +} + +export { createManifestValidator }; diff --git a/packages/config/src/versions/types.ts b/packages/config/src/versions/types.ts index fe3854cf..54b37f86 100644 --- a/packages/config/src/versions/types.ts +++ b/packages/config/src/versions/types.ts @@ -1,6 +1,7 @@ import type { AzionConfig } from '../types'; import type { AzionConfigV3 } from './v3/types'; -import type ProcessConfigContext from './v4/processStrategy/processConfigContext'; +import type { AzionConfigV6 } from './v6/types'; +import type ProcessConfigContext from './shared/processStrategy/processConfigContext'; /** * Config shape of each Azion API version the package knows how to process. @@ -11,6 +12,7 @@ import type ProcessConfigContext from './v4/processStrategy/processConfigContext export interface ConfigByVersion { 3: AzionConfigV3; 4: AzionConfig; + 6: AzionConfigV6; } export type ApiVersion = keyof ConfigByVersion; @@ -32,7 +34,7 @@ export const DEFAULT_API_VERSION: ApiVersion = 4; export interface ConfigVersionModule { version: ApiVersion; /** Builds the strategy context that converts config <-> manifest for this version. */ - factoryProcessContext: () => ProcessConfigContext; + factoryProcessContext: () => ProcessConfigContext; /** Validates a config against this version's schema. Throws on failure. */ validateConfig: (config: AnyAzionConfig | Record, schema?: Record) => void; /** Validates a manifest against this version's manifest schema. Throws on failure. */ diff --git a/packages/config/src/versions/v4/converterJsonConfig/index.ts b/packages/config/src/versions/v4/converterJsonConfig/index.ts index 07143299..7371ca9e 100644 --- a/packages/config/src/versions/v4/converterJsonConfig/index.ts +++ b/packages/config/src/versions/v4/converterJsonConfig/index.ts @@ -1,4 +1,5 @@ -import { AzionConfig } from '../../../types'; +import type { AzionConfig } from '../../../types'; +import { createJsonConfigConverter } from '../../shared/converterJsonConfig'; import { factoryProcessContext } from '../processStrategy'; import { schemaManifest } from '../schemas/schemaManifest'; import { validateConfig } from '../validateConfig'; @@ -30,20 +31,10 @@ import { validateConfig } from '../validateConfig'; * console.log(configObject); * */ -function convertJsonConfigToObject(config: string): AzionConfig { - let configObject: Record; - try { - configObject = JSON.parse(config); - } catch { - throw new Error('Invalid JSON configuration.'); - } - validateConfig(configObject, schemaManifest); - const payloadConfig: AzionConfig = {}; - const processConfigContext = factoryProcessContext(); - - processConfigContext.transformToConfig(configObject, payloadConfig); - - return payloadConfig; -} +const convertJsonConfigToObject = createJsonConfigConverter({ + validate: (manifest) => validateConfig(manifest, schemaManifest), + factoryProcessContext, + createConfig: () => ({}), +}); export { convertJsonConfigToObject }; diff --git a/packages/config/src/versions/v4/processStrategy/processConfigContext.ts b/packages/config/src/versions/v4/processStrategy/processConfigContext.ts index 566c8356..b2cdb62a 100644 --- a/packages/config/src/versions/v4/processStrategy/processConfigContext.ts +++ b/packages/config/src/versions/v4/processStrategy/processConfigContext.ts @@ -1,47 +1,11 @@ -import { AzionConfig } from '../../../types'; -import ProcessConfigStrategy from './processConfigStrategy'; +import type { AzionConfig } from '../../../types'; +import SharedProcessConfigContext from '../../shared/processStrategy/processConfigContext'; /** * ProcessConfigContext * @class - * @description This class is responsible for generating the context of the process config. + * @description Context of the v4 process config. */ -class ProcessConfigContext { - strategies: { [key: string]: ProcessConfigStrategy }; - constructor() { - this.strategies = {}; - } - - setStrategy(type: string, strategy: ProcessConfigStrategy): void { - this.strategies[type] = strategy; - } - /** - * Transform to manifest is responsible for transforming the config to the manifest. - * @param config AzionConfig - * @param context manifest object - * @returns - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToManifest(config: AzionConfig, context: any) { - Object.keys(this.strategies).forEach((key) => { - context[key] = this.strategies[key].transformToManifest(config, context); - }); - return context; - } - - /** - * Transform to config is responsible for transforming the payload to the config. - * @param payload Manifest object - * @param transformedPayload AzionConfig object - * @returns - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToConfig(payload: any, transformedPayload: AzionConfig): AzionConfig { - Object.keys(this.strategies).forEach((key) => { - payload[key] = this.strategies[key].transformToConfig(payload, transformedPayload); - }); - return payload; - } -} +class ProcessConfigContext extends SharedProcessConfigContext {} export default ProcessConfigContext; diff --git a/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts b/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts index 8d06a946..1b52dbc9 100644 --- a/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts +++ b/packages/config/src/versions/v4/processStrategy/processConfigStrategy.ts @@ -1,21 +1,11 @@ +import type { AzionConfig } from '../../../types'; +import SharedProcessConfigStrategy from '../../shared/processStrategy/processConfigStrategy'; + /** * ProcessConfigStrategy * @class ProcessConfigStrategy - * @description This class is the base class for all process config strategies. + * @description Base class of the v4 process config strategies. */ - -import { AzionConfig } from '../../../types'; - -class ProcessConfigStrategy { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToManifest(config: any, context: any) { - return context; - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars - transformToConfig(payload: any, transformedPayload: AzionConfig): AzionConfig | any { - return payload; - } -} +class ProcessConfigStrategy extends SharedProcessConfigStrategy {} export default ProcessConfigStrategy; diff --git a/packages/config/src/versions/v4/validateConfig/index.ts b/packages/config/src/versions/v4/validateConfig/index.ts index 6ec57dbc..88a3bdf0 100644 --- a/packages/config/src/versions/v4/validateConfig/index.ts +++ b/packages/config/src/versions/v4/validateConfig/index.ts @@ -1,66 +1,14 @@ -import Ajv from 'ajv'; -import ajvErrors from 'ajv-errors'; -import addKeywords from 'ajv-keywords'; - -import { AzionConfig } from '../../../types'; +import type { AzionConfig } from '../../../types'; +import { createConfigValidator } from '../../shared/validateConfig'; import azionConfigSchema from '../schemas/schema'; /** * Validates the provided configuration against a JSON Schema. - * This function uses AJV (Another JSON Schema Validator) to validate the configuration. - * If the configuration is not valid, an exception is thrown with the error message of the first validation issue encountered. + * If the configuration is not valid, an exception is thrown with the first validation issues encountered. * @param {AzionConfig | Record} config - The configuration to be validated. * @param {object} schema - The JSON Schema to be used for validation. Default is the Azion CDN configuration schema. * @throws {Error} Throws an error if the configuration fails validation. */ -function validateConfig( - config: AzionConfig | Record, - schema: Record = azionConfigSchema, -) { - /* Converts legacy configuration properties to the new `behavior` format. */ - const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); - ajvErrors(ajv); - addKeywords(ajv, ['instanceof']); - const validate = ajv.compile(schema); - const valid = validate(config); - - const handleMessageError = (errors: unknown[]) => { - const messages = errors - ?.slice(0, 3) - ?.map((error: unknown, index: number) => { - const errorObject = error as { - message: string; - instancePath: string; - params: { missingProperty?: string | undefined }; - }; - - const errorDetails = [ - `📍 Error #${index + 1}:`, - ` Message: ${errorObject.message}`, - errorObject.instancePath ? ` Path: ${errorObject.instancePath}` : null, - errorObject.params?.missingProperty ? ` Missing Property: ${errorObject.params.missingProperty}` : null, - ] - .filter(Boolean) - .join('\n'); - - return errorDetails; - }) - .join('\n\n'); - - const totalErrors = errors?.length || 0; - const moreErrorsNote = totalErrors > 3 ? `\n\n... and ${totalErrors - 3} more error(s)` : ''; - - return `⛔️ Azion Configuration Validation Failed\n${'-'.repeat(50)}\n${messages}${moreErrorsNote}\n${'-'.repeat(50)}`; - }; - - if (!valid) { - if (validate.errors && validate.errors.length > 0) { - const messages = handleMessageError(validate.errors); - throw new Error(messages); - } else { - throw new Error('Azion validation failed.'); - } - } -} +const validateConfig = createConfigValidator(azionConfigSchema); export { validateConfig }; diff --git a/packages/config/src/versions/v4/validateManifest/index.ts b/packages/config/src/versions/v4/validateManifest/index.ts index 95a849de..de6e4bee 100644 --- a/packages/config/src/versions/v4/validateManifest/index.ts +++ b/packages/config/src/versions/v4/validateManifest/index.ts @@ -1,32 +1,13 @@ -import Ajv from 'ajv'; -import ajvErrors from 'ajv-errors'; -import addKeywords from 'ajv-keywords'; - +import { createManifestValidator } from '../../shared/validateManifest'; import { schemaManifest as azionManifestSchema } from '../schemas/schemaManifest'; /** * Validates the provided manifest against the Azion Manifest Schema. - * This function uses AJV (Another JSON Schema Validator) to validate the manifest. * If the manifest is not valid, an exception is thrown with the error message of the first validation issue encountered. * @param {Record} manifest - The manifest to be validated. * @param {object} schema - The JSON Schema to be used for validation. Default is the Azion Manifest schema. * @throws {Error} Throws an error if the manifest fails validation. */ -function validateManifest(manifest: Record, schema: Record = azionManifestSchema) { - const ajv = new Ajv({ allErrors: true, $data: true, allowUnionTypes: true }); - ajvErrors(ajv); - addKeywords(ajv, ['instanceof']); - const validate = ajv.compile(schema); - const valid = validate(manifest); - - if (!valid) { - if (validate.errors && validate.errors.length > 0) { - const firstError = validate.errors[0]; - throw new Error('Azion validation: ' + firstError.message); - } else { - throw new Error('Azion validation failed.'); - } - } -} +const validateManifest = createManifestValidator(azionManifestSchema); export { validateManifest }; diff --git a/packages/config/src/versions/v6/converterJsonConfig/index.ts b/packages/config/src/versions/v6/converterJsonConfig/index.ts new file mode 100644 index 00000000..c7a68f11 --- /dev/null +++ b/packages/config/src/versions/v6/converterJsonConfig/index.ts @@ -0,0 +1,18 @@ +import { createJsonConfigConverter } from '../../shared/converterJsonConfig'; +import { factoryProcessContext } from '../processStrategy'; +import type { AzionConfigV6 } from '../types'; +import { validateManifest } from '../validateManifest'; + +/** + * Converts a JSON manifest string to an AzionConfigV6 object. + * @param {string} config - The JSON string to be converted. + * @returns {AzionConfigV6} The AzionConfigV6 object. + * @throws {Error} Throws an error if the provided JSON string is invalid. + */ +const convertJsonConfigToObject = createJsonConfigConverter({ + validate: (manifest) => validateManifest(manifest), + factoryProcessContext, + createConfig: () => ({ version: 6 }), +}); + +export { convertJsonConfigToObject }; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts new file mode 100644 index 00000000..4f607e78 --- /dev/null +++ b/packages/config/src/versions/v6/index.ts @@ -0,0 +1,24 @@ +import type { ConfigVersionAccessors, ConfigVersionModule } from '../types'; +import { convertJsonConfigToObject } from './converterJsonConfig'; +import { factoryProcessContext } from './processStrategy'; +import { validateConfig } from './validateConfig'; +import { validateManifest } from './validateManifest'; + +const accessors: ConfigVersionAccessors = { + // TODO: define where v6 keeps the application name, the storage and the firewall keys + getApplicationName: () => undefined, + getStorage: () => undefined, + firewallReplacedKeys: [], +}; + +// v6 has its own AzionConfig type, which is not assignable to the default (v4) one used by the shared contract +const v6 = { + version: 6, + factoryProcessContext, + validateConfig, + validateManifest, + convertJsonConfigToObject, + accessors, +} as unknown as ConfigVersionModule; + +export default v6; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts new file mode 100644 index 00000000..e7fa210b --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -0,0 +1,10 @@ +import ProcessConfigContext from '../../shared/processStrategy/processConfigContext'; +import type { AzionConfigV6 } from '../types'; + +function factoryProcessContext() { + const processConfigContext = new ProcessConfigContext(); + // TODO: register the v6 strategies (setStrategy) as the v6 resources are defined + return processConfigContext; +} + +export { factoryProcessContext }; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts new file mode 100644 index 00000000..2321605a --- /dev/null +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -0,0 +1,15 @@ +/** + * JSON Schema of the v6 config. + * TODO: placeholder. Only `version` and `build` are accepted until the v6 schemas are defined. + */ +const azionConfigSchema = { + $id: 'azionConfig', + type: 'object', + additionalProperties: false, + properties: { + version: { const: 6 }, + build: { type: 'object' }, + }, +}; + +export default azionConfigSchema; diff --git a/packages/config/src/versions/v6/schemas/schemaManifest.ts b/packages/config/src/versions/v6/schemas/schemaManifest.ts new file mode 100644 index 00000000..97f13c4b --- /dev/null +++ b/packages/config/src/versions/v6/schemas/schemaManifest.ts @@ -0,0 +1,10 @@ +/** + * JSON Schema of the v6 manifest. + * TODO: placeholder. Accepts any object until the v6 manifest is defined. + */ +const schemaManifest = { + $id: 'azionManifest', + type: 'object', +}; + +export { schemaManifest }; diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts new file mode 100644 index 00000000..dfc67dae --- /dev/null +++ b/packages/config/src/versions/v6/types.ts @@ -0,0 +1,12 @@ +import type { AzionBuild } from '../../types'; + +/** + * Config of the Azion API v6. + * TODO: structure placeholder. Replace with the v6 resources once the schemas are defined. + */ +export type AzionConfigV6 = { + /** Azion API version this config targets. */ + version: 6; + /** Build configuration (shared by every API version). */ + build?: AzionBuild; +}; diff --git a/packages/config/src/versions/v6/validateConfig/index.ts b/packages/config/src/versions/v6/validateConfig/index.ts new file mode 100644 index 00000000..aa8d1727 --- /dev/null +++ b/packages/config/src/versions/v6/validateConfig/index.ts @@ -0,0 +1,14 @@ +import { createConfigValidator } from '../../shared/validateConfig'; +import azionConfigSchema from '../schemas/schema'; +import type { AzionConfigV6 } from '../types'; + +/** + * Validates the provided configuration against the v6 JSON Schema. + * If the configuration is not valid, an exception is thrown with the first validation issues encountered. + * @param {AzionConfigV6 | Record} config - The configuration to be validated. + * @param {object} schema - The JSON Schema to be used for validation. Default is the v6 configuration schema. + * @throws {Error} Throws an error if the configuration fails validation. + */ +const validateConfig = createConfigValidator(azionConfigSchema); + +export { validateConfig }; diff --git a/packages/config/src/versions/v6/validateManifest/index.ts b/packages/config/src/versions/v6/validateManifest/index.ts new file mode 100644 index 00000000..92bfa44f --- /dev/null +++ b/packages/config/src/versions/v6/validateManifest/index.ts @@ -0,0 +1,12 @@ +import { createManifestValidator } from '../../shared/validateManifest'; +import { schemaManifest as azionManifestSchema } from '../schemas/schemaManifest'; + +/** + * Validates the provided manifest against the Azion Manifest Schema (API v6). + * @param {Record} manifest - The manifest to be validated. + * @param {object} schema - Optional JSON Schema overriding the default manifest schema. + * @throws {Error} Throws an error if the manifest fails validation. + */ +const validateManifest = createManifestValidator(azionManifestSchema); + +export { validateManifest }; From 6129916a7b4fa25ee7010471a48c7dfbf8a19d75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 15:58:45 -0300 Subject: [PATCH 02/29] feat(config): add build schema and strategies to API v6 Add the v6 build schema, the build and version process strategies and register them in the v6 context, so the v6 manifest carries version and build. The build schema is the one of v4, moved to versions/shared/schemas and re-exported by v4 and v6 as the entry point of each version. The v6 config schema is now organised in definitions.mainConfig like v4, which the object form of build.preset references. --- packages/config/src/versions/registry.test.ts | 5 +- .../src/versions/shared/schemas/build.ts | 92 +++++++++++++++++++ .../src/versions/v4/schemas/build/index.ts | 91 +----------------- .../buildProcessConfigStrategy.test.ts | 57 ++++++++++++ .../buildProcessConfigStrategy.ts | 28 ++++++ .../versionProcessConfigStrategy.test.ts | 36 ++++++++ .../versionProcessConfigStrategy.ts | 24 +++++ .../src/versions/v6/processStrategy/index.ts | 6 +- .../src/versions/v6/schemas/build/index.ts | 3 + .../config/src/versions/v6/schemas/schema.ts | 23 +++-- .../versions/v6/validateConfig/index.test.ts | 60 ++++++++++++ 11 files changed, 326 insertions(+), 99 deletions(-) create mode 100644 packages/config/src/versions/shared/schemas/build.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/build/index.ts create mode 100644 packages/config/src/versions/v6/validateConfig/index.test.ts diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 92ab32b9..4ea80725 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -146,14 +146,15 @@ describe('v6 support', () => { expect(() => validateConfig({ version: 6, origin: [] })).toThrow(); }); - it('processes a v6 config without leaking version into the manifest', () => { - expect(processConfig(v6Config)).not.toHaveProperty('version'); + it('writes the version and the build to the v6 manifest', () => { + expect(processConfig(v6Config)).toEqual({ version: 6, build: v6Config.build }); }); it('forwards the version to manifest helpers', () => { expect(() => validateManifest({}, undefined, { version: 6 })).not.toThrow(); expect(() => convertJsonConfigToObject('{', { version: 6 })).toThrow('Invalid JSON configuration.'); expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6 }); + expect(convertJsonConfigToObject(JSON.stringify(processConfig(v6Config)), { version: 6 })).toEqual(v6Config); }); it('types defineConfig by the declared version', () => { diff --git a/packages/config/src/versions/shared/schemas/build.ts b/packages/config/src/versions/shared/schemas/build.ts new file mode 100644 index 00000000..1660aae8 --- /dev/null +++ b/packages/config/src/versions/shared/schemas/build.ts @@ -0,0 +1,92 @@ +import { BUILD_BUNDLERS } from '../../../constants'; + +const buildSchema = { + type: 'object', + properties: { + entry: { + oneOf: [ + { type: 'string' }, + { type: 'array', items: { type: 'string' } }, + { type: 'object', additionalProperties: { type: 'string' } }, + ], + errorMessage: "The 'build.entry' must be a string, array of strings, or object with string values", + }, + bundler: { + type: 'string', + enum: BUILD_BUNDLERS, + errorMessage: "The 'build.bundler' must be either 'webpack' or 'esbuild'", + }, + preset: { + anyOf: [ + { type: 'string' }, + { + type: 'object', + properties: { + metadata: { + type: 'object', + properties: { + name: { + type: 'string', + errorMessage: "The 'name' field in preset metadata must be a string", + }, + ext: { + type: 'string', + errorMessage: "The 'ext' field in preset metadata must be a string", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in preset metadata', + required: "The 'name' field is required in preset metadata", + }, + }, + config: { + $ref: '#/definitions/mainConfig', + }, + handler: { instanceof: 'Function' }, + prebuild: { instanceof: 'Function' }, + postbuild: { instanceof: 'Function' }, + }, + required: ['metadata', 'config'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in preset', + required: "Preset must contain both 'metadata' and 'config' properties", + }, + }, + ], + errorMessage: 'Preset must be either a string or an object with preset properties', + }, + polyfills: { + type: 'boolean', + errorMessage: "The 'build.polyfills' must be a boolean", + }, + worker: { + type: 'boolean', + errorMessage: "The 'build.worker' must be a boolean", + }, + extend: { + instanceof: 'Function', + errorMessage: "The 'build.extend' must be a function", + }, + memoryFS: { + type: 'object', + properties: { + injectionDirs: { + type: 'array', + items: { type: 'string' }, + }, + removePathPrefix: { type: 'string' }, + }, + required: ['injectionDirs', 'removePathPrefix'], + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'build' object", + }, +}; + +export default buildSchema; diff --git a/packages/config/src/versions/v4/schemas/build/index.ts b/packages/config/src/versions/v4/schemas/build/index.ts index 54905f9e..51b2fca5 100644 --- a/packages/config/src/versions/v4/schemas/build/index.ts +++ b/packages/config/src/versions/v4/schemas/build/index.ts @@ -1,92 +1,3 @@ -import { BUILD_BUNDLERS } from '../../../../constants'; - -const buildSchema = { - type: 'object', - properties: { - entry: { - oneOf: [ - { type: 'string' }, - { type: 'array', items: { type: 'string' } }, - { type: 'object', additionalProperties: { type: 'string' } }, - ], - errorMessage: "The 'build.entry' must be a string, array of strings, or object with string values", - }, - bundler: { - type: 'string', - enum: BUILD_BUNDLERS, - errorMessage: "The 'build.bundler' must be either 'webpack' or 'esbuild'", - }, - preset: { - anyOf: [ - { type: 'string' }, - { - type: 'object', - properties: { - metadata: { - type: 'object', - properties: { - name: { - type: 'string', - errorMessage: "The 'name' field in preset metadata must be a string", - }, - ext: { - type: 'string', - errorMessage: "The 'ext' field in preset metadata must be a string", - }, - }, - required: ['name'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in preset metadata', - required: "The 'name' field is required in preset metadata", - }, - }, - config: { - $ref: '#/definitions/mainConfig', - }, - handler: { instanceof: 'Function' }, - prebuild: { instanceof: 'Function' }, - postbuild: { instanceof: 'Function' }, - }, - required: ['metadata', 'config'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in preset', - required: "Preset must contain both 'metadata' and 'config' properties", - }, - }, - ], - errorMessage: 'Preset must be either a string or an object with preset properties', - }, - polyfills: { - type: 'boolean', - errorMessage: "The 'build.polyfills' must be a boolean", - }, - worker: { - type: 'boolean', - errorMessage: "The 'build.worker' must be a boolean", - }, - extend: { - instanceof: 'Function', - errorMessage: "The 'build.extend' must be a function", - }, - memoryFS: { - type: 'object', - properties: { - injectionDirs: { - type: 'array', - items: { type: 'string' }, - }, - removePathPrefix: { type: 'string' }, - }, - required: ['injectionDirs', 'removePathPrefix'], - additionalProperties: false, - }, - }, - additionalProperties: false, - errorMessage: { - additionalProperties: "No additional properties are allowed in the 'build' object", - }, -}; +import buildSchema from '../../../shared/schemas/build'; export default buildSchema; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts new file mode 100644 index 00000000..65ea1c84 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.test.ts @@ -0,0 +1,57 @@ +import type { AzionBuild } from '../../../../types'; +import type { AzionConfigV6 } from '../../types'; +import BuildProcessConfigStrategy from './buildProcessConfigStrategy'; + +describe('BuildProcessConfigStrategy (v6)', () => { + let strategy: BuildProcessConfigStrategy; + + beforeEach(() => { + strategy = new BuildProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when no build configuration is provided', () => { + const config: AzionConfigV6 = { version: 6 }; + expect(strategy.transformToManifest(config)).toBeUndefined(); + }); + + it('should transform a complete build configuration to manifest format', () => { + const buildConfig: AzionBuild = { + bundler: 'esbuild', + entry: { main: './src/index.js', worker: './src/worker.js' }, + polyfills: true, + worker: true, + preset: 'next', + memoryFS: { injectionDirs: ['./src/injected'], removePathPrefix: './src' }, + }; + + const result = strategy.transformToManifest({ version: 6, build: buildConfig }); + + expect(result).toEqual(buildConfig); + }); + }); + + describe('transformToConfig', () => { + it('should not set build when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.build).toBeUndefined(); + }); + + it('should transform a build manifest to config format and replace an existing build', () => { + const newBuildConfig: AzionBuild = { bundler: 'esbuild', entry: './src/new-index.js' }; + const transformedPayload: AzionConfigV6 = { + version: 6, + build: { bundler: 'webpack', entry: './src/old-index.js' }, + }; + + const result = strategy.transformToConfig({ build: newBuildConfig }, transformedPayload); + + expect(result).toEqual(newBuildConfig); + expect(transformedPayload.build).toEqual(newBuildConfig); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts new file mode 100644 index 00000000..f01b23c6 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/buildProcessConfigStrategy.ts @@ -0,0 +1,28 @@ +import type { AzionBuild } from '../../../../types'; +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * BuildProcessConfigStrategy + * @class BuildProcessConfigStrategy + * @description This class is implementation of the v6 Build Process Config Strategy. + */ +class BuildProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + const build = config?.build; + if (!build) { + return; + } + const payload: AzionBuild = build; + return payload; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const build = payload?.build; + transformedPayload.build = build; + return transformedPayload.build; + } +} + +export default BuildProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..3955f144 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,36 @@ +import type { AzionConfigV6 } from '../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v6)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 6 })).toBe(6); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({ version: 6 }, transformedPayload); + + expect(result).toBe(6); + expect(transformedPayload.version).toBe(6); + }); + + it('should keep the version of the config when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBe(6); + expect(transformedPayload.version).toBe(6); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..deb100d3 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,24 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + return config?.version; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index e7fa210b..c8619f92 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -1,9 +1,13 @@ import ProcessConfigContext from '../../shared/processStrategy/processConfigContext'; import type { AzionConfigV6 } from '../types'; +import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); - // TODO: register the v6 strategies (setStrategy) as the v6 resources are defined + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); + processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); + // TODO: register the other v6 strategies (setStrategy) as the v6 resources are defined return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/build/index.ts b/packages/config/src/versions/v6/schemas/build/index.ts new file mode 100644 index 00000000..51b2fca5 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/build/index.ts @@ -0,0 +1,3 @@ +import buildSchema from '../../../shared/schemas/build'; + +export default buildSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index 2321605a..0d1b48ed 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -1,15 +1,26 @@ +import buildSchema from './build'; + /** * JSON Schema of the v6 config. - * TODO: placeholder. Only `version` and `build` are accepted until the v6 schemas are defined. + * TODO: only `version` and `build` are accepted until the schemas of the other v6 resources are defined. */ const azionConfigSchema = { $id: 'azionConfig', - type: 'object', - additionalProperties: false, - properties: { - version: { const: 6 }, - build: { type: 'object' }, + definitions: { + mainConfig: { + type: 'object', + properties: { + version: { type: 'number', enum: [6] }, + build: buildSchema, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'Config can only contain the following properties: version, build', + type: 'Configuration must be an object', + }, + }, }, + $ref: '#/definitions/mainConfig', }; export default azionConfigSchema; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts new file mode 100644 index 00000000..80bba21b --- /dev/null +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -0,0 +1,60 @@ +import { validateConfig } from '.'; + +describe('validateConfig (v6)', () => { + describe('build', () => { + it('accepts a complete build config', () => { + expect(() => + validateConfig({ + version: 6, + build: { + bundler: 'esbuild', + entry: { main: './src/index.js' }, + preset: 'next', + polyfills: true, + worker: false, + memoryFS: { injectionDirs: ['./src/injected'], removePathPrefix: './src' }, + }, + }), + ).not.toThrow(); + }); + + it('accepts a preset declared as an object', () => { + expect(() => + validateConfig({ + version: 6, + build: { + preset: { metadata: { name: 'custom' }, config: { version: 6, build: { bundler: 'esbuild' } } }, + }, + }), + ).not.toThrow(); + }); + + it('rejects an invalid bundler', () => { + expect(() => validateConfig({ version: 6, build: { bundler: 'rollup' } })).toThrow( + "The 'build.bundler' must be either 'webpack' or 'esbuild'", + ); + }); + + it('rejects unknown properties in build', () => { + expect(() => validateConfig({ version: 6, build: { unknown: true } })).toThrow( + "No additional properties are allowed in the 'build' object", + ); + }); + + it('rejects an invalid entry', () => { + expect(() => validateConfig({ version: 6, build: { entry: 1 } })).toThrow( + "The 'build.entry' must be a string, array of strings, or object with string values", + ); + }); + }); + + it('rejects properties the v6 schema does not know yet', () => { + expect(() => validateConfig({ version: 6, applications: [] })).toThrow( + 'Config can only contain the following properties: version, build', + ); + }); + + it('rejects another version', () => { + expect(() => validateConfig({ version: 4, build: {} })).toThrow(); + }); +}); From f33e017786474196553f50c11f6b181a987763b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 15:59:09 -0300 Subject: [PATCH 03/29] feat(config): write the API version to the v3 and v4 manifests Add a version process strategy to v3 and v4, as v6 has, so every manifest carries the version of the API it targets (the default one, 4, when a v4 config does not declare it). The v3 golden fixtures stay frozen: the golden tests add version to the expected manifest instead. --- packages/config/src/versions/registry.test.ts | 7 ++-- .../src/versions/v3/__fixtures__/README.md | 3 ++ .../config/src/versions/v3/golden.test.ts | 3 +- .../versionProcessConfigStrategy.test.ts | 40 +++++++++++++++++++ .../versionProcessConfigStrategy.ts | 24 +++++++++++ .../src/versions/v3/processStrategy/index.ts | 2 + .../versionProcessConfigStrategy.test.ts | 40 +++++++++++++++++++ .../versionProcessConfigStrategy.ts | 26 ++++++++++++ .../src/versions/v4/processStrategy/index.ts | 2 + packages/presets/src/presets/configs.test.ts | 3 +- 10 files changed, 145 insertions(+), 5 deletions(-) create mode 100644 packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 4ea80725..27fc69f1 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -55,8 +55,9 @@ describe('version dispatch', () => { expect(processConfig({ ...config, version: 4 })).toEqual(processConfig(config)); }); - it('does not leak version into the manifest', () => { - expect(processConfig({ ...config, version: 4 })).not.toHaveProperty('version'); + it('writes the version to the manifest, the default one when it is not declared', () => { + expect(processConfig({ ...config, version: 4 })).toHaveProperty('version', 4); + expect(processConfig(config)).toHaveProperty('version', 4); }); it('rejects a config that declares an unsupported version', () => { @@ -106,7 +107,7 @@ describe('v3 support', () => { expect(manifest).toHaveProperty('origin'); expect(manifest).toHaveProperty('rules'); expect(manifest).not.toHaveProperty('applications'); - expect(manifest).not.toHaveProperty('version'); + expect(manifest).toHaveProperty('version', 3); }); it('rejects v3-only fields on a v4 config and vice versa', () => { diff --git a/packages/config/src/versions/v3/__fixtures__/README.md b/packages/config/src/versions/v3/__fixtures__/README.md index 1fa3cf1c..0b0840c3 100644 --- a/packages/config/src/versions/v3/__fixtures__/README.md +++ b/packages/config/src/versions/v3/__fixtures__/README.md @@ -22,4 +22,7 @@ generates: - `nuxt` does not declare `build.polyfills`, as its v4 config. - `emscripten` uses `bundler: 'webpack'`, as its v4 config (its `extend` is a webpack configuration). +- The manifest of this implementation also carries `version: 3` (written by `VersionProcessConfigStrategy`). The fixtures + do not have it, so `golden.test.ts` and the presets test add it to the expected manifest instead of changing the files. + Everything else is exactly what the original implementation produced. diff --git a/packages/config/src/versions/v3/golden.test.ts b/packages/config/src/versions/v3/golden.test.ts index 86b23676..a3a5199c 100644 --- a/packages/config/src/versions/v3/golden.test.ts +++ b/packages/config/src/versions/v3/golden.test.ts @@ -19,6 +19,7 @@ describe('v3 golden manifests (generated by the original 1.20.x implementation)' const config = { ...read(`${preset}.input.json`), version: 3 }; expect(() => validateConfig(config)).not.toThrow(); - expect(processConfig(config)).toEqual(read(`${preset}.manifest.json`)); + // the fixtures are frozen, so the `version` the v3 manifest carries is added here (see __fixtures__/README.md) + expect(processConfig(config)).toEqual({ version: 3, ...read(`${preset}.manifest.json`) }); }); }); diff --git a/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..12935be2 --- /dev/null +++ b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,40 @@ +import type { AzionConfig } from '../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v3)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 3 })).toBe(3); + }); + + it('should write the API version 3 when the config does not declare one', () => { + expect(strategy.transformToManifest({})).toBe(3); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({ version: 3 }, transformedPayload); + + expect(result).toBe(3); + expect(transformedPayload.version).toBe(3); + }); + + it('should leave the config without version when the manifest has none', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.version).toBeUndefined(); + }); + }); +}); diff --git a/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..ded2f994 --- /dev/null +++ b/packages/config/src/versions/v3/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,24 @@ +import { AzionConfig } from '../../types'; +import ProcessConfigStrategy from '../processConfigStrategy'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfig) { + return config?.version ?? 3; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfig) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v3/processStrategy/index.ts b/packages/config/src/versions/v3/processStrategy/index.ts index bb8ece4d..f27c15e5 100644 --- a/packages/config/src/versions/v3/processStrategy/index.ts +++ b/packages/config/src/versions/v3/processStrategy/index.ts @@ -9,9 +9,11 @@ import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigS import ProcessConfigContext from './processConfigContext'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; import FirewallProcessConfigStrategy from './implementations/secure/firewallProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('origin', new OriginProcessConfigStrategy()); processConfigContext.setStrategy('cache', new CacheProcessConfigStrategy()); diff --git a/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts new file mode 100644 index 00000000..4e6f6a55 --- /dev/null +++ b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.test.ts @@ -0,0 +1,40 @@ +import type { AzionConfig } from '../../../../types'; +import VersionProcessConfigStrategy from './versionProcessConfigStrategy'; + +describe('VersionProcessConfigStrategy (v4)', () => { + let strategy: VersionProcessConfigStrategy; + + beforeEach(() => { + strategy = new VersionProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should write the version of the config to the manifest', () => { + expect(strategy.transformToManifest({ version: 4 })).toBe(4); + }); + + it('should write the API version 4 when the config does not declare one', () => { + expect(strategy.transformToManifest({})).toBe(4); + }); + }); + + describe('transformToConfig', () => { + it('should read the version of the manifest into the config', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({ version: 4 }, transformedPayload); + + expect(result).toBe(4); + expect(transformedPayload.version).toBe(4); + }); + + it('should leave the config without version when the manifest has none', () => { + const transformedPayload: AzionConfig = {}; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toBeUndefined(); + expect(transformedPayload.version).toBeUndefined(); + }); + }); +}); diff --git a/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts new file mode 100644 index 00000000..42598957 --- /dev/null +++ b/packages/config/src/versions/v4/processStrategy/implementations/versionProcessConfigStrategy.ts @@ -0,0 +1,26 @@ +import type { AzionConfig } from '../../../../types'; +import { DEFAULT_API_VERSION } from '../../../types'; +import ProcessConfigStrategy from '../processConfigStrategy'; + +/** + * VersionProcessConfigStrategy + * @class VersionProcessConfigStrategy + * @description Writes the API version to the manifest and reads it back into the config. + * A config that does not declare `version` targets the default version. + */ +class VersionProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfig) { + return config?.version ?? DEFAULT_API_VERSION; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfig) { + const version = payload?.version; + if (version !== undefined) { + transformedPayload.version = version; + } + return transformedPayload.version; + } +} + +export default VersionProcessConfigStrategy; diff --git a/packages/config/src/versions/v4/processStrategy/index.ts b/packages/config/src/versions/v4/processStrategy/index.ts index 1dfeea2c..05b00432 100644 --- a/packages/config/src/versions/v4/processStrategy/index.ts +++ b/packages/config/src/versions/v4/processStrategy/index.ts @@ -9,12 +9,14 @@ import FirewallProcessConfigStrategy from './implementations/secure/firewallProc import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; +import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; import WorkloadDeploymentsProcessConfigStrategy from './implementations/workloadDeploymentsProcessConfigStrategy'; import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import ProcessConfigContext from './processConfigContext'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); + processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); processConfigContext.setStrategy('network_list', new NetworkListProcessConfigStrategy()); diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index e8e1a0b6..a892f6c0 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -51,7 +51,8 @@ describe('preset configs by API version', () => { const config = resolvePresetConfig(byName(name), 3); expect(() => validateConfig(config)).not.toThrow(); // the golden is JSON, so compare through JSON as well (drops `undefined` fields) - expect(JSON.parse(JSON.stringify(processConfig(config)))).toEqual(golden(name, 'manifest')); + // the fixtures are frozen and do not carry the `version` the v3 manifest has (see v3/__fixtures__/README.md) + expect(JSON.parse(JSON.stringify(processConfig(config)))).toEqual({ version: 3, ...golden(name, 'manifest') }); }); }); From 70f18cdc4edf143746bd026cfa49525e5c7f8053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 15:59:20 -0300 Subject: [PATCH 04/29] feat(presets): add the v6 config to the javascript preset The v6 config only carries the build for now, as the v6 config schema does not have the other resources yet. --- packages/presets/src/presets/configs.test.ts | 19 ++++++++++++++++++- .../src/presets/javascript/config.v6.ts | 11 +++++++++++ .../presets/src/presets/javascript/index.ts | 3 ++- 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 packages/presets/src/presets/javascript/config.v6.ts diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index a892f6c0..10c0dcec 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -36,7 +36,24 @@ describe('preset configs by API version', () => { it('has a v3 config for every preset that existed on v3', () => { expect(goldenPresets.length).toBe(24); - goldenPresets.forEach((name) => expect(getPresetApiVersions(byName(name))).toEqual([3, 4])); + goldenPresets.forEach((name) => expect(getPresetApiVersions(byName(name))).toEqual(expect.arrayContaining([3, 4]))); + }); + + describe('v6', () => { + it('is declared by javascript only for now', () => { + const withV6 = presets.filter((preset) => preset.configs?.[6]).map((preset) => preset.metadata.name); + expect(withV6).toEqual(['javascript']); + expect(getPresetApiVersions(byName('javascript'))).toEqual([3, 4, 6]); + expect(() => resolvePresetConfig(byName('react'), 6)).toThrow('does not support config version 6'); + }); + + it('javascript: validates and keeps the build of the v4 config', () => { + const config = resolvePresetConfig(byName('javascript'), 6); + expect(config.version).toBe(6); + expect(() => validateConfig(config)).not.toThrow(); + expect(config.build).toEqual(resolvePresetConfig(byName('javascript'), 4).build); + expect(processConfig(config)).toEqual({ version: 6, build: { entry: 'index.js' } }); + }); }); describe.each(goldenPresets)('%s (v3)', (name) => { diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts new file mode 100644 index 00000000..24871713 --- /dev/null +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -0,0 +1,11 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +// TODO: add the remaining v6 resources (functions, applications, workloads...) once their schemas are defined +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + }, +}; + +export default config; diff --git a/packages/presets/src/presets/javascript/index.ts b/packages/presets/src/presets/javascript/index.ts index cb5d7587..1ae396ad 100644 --- a/packages/presets/src/presets/javascript/index.ts +++ b/packages/presets/src/presets/javascript/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; -export const javascript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata }; +export const javascript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata }; From 6191ea4f8e98e90b3329eda168fc1413807d1102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 17:04:49 -0300 Subject: [PATCH 05/29] feat(config): add applications, functions and rules to API v6 Add the v6 schemas and process strategies of the applications, the functions, the rules of an application (request and response phases) and its function instances, based on v4 and checked against the v6 API requests: - the name of an application and of a rule has at most 100 characters - the rule variables follow the phase table of ApplicationCriterionField: tcpinfo_rtt is also available in request, server_addr, server_port and ssl_client_* are also available in response, sent_http_name does not exist v6 has its own constants (v6/constants.ts). Function bindings (storage) and the connector validation of set_connector are left out until the v6 config has storage and connectors. The v6 accessor reads the application name from applications. --- .../config/src/versions/accessors.test.ts | 2 + packages/config/src/versions/registry.test.ts | 35 ++- packages/config/src/versions/v6/constants.ts | 93 +++++++ packages/config/src/versions/v6/index.ts | 5 +- .../applicationProcessConfigStrategy.test.ts | 186 ++++++++++++++ .../applicationProcessConfigStrategy.ts | 85 ++++++ ...tionInstancesProcessConfigStrategy.test.ts | 53 ++++ .../functionInstancesProcessConfigStrategy.ts | 69 +++++ .../rulesProcessConfigStrategy.test.ts | 97 +++++++ .../application/rulesProcessConfigStrategy.ts | 184 +++++++++++++ .../functionsProcessConfigStrategy.test.ts | 101 ++++++++ .../functionsProcessConfigStrategy.ts | 60 +++++ .../src/versions/v6/processStrategy/index.ts | 4 + .../schemas/applications/behaviors/index.ts | 217 ++++++++++++++++ .../versions/v6/schemas/applications/index.ts | 243 ++++++++++++++++++ .../versions/v6/schemas/functions/index.ts | 47 ++++ .../config/src/versions/v6/schemas/schema.ts | 9 +- packages/config/src/versions/v6/types.ts | 39 ++- .../versions/v6/validateConfig/index.test.ts | 208 ++++++++++++++- 19 files changed, 1724 insertions(+), 13 deletions(-) create mode 100644 packages/config/src/versions/v6/constants.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/applications/behaviors/index.ts create mode 100644 packages/config/src/versions/v6/schemas/applications/index.ts create mode 100644 packages/config/src/versions/v6/schemas/functions/index.ts diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index 25771d5a..27b13b8f 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -20,6 +20,8 @@ describe('version accessors', () => { expect(getApplicationName(v4)).toBe('app-1'); expect(getApplicationName({})).toBeUndefined(); expect(getApplicationName(v3)).toBeUndefined(); + expect(getApplicationName({ version: 6, applications: [{ name: 'app-6' }] })).toBe('app-6'); + expect(getApplicationName({ version: 6 })).toBeUndefined(); }); it('reads the storage where each version keeps it', () => { diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 27fc69f1..a186367f 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -139,7 +139,7 @@ describe('v6 support', () => { it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { expect(() => validateConfig(v6Config)).not.toThrow(); - expect(() => validateConfig({ version: 6, applications: [] })).toThrow(); + expect(() => validateConfig({ version: 6, workloads: [] })).toThrow(); }); it('does not accept v6 on the v4 schema nor the other way around', () => { @@ -147,15 +147,40 @@ describe('v6 support', () => { expect(() => validateConfig({ version: 6, origin: [] })).toThrow(); }); - it('writes the version and the build to the v6 manifest', () => { - expect(processConfig(v6Config)).toEqual({ version: 6, build: v6Config.build }); + it('writes the version, the build and the applications to the v6 manifest', () => { + expect(processConfig(v6Config)).toEqual({ + version: 6, + build: v6Config.build, + functions: [], + applications: [], + }); + }); + + it('processes the v6 applications into the manifest', () => { + const manifest = processConfig({ ...v6Config, applications: [{ name: 'my-app' }] }); + expect(manifest.applications).toEqual([ + { + name: 'my-app', + active: true, + debug: false, + modules: { + cache: { enabled: true }, + functions: { enabled: false }, + application_accelerator: { enabled: true }, + image_processor: { enabled: false }, + }, + }, + ]); }); it('forwards the version to manifest helpers', () => { expect(() => validateManifest({}, undefined, { version: 6 })).not.toThrow(); expect(() => convertJsonConfigToObject('{', { version: 6 })).toThrow('Invalid JSON configuration.'); - expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6 }); - expect(convertJsonConfigToObject(JSON.stringify(processConfig(v6Config)), { version: 6 })).toEqual(v6Config); + expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6, applications: [] }); + expect(convertJsonConfigToObject(JSON.stringify(processConfig(v6Config)), { version: 6 })).toEqual({ + ...v6Config, + applications: [], + }); }); it('types defineConfig by the declared version', () => { diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts new file mode 100644 index 00000000..99e9a608 --- /dev/null +++ b/packages/config/src/versions/v6/constants.ts @@ -0,0 +1,93 @@ +// Constants of the Azion API v6 config. Variables are the ones of `ApplicationCriterionField` of the v6 API. + +/** Variables available in the request and in the response phase. */ +export const COMMON_VARIABLES = [ + 'args', + 'device_group', + 'geoip_city_continent_code', + 'geoip_city_country_code', + 'geoip_city_country_name', + 'geoip_city', + 'geoip_continent_code', + 'geoip_country_code', + 'geoip_country_name', + 'geoip_region_name', + 'geoip_region', + 'host', + 'domain', + 'remote_addr', + 'remote_user', + 'request_method', + 'request_uri', + 'request', + 'scheme', + 'uri', + 'server_addr', + 'server_port', + 'ssl_client_cert', + 'ssl_client_escaped_cert', + 'ssl_client_fingerprint', + 'ssl_client_i_dn', + 'ssl_client_s_dn_parsed', + 'ssl_client_s_dn', + 'ssl_client_serial', + 'ssl_client_v_end', + 'ssl_client_v_remain', + 'ssl_client_v_start', + 'ssl_client_verify', + 'tcpinfo_rtt', + 'remote_port', + 'request_body', +] as const; + +/** Variables available only in the response phase. */ +export const RESPONSE_ONLY_VARIABLES = ['status', 'upstream_addr', 'upstream_status'] as const; + +export const SPECIAL_VARIABLES = ['cookie_time_offset', 'encode_base64'] as const; + +export const ALL_REQUEST_VARIABLES = [...COMMON_VARIABLES] as const; + +export const ALL_RESPONSE_VARIABLES = [...COMMON_VARIABLES, ...RESPONSE_ONLY_VARIABLES] as const; + +export const RULE_OPERATORS_WITH_VALUE = [ + 'is_equal', + 'is_not_equal', + 'starts_with', + 'does_not_start_with', + 'matches', + 'does_not_match', +] as const; + +export const RULE_OPERATORS_WITHOUT_VALUE = ['exists', 'does_not_exist'] as const; + +export const RULE_CONDITIONALS = ['if', 'and', 'or'] as const; + +export const NO_ARGS_BEHAVIORS = [ + 'deny', + 'no_content', + 'deliver', + 'finish_request_phase', + 'forward_cookies', + 'optimize_images', + 'bypass_cache', + 'enable_gzip', + 'redirect_http_to_https', +] as const; + +export const STRING_BEHAVIORS = ['redirect_to_301', 'redirect_to_302', 'rewrite_request'] as const; + +export const ID_BEHAVIORS = ['run_function', 'set_cache_policy', 'set_connector', 'set_origin'] as const; + +export const HEADER_BEHAVIORS = [ + 'add_request_header', + 'add_response_header', + 'filter_request_header', + 'filter_response_header', +] as const; + +export const COOKIE_BEHAVIORS = [ + 'add_request_cookie', + 'filter_request_cookie', + 'set_cookie', + 'filter_response_cookie', +] as const; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts index 4f607e78..3046366a 100644 --- a/packages/config/src/versions/v6/index.ts +++ b/packages/config/src/versions/v6/index.ts @@ -2,11 +2,12 @@ import type { ConfigVersionAccessors, ConfigVersionModule } from '../types'; import { convertJsonConfigToObject } from './converterJsonConfig'; import { factoryProcessContext } from './processStrategy'; import { validateConfig } from './validateConfig'; +import type { AzionConfigV6 } from './types'; import { validateManifest } from './validateManifest'; const accessors: ConfigVersionAccessors = { - // TODO: define where v6 keeps the application name, the storage and the firewall keys - getApplicationName: () => undefined, + getApplicationName: (config) => (config as AzionConfigV6).applications?.[0]?.name, + // TODO: define where v6 keeps the storage and the firewall keys getStorage: () => undefined, firewallReplacedKeys: [], }; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts new file mode 100644 index 00000000..2532b8e6 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts @@ -0,0 +1,186 @@ +import type { AzionConfigV6 } from '../../../types'; +import ApplicationProcessConfigStrategy from './applicationProcessConfigStrategy'; + +describe('ApplicationProcessConfigStrategy (v6)', () => { + let strategy: ApplicationProcessConfigStrategy; + + beforeEach(() => { + strategy = new ApplicationProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no applications', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults to a minimal application', () => { + const result = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(result).toEqual([ + { + name: 'my-app', + active: true, + debug: false, + modules: { + cache: { enabled: true }, + functions: { enabled: false }, + application_accelerator: { enabled: true }, + image_processor: { enabled: false }, + }, + }, + ]); + }); + + it('should map every field of the application to the manifest', () => { + const result = strategy.transformToManifest({ + version: 6, + applications: [ + { + name: 'my-app', + active: false, + debug: true, + edgeCacheEnabled: false, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: true, + }, + ], + }); + + expect(result).toEqual([ + { + name: 'my-app', + active: false, + debug: true, + modules: { + cache: { enabled: false }, + functions: { enabled: true }, + application_accelerator: { enabled: false }, + image_processor: { enabled: true }, + }, + }, + ]); + }); + }); + + describe('rules and function instances', () => { + const config: AzionConfigV6 = { + version: 6, + functions: [{ name: 'fn', path: './fn.js' }], + applications: [ + { + name: 'my-app', + rules: { + request: [ + { + name: 'Execute Function', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + ], + }, + functionsInstances: [{ name: 'instance', ref: 'fn' }], + }, + ], + }; + + it('should write rules and function instances to the manifest', () => { + const [application] = strategy.transformToManifest(config); + + expect(application.rules).toHaveLength(1); + expect(application.rules[0]).toEqual(expect.objectContaining({ phase: 'request' })); + expect(application.functions_instances).toEqual([{ name: 'instance', function: 'fn', args: {}, active: true }]); + }); + + it('should enable the functions module when the application has function instances', () => { + const [application] = strategy.transformToManifest(config); + expect(application.modules.functions.enabled).toBe(true); + }); + + it('should not write rules and function instances when the application has none', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('rules'); + expect(application).not.toHaveProperty('functions_instances'); + }); + + it('should round trip rules and function instances through the manifest', () => { + const manifest = { applications: strategy.transformToManifest(config) }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig(manifest, transformedPayload); + const [application] = transformedPayload.applications!; + + expect(application.rules?.request?.[0].name).toBe('Execute Function'); + expect(application.functionsInstances).toEqual([{ name: 'instance', ref: 'fn', args: {}, active: true }]); + expect(application.functionsEnabled).toBe(true); + }); + }); + + describe('transformToConfig', () => { + it('should set an empty array when the manifest has no applications', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + const result = strategy.transformToConfig({}, transformedPayload); + + expect(result).toEqual([]); + expect(transformedPayload.applications).toEqual([]); + }); + + it('should map the manifest application back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + const payload = { + applications: [ + { + name: 'my-app', + active: false, + debug: true, + modules: { + cache: { enabled: false }, + functions: { enabled: true }, + application_accelerator: { enabled: false }, + image_processor: { enabled: true }, + }, + }, + ], + }; + + strategy.transformToConfig(payload, transformedPayload); + + expect(transformedPayload.applications).toEqual([ + { + name: 'my-app', + active: false, + debug: true, + edgeCacheEnabled: false, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: true, + }, + ]); + }); + + it('should round trip a config through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + applications: [ + { + name: 'my-app', + active: true, + debug: false, + edgeCacheEnabled: true, + functionsEnabled: false, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + }, + ], + }; + const manifest = { applications: strategy.transformToManifest(config) }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig(manifest, transformedPayload); + + expect(transformedPayload).toEqual(config); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts new file mode 100644 index 00000000..d236f100 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -0,0 +1,85 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionApplicationV6, AzionConfigV6 } from '../../../types'; +import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; +import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; + +/** + * ApplicationProcessConfigStrategy + * @class ApplicationProcessConfigStrategy + * @description Converts the v6 applications between the config and the manifest. + * TODO: convert the remaining resources of an application (cache settings, device groups). + */ +class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { + private rulesStrategy = new RulesProcessConfigStrategy(); + private functionInstancesStrategy = new FunctionInstancesProcessConfigStrategy(); + + transformToManifest(config: AzionConfigV6) { + if (!config.applications || !Array.isArray(config.applications)) { + return []; + } + + return config.applications.map((app: AzionApplicationV6) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const application: Record = { + name: app.name, + active: app.active ?? true, + debug: app.debug ?? false, + modules: { + cache: { + enabled: app.edgeCacheEnabled ?? true, + }, + functions: { + enabled: + app.functionsEnabled || (app.functionsInstances && app.functionsInstances.length > 0) ? true : false, + }, + application_accelerator: { + enabled: app.applicationAcceleratorEnabled ?? true, + }, + image_processor: { + enabled: app.imageProcessorEnabled ?? false, + }, + }, + }; + + if (app.rules) { + application.rules = this.rulesStrategy.transformToManifest(app.rules, config.functions); + } + + if (app.functionsInstances) { + application.functions_instances = this.functionInstancesStrategy.transformToManifest( + app.functionsInstances, + config, + ); + } + + return application; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + if (!payload.applications || !Array.isArray(payload.applications)) { + transformedPayload.applications = []; + return transformedPayload.applications; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.applications = payload.applications.map((app: any) => ({ + name: app.name, + active: app.active, + debug: app.debug, + edgeCacheEnabled: app.modules?.cache?.enabled, + functionsEnabled: app.modules?.functions?.enabled, + applicationAcceleratorEnabled: app.modules?.application_accelerator?.enabled, + imageProcessorEnabled: app.modules?.image_processor?.enabled, + rules: app.rules ? this.rulesStrategy.transformToConfig(app.rules) : undefined, + functionsInstances: app.functions_instances + ? this.functionInstancesStrategy.transformToConfig(app.functions_instances) + : undefined, + })); + + return transformedPayload.applications; + } +} + +export default ApplicationProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..6598595c --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts @@ -0,0 +1,53 @@ +import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; + +describe('FunctionInstancesProcessConfigStrategy (v6)', () => { + let strategy: FunctionInstancesProcessConfigStrategy; + + beforeEach(() => { + strategy = new FunctionInstancesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + const config = { version: 6 as const, functions: [{ name: 'fn', path: './fn.js' }] }; + + it('should return undefined when there are no instances', () => { + expect(strategy.transformToManifest([], config)).toBeUndefined(); + }); + + it('should map an instance to the manifest and apply the defaults', () => { + expect(strategy.transformToManifest([{ name: 'instance', ref: 'fn' }], config)).toEqual([ + { name: 'instance', function: 'fn', args: {}, active: true }, + ]); + expect(strategy.transformToManifest([{ name: 'i', ref: 'fn', args: { a: 1 }, active: false }], config)).toEqual([ + { name: 'i', function: 'fn', args: { a: 1 }, active: false }, + ]); + }); + + it('should throw when a referenced function name is not defined', () => { + expect(() => strategy.transformToManifest([{ name: 'instance', ref: 'missing' }], config)).toThrow( + 'Function instance "instance" references non-existent Function "missing".', + ); + expect(() => strategy.transformToManifest([{ name: 'instance', ref: 'fn' }], { version: 6 })).toThrow( + 'references non-existent Function "fn"', + ); + }); + + it('should not validate a function referenced by id', () => { + expect(strategy.transformToManifest([{ name: 'instance', ref: 10 }], { version: 6 })).toEqual([ + { name: 'instance', function: 10, args: {}, active: true }, + ]); + }); + }); + + describe('transformToConfig', () => { + it('should return an empty array when there is nothing to convert', () => { + expect(strategy.transformToConfig([])).toEqual([]); + }); + + it('should map the manifest instances back to the config', () => { + expect(strategy.transformToConfig([{ name: 'i', function: 10, args: { a: 1 } }])).toEqual([ + { name: 'i', ref: 10, args: { a: 1 }, active: true }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts new file mode 100644 index 00000000..e9be0cfe --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts @@ -0,0 +1,69 @@ +import type { AzionFunctionInstance } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionFunctionV6 } from '../../../types'; + +/** + * FunctionInstancesProcessConfigStrategy V6 + * @class FunctionInstancesProcessConfigStrategy + * @description This class is implementation of the Function Instances Process Config Strategy for API V6. + */ +class FunctionInstancesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that referenced Function exists + */ + private validateFunctionReference( + functions: AzionFunctionV6[] | undefined, + functionNameOrId: string | number, + instanceName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof functionNameOrId === 'string') { + if (!Array.isArray(functions) || !functions.find((func) => func.name === functionNameOrId)) { + throw new Error(`Function instance "${instanceName}" references non-existent Function "${functionNameOrId}".`); + } + } + } + + /** + * Transform azion.config Function Instances to V6 manifest format + */ + transformToManifest(functionInstances: AzionFunctionInstance[], config: AzionConfigV6) { + if (!Array.isArray(functionInstances) || functionInstances.length === 0) { + return; + } + + return functionInstances.map((instance) => { + // Validate Function reference + this.validateFunctionReference(config.functions, instance.ref, instance.name); + + return { + name: instance.name, + function: instance.ref, + args: instance.args || {}, + active: instance.active ?? true, + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config Function Instances + * Note: the API returns function as ID, but azion.config expects function name. + * The CLI should resolve ID to name before calling this method. + */ + transformToConfig( + payload: Array<{ name: string; function: number | string; args?: Record; active?: boolean }>, + ): AzionFunctionInstance[] { + if (!Array.isArray(payload) || payload.length === 0) { + return []; + } + + return payload.map((instance) => ({ + name: instance.name, + ref: instance.function, + args: instance.args, + active: instance.active ?? true, + })); + } +} + +export default FunctionInstancesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..c2666d89 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.test.ts @@ -0,0 +1,97 @@ +import type { AzionManifestRule, AzionRules } from '../../../../../types'; +import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; + +describe('RulesProcessConfigStrategy (v6)', () => { + let strategy: RulesProcessConfigStrategy; + + const rules: AzionRules = { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + ], + response: [ + { + name: 'Add header', + active: false, + criteria: [[{ variable: 'status', conditional: 'if', operator: 'exists' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], + }, + ], + }; + + const manifest: AzionManifestRule[] = [ + { + phase: 'request', + rule: { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], + }, + }, + { + phase: 'response', + rule: { + name: 'Add header', + description: undefined, + active: false, + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'exists' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], + }, + }, + ]; + + beforeEach(() => { + strategy = new RulesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no rules', () => { + expect(strategy.transformToManifest({})).toEqual([]); + }); + + it('should map request and response rules with their phase, wrapping the variables in ${}', () => { + expect(strategy.transformToManifest(rules, [{ name: 'fn', path: './fn.js' }])).toEqual(manifest); + }); + + it('should throw when run_function references a function that is not defined', () => { + expect(() => strategy.transformToManifest(rules, [{ name: 'other', path: './o.js' }])).toThrow( + 'Function "fn" referenced in rule "Execute Function" is not defined in the functions array.', + ); + }); + + it('should not validate a function referenced by id', () => { + const byId: AzionRules = { + request: [{ ...rules.request![0], behaviors: [{ type: 'run_function', attributes: { value: 10 } }] }], + }; + expect(() => strategy.transformToManifest(byId, [])).not.toThrow(); + }); + + it('should not validate the function references when the config has no functions', () => { + expect(() => strategy.transformToManifest(rules)).not.toThrow(); + }); + }); + + describe('transformToConfig', () => { + it('should return empty rules when the manifest is not an array', () => { + expect(strategy.transformToConfig(undefined as unknown as AzionManifestRule[])).toEqual({ + request: [], + response: [], + }); + }); + + it('should split the manifest rules by phase back into the config', () => { + const result = strategy.transformToConfig(manifest); + + expect(result.request).toHaveLength(1); + expect(result.response).toHaveLength(1); + expect(result.request![0]).toEqual(expect.objectContaining({ name: 'Execute Function', active: true })); + expect(result.response![0]).toEqual(expect.objectContaining({ name: 'Add header', active: false })); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts new file mode 100644 index 00000000..18ad31e0 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts @@ -0,0 +1,184 @@ +import type { + AzionManifestRule, + AzionRule, + AzionRuleBehavior, + AzionRuleCriteriaArray, + AzionRules, + RuleVariable, +} from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionFunctionV6 } from '../../../types'; + +/** + * RulesProcessConfigStrategy + * @class RulesProcessConfigStrategy + * @description This class is implementation of the Rules ProcessConfig Strategy for V6. + * TODO: validate the connectors referenced by `set_connector` once the v6 config has connectors. + */ +class RulesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validates function references in rules + */ + private validateFunctionReferences(applicationRules: AzionRules, functions?: AzionFunctionV6[]) { + if (!functions) return; + + const definedFunctions = new Set(functions.map((f) => f.name)); + + // Check request rules + if (applicationRules.request) { + for (const rule of applicationRules.request) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'run_function' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedFunctions.has(behavior.attributes.value)) { + throw new Error( + `Function "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the functions array.`, + ); + } + } + } + } + } + + // Check response rules + if (applicationRules.response) { + for (const rule of applicationRules.response) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'run_function' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedFunctions.has(behavior.attributes.value)) { + throw new Error( + `Function "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the functions array.`, + ); + } + } + } + } + } + } + + /** + * Transforms azion.config rules to API manifest format + */ + transformToManifest(applicationRules: AzionRules, functions?: AzionFunctionV6[]): AzionManifestRule[] { + // Validate function references + this.validateFunctionReferences(applicationRules, functions); + + const payload: AzionManifestRule[] = []; + + if (!applicationRules || Object.keys(applicationRules).length === 0) { + return payload; + } + + // Process request rules + if (Array.isArray(applicationRules.request)) { + applicationRules.request.forEach((rule) => { + const manifestRule: AzionManifestRule = { + phase: 'request', + rule: { + name: rule.name, + description: rule.description, + active: rule.active !== undefined ? rule.active : true, + criteria: rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ) as AzionRuleCriteriaArray, + behaviors: rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }, + }; + payload.push(manifestRule); + }); + } + + // Process response rules + if (Array.isArray(applicationRules.response)) { + applicationRules.response.forEach((rule) => { + const manifestRule: AzionManifestRule = { + phase: 'response', + rule: { + name: rule.name, + description: rule.description, + active: rule.active !== undefined ? rule.active : true, + criteria: rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ) as AzionRuleCriteriaArray, + behaviors: rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }, + }; + payload.push(manifestRule); + }); + } + + return payload; + } + + /** + * Transforms API manifest format back to azion.config rules + */ + transformToConfig(rulesPayload: AzionManifestRule[]): AzionRules { + if (!Array.isArray(rulesPayload)) { + return { request: [], response: [] }; + } + + const rules: AzionRules = { + request: [], + response: [], + }; + + rulesPayload.forEach((manifestRule) => { + const rule: AzionRule = { + name: manifestRule.rule.name, + description: manifestRule.rule.description, + active: manifestRule.rule.active !== undefined ? manifestRule.rule.active : true, + criteria: manifestRule.rule.criteria.map((criteriaGroup) => + criteriaGroup.map((criterion) => { + const baseCriterion = { + variable: criterion.variable as RuleVariable, + conditional: criterion.conditional, + operator: criterion.operator, + }; + + // Add argument if present + if ('argument' in criterion && criterion.argument !== undefined) { + return { + ...baseCriterion, + argument: criterion.argument, + }; + } + + return baseCriterion; + }), + ) as AzionRuleCriteriaArray, + behaviors: manifestRule.rule.behaviors.map((behavior) => ({ + type: behavior.type, + ...('attributes' in behavior && behavior.attributes && { attributes: behavior.attributes }), + })) as AzionRuleBehavior[], + }; + + if (manifestRule.phase === 'request') { + rules.request!.push(rule); + } else if (manifestRule.phase === 'response') { + rules.response!.push(rule); + } + }); + + return rules; + } +} + +export default RulesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts new file mode 100644 index 00000000..5965fcc0 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts @@ -0,0 +1,101 @@ +import type { AzionConfigV6 } from '../../types'; +import FunctionsProcessConfigStrategy from './functionsProcessConfigStrategy'; + +describe('FunctionsProcessConfigStrategy (v6)', () => { + let strategy: FunctionsProcessConfigStrategy; + + beforeEach(() => { + strategy = new FunctionsProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no functions', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, functions: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal function', () => { + const result = strategy.transformToManifest({ + version: 6, + functions: [{ name: 'my-function', path: './functions/index.js' }], + }); + + expect(result).toEqual([ + { + name: 'my-function', + runtime: 'azion_js', + default_args: {}, + execution_environment: 'application', + active: true, + path: './functions/index.js', + }, + ]); + }); + + it('should map every field of the function to the manifest', () => { + const result = strategy.transformToManifest({ + version: 6, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + active: false, + }, + ], + }); + + expect(result).toEqual([ + { + name: 'my-function', + runtime: 'azion_js', + default_args: { key: 'value' }, + execution_environment: 'firewall', + active: false, + path: './functions/index.js', + }, + ]); + }); + }); + + describe('transformToConfig', () => { + it('should not set functions when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.functions).toBeUndefined(); + }); + + it('should map the manifest functions back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + functions: [ + { + name: 'my-function', + runtime: 'azion_js', + default_args: { key: 'value' }, + execution_environment: 'firewall', + active: false, + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.functions).toEqual([ + { + name: 'my-function', + path: './functions/my-function.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + active: false, + }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts new file mode 100644 index 00000000..0e414471 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts @@ -0,0 +1,60 @@ +import type { FunctionExecutionEnvironment, FunctionRuntime } from '../../../../types'; +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * FunctionsProcessConfigStrategy V6 + * @class FunctionsProcessConfigStrategy + * @description This class is implementation of the Functions Process Config Strategy for API V6. + * TODO: validate and convert `bindings` (storage) once the v6 config has storage. + */ +class FunctionsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config Functions to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.functions) || config?.functions.length === 0) { + return []; + } + + return config.functions.map((func) => ({ + name: func.name, + runtime: func.runtime || 'azion_js', + default_args: func.defaultArgs || {}, + execution_environment: func.executionEnvironment || 'application', + active: func.active ?? true, + path: func.path, + })); + } + + /** + * Transform V6 manifest format back to azion.config Functions + */ + transformToConfig( + payload: { + functions?: Array<{ + name: string; + runtime?: string; + default_args?: Record; + execution_environment?: string; + active?: boolean; + }>; + }, + transformedPayload: AzionConfigV6, + ) { + if (!Array.isArray(payload?.functions) || payload?.functions.length === 0) { + return; + } + + transformedPayload.functions = payload.functions.map((func) => ({ + name: func.name, + path: `./functions/${func.name}.js`, // Default path since it's not in the API + runtime: func.runtime as FunctionRuntime, + defaultArgs: func.default_args, + executionEnvironment: func.execution_environment as FunctionExecutionEnvironment, + active: func.active, + })); + } +} + +export default FunctionsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index c8619f92..e96aa739 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -1,12 +1,16 @@ import ProcessConfigContext from '../../shared/processStrategy/processConfigContext'; import type { AzionConfigV6 } from '../types'; +import ApplicationProcessConfigStrategy from './implementations/application/applicationProcessConfigStrategy'; import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; +import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; function factoryProcessContext() { const processConfigContext = new ProcessConfigContext(); processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); + processConfigContext.setStrategy('functions', new FunctionsProcessConfigStrategy()); + processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); // TODO: register the other v6 strategies (setStrategy) as the v6 resources are defined return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts b/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts new file mode 100644 index 00000000..35de7141 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/applications/behaviors/index.ts @@ -0,0 +1,217 @@ +import { + COOKIE_BEHAVIORS, + HEADER_BEHAVIORS, + ID_BEHAVIORS, + NO_ARGS_BEHAVIORS, + STRING_BEHAVIORS, +} from '../../../constants'; + +const noArgsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: NO_ARGS_BEHAVIORS, + errorMessage: "The 'type' field must be a valid no-args behavior type.", + }, + }, + required: ['type'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in no-args behaviors.', + required: "The 'type' field is required in no-args behaviors.", + }, +}; + +const stringBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: STRING_BEHAVIORS, + errorMessage: "The 'type' field must be a valid string behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in string behavior attributes.', + required: "The 'value' field is required in string behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +// Schema para behaviors com ID value (run_function, set_cache_policy, etc.) +const idBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ID_BEHAVIORS, + errorMessage: "The 'type' field must be a valid ID behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + oneOf: [ + { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + }, + { + type: 'number', + minimum: 1, + }, + ], + errorMessage: "The 'value' field must be a string or positive number.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in ID behavior attributes.', + required: "The 'value' field is required in ID behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const headerBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: HEADER_BEHAVIORS, + errorMessage: "The 'type' field must be a valid header behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a non-empty string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in header behavior attributes.', + required: "The 'value' field is required in header behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const cookieBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: COOKIE_BEHAVIORS, + errorMessage: "The 'type' field must be a valid cookie behavior type.", + }, + attributes: { + type: 'object', + properties: { + value: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a non-empty string between 1 and 255 characters.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in cookie behavior attributes.', + required: "The 'value' field is required in cookie behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const captureGroupsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['capture_match_groups'], + errorMessage: "The 'type' field must be 'capture_match_groups'.", + }, + attributes: { + type: 'object', + properties: { + regex: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'regex' field must be a string between 1 and 255 characters.", + }, + subject: { + type: 'string', + minLength: 4, + maxLength: 50, + pattern: '.*', + errorMessage: "The 'subject' field must be a string between 4 and 50 characters.", + }, + captured_array: { + type: 'string', + minLength: 1, + maxLength: 10, + pattern: '.*', + errorMessage: "The 'captured_array' field must be a string between 1 and 10 characters.", + }, + }, + required: ['regex', 'subject', 'captured_array'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in capture groups behavior attributes.', + required: + "All fields ('regex', 'subject', 'captured_array') are required in capture groups behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const applicationRuleBehaviorSchema = { + oneOf: [ + noArgsBehaviorSchema, + stringBehaviorSchema, + idBehaviorSchema, + headerBehaviorSchema, + cookieBehaviorSchema, + captureGroupsBehaviorSchema, + ], + errorMessage: 'Each behavior must match one of the valid behavior formats.', +}; + +export default applicationRuleBehaviorSchema; diff --git a/packages/config/src/versions/v6/schemas/applications/index.ts b/packages/config/src/versions/v6/schemas/applications/index.ts new file mode 100644 index 00000000..6e211785 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/applications/index.ts @@ -0,0 +1,243 @@ +import { + ALL_REQUEST_VARIABLES, + ALL_RESPONSE_VARIABLES, + RULE_CONDITIONALS, + RULE_OPERATORS_WITH_VALUE, + RULE_OPERATORS_WITHOUT_VALUE, + SPECIAL_VARIABLES, +} from '../../constants'; +import applicationRuleBehaviorSchema from './behaviors'; + +const createVariableValidation = (isRequestPhase = false) => ({ + type: 'string', + anyOf: [ + { + type: 'string', + pattern: + '^\\$\\{(' + [...new Set(isRequestPhase ? ALL_REQUEST_VARIABLES : ALL_RESPONSE_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + pattern: isRequestPhase + ? '^\\$\\{(arg_|cookie_|http_)[a-zA-Z0-9_]+\\}$' + : '^\\$\\{(arg_|cookie_|http_|sent_http_|upstream_cookie_|upstream_http_)[a-zA-Z0-9_]+\\}$', + }, + { + // special variables with arguments + type: 'string', + pattern: `^\\$\\{(${SPECIAL_VARIABLES.join('|')})\\([^)]+\\)\\}$`, + }, + ], + errorMessage: isRequestPhase + ? "The 'variable' field must be a valid request phase variable wrapped in ${}, follow the patterns arg_*, cookie_*, http_*, or be a special function variable cookie_time_offset(), encode_base64()" + : "The 'variable' field must be a valid response phase variable wrapped in ${}, follow the patterns arg_*, cookie_*, http_*, sent_http_*, upstream_cookie_*, upstream_http_*, or be a special function variable cookie_time_offset(), encode_base64()", +}); + +const createCriteriaBaseSchema = (isRequestPhase = false) => ({ + type: 'object', + properties: { + variable: createVariableValidation(isRequestPhase).anyOf + ? { + type: 'string', + anyOf: createVariableValidation(isRequestPhase).anyOf, + errorMessage: createVariableValidation(isRequestPhase).errorMessage, + } + : createVariableValidation(isRequestPhase), + conditional: { + type: 'string', + enum: RULE_CONDITIONALS, + errorMessage: `The 'conditional' field must be one of: ${RULE_CONDITIONALS.join(', ')}`, + }, + operator: { + type: 'string', + enum: [...RULE_OPERATORS_WITH_VALUE, ...RULE_OPERATORS_WITHOUT_VALUE], + errorMessage: `The 'operator' field must be one of: ${[...RULE_OPERATORS_WITH_VALUE, ...RULE_OPERATORS_WITHOUT_VALUE].join(', ')}`, + }, + argument: { + type: 'string', + errorMessage: "The 'argument' field must be a string", + }, + }, + required: ['variable', 'conditional', 'operator'], + allOf: [ + { + if: { + properties: { + operator: { enum: RULE_OPERATORS_WITH_VALUE }, + }, + }, + then: { + required: ['argument'], + }, + }, + { + if: { + properties: { + operator: { enum: RULE_OPERATORS_WITHOUT_VALUE }, + }, + }, + then: { + not: { + required: ['argument'], + }, + }, + }, + ], + additionalProperties: false, +}); + +const createRuleSchema = (isRequestPhase = false) => ({ + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters.", + }, + description: { + type: 'string', + maxLength: 1000, + errorMessage: "The 'description' field must be a string with maximum 1000 characters.", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean.", + }, + criteria: { + type: 'array', + items: { + type: 'array', + items: createCriteriaBaseSchema(isRequestPhase), + minItems: 1, + maxItems: 10, + errorMessage: 'Each criteria group must have between 1 and 10 criteria items.', + }, + minItems: 1, + maxItems: 5, + errorMessage: 'The criteria must be an array of arrays with 1-5 groups.', + }, + behaviors: { + type: 'array', + items: applicationRuleBehaviorSchema, + minItems: 1, + maxItems: 10, + errorMessage: 'The behaviors must be an array with 1-10 items.', + }, + }, + required: ['name', 'criteria', 'behaviors'], + additionalProperties: false, +}); + +/** + * Schema of the v6 applications. + * Based on v4, checked against the requests of the v6 API: `name` has at most 100 characters in an application + * (`ApplicationRequest`) and in a rule (`RequestPhaseRuleRequest`, `ResponsePhaseRuleRequest`). + * TODO: add the remaining resources of an application (cache settings, device groups). + */ +const applicationsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: "The 'name' field must be a string with 1 to 100 characters", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + debug: { + type: 'boolean', + default: false, + errorMessage: "The 'debug' field must be a boolean", + }, + edgeCacheEnabled: { + type: 'boolean', + default: true, + errorMessage: "The 'edgeCacheEnabled' field must be a boolean", + }, + functionsEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'functionsEnabled' field must be a boolean", + }, + applicationAcceleratorEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'applicationAcceleratorEnabled' field must be a boolean", + }, + imageProcessorEnabled: { + type: 'boolean', + default: false, + errorMessage: "The 'imageProcessorEnabled' field must be a boolean", + }, + rules: { + type: 'object', + properties: { + request: { + type: 'array', + items: createRuleSchema(true), + }, + response: { + type: 'array', + items: createRuleSchema(false), + }, + }, + additionalProperties: false, + }, + functionsInstances: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters", + }, + ref: { + type: ['string', 'number'], + errorMessage: "The 'ref' field must be a string or number referencing an existing Function name or ID", + }, + args: { + type: 'object', + default: {}, + errorMessage: "The 'args' field must be an object", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + }, + required: ['name', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in function instance objects', + required: "The 'name' and 'ref' fields are required in each function instance", + }, + }, + errorMessage: "The 'functionsInstances' field must be an array of function instance objects", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in an application', + required: { name: "The 'name' field is required in an application" }, + }, + }, + errorMessage: "The 'applications' field must be an array of application items.", +}; + +export default applicationsSchema; diff --git a/packages/config/src/versions/v6/schemas/functions/index.ts b/packages/config/src/versions/v6/schemas/functions/index.ts new file mode 100644 index 00000000..9659f145 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/functions/index.ts @@ -0,0 +1,47 @@ +// TODO: add `bindings` (storage) once the v6 config has storage +const functionsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 250 characters", + }, + path: { + type: 'string', + errorMessage: "The 'path' field must be a string", + }, + runtime: { + type: 'string', + enum: ['azion_js'], + default: 'azion_js', + errorMessage: "The 'runtime' field must be 'azion_js'", + }, + defaultArgs: { + type: 'object', + default: {}, + errorMessage: "The 'defaultArgs' field must be an object", + }, + executionEnvironment: { + type: 'string', + enum: ['application', 'firewall'], + default: 'application', + errorMessage: "The 'executionEnvironment' field must be 'application' or 'firewall'", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + }, + required: ['name', 'path'], + additionalProperties: false, + }, + errorMessage: "The 'functions' field must be an array of function objects with at least one item", +}; + +export default functionsSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index 0d1b48ed..592f6bf9 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -1,8 +1,10 @@ +import applicationsSchema from './applications'; import buildSchema from './build'; +import functionsSchema from './functions'; /** * JSON Schema of the v6 config. - * TODO: only `version` and `build` are accepted until the schemas of the other v6 resources are defined. + * TODO: only `version`, `build`, `functions` and `applications` are accepted until the schemas of the other v6 resources are defined. */ const azionConfigSchema = { $id: 'azionConfig', @@ -12,10 +14,13 @@ const azionConfigSchema = { properties: { version: { type: 'number', enum: [6] }, build: buildSchema, + functions: functionsSchema, + applications: applicationsSchema, }, additionalProperties: false, errorMessage: { - additionalProperties: 'Config can only contain the following properties: version, build', + additionalProperties: + 'Config can only contain the following properties: version, build, functions, applications', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index dfc67dae..ff72b214 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -1,12 +1,47 @@ -import type { AzionBuild } from '../../types'; +import type { AzionBuild, AzionFunction, AzionFunctionInstance, AzionRules } from '../../types'; + +/** + * Function of the Azion API v6. + * TODO: add `bindings` (storage) once the v6 config has storage. + */ +export type AzionFunctionV6 = Omit; + +/** + * Application of the Azion API v6. + * TODO: add the remaining resources of an application (cache settings, device groups). + */ +export type AzionApplicationV6 = { + /** Application name */ + name: string; + /** Enable edge cache */ + edgeCacheEnabled?: boolean; + /** Enable functions */ + functionsEnabled?: boolean; + /** Enable application accelerator */ + applicationAcceleratorEnabled?: boolean; + /** Enable image processor */ + imageProcessorEnabled?: boolean; + /** Indicates if the application is active */ + active?: boolean; + /** Enable debug mode */ + debug?: boolean; + /** Rules configuration */ + rules?: AzionRules; + /** Function instances */ + functionsInstances?: AzionFunctionInstance[]; +}; /** * Config of the Azion API v6. - * TODO: structure placeholder. Replace with the v6 resources once the schemas are defined. + * TODO: structure placeholder. Add the remaining v6 resources once their schemas are defined. */ export type AzionConfigV6 = { /** Azion API version this config targets. */ version: 6; /** Build configuration (shared by every API version). */ build?: AzionBuild; + /** Functions */ + functions?: AzionFunctionV6[]; + /** Applications */ + applications?: AzionApplicationV6[]; }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 80bba21b..699d4c6b 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -48,9 +48,67 @@ describe('validateConfig (v6)', () => { }); }); + describe('applications', () => { + it('accepts a complete application', () => { + expect(() => + validateConfig({ + version: 6, + applications: [ + { + name: 'my-app', + active: true, + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: false, + imageProcessorEnabled: false, + }, + ], + }), + ).not.toThrow(); + }); + + it('requires the name', () => { + expect(() => validateConfig({ version: 6, applications: [{ active: true }] })).toThrow( + "The 'name' field is required in an application", + ); + }); + + it('accepts a name of 100 characters and rejects a longer one (v6 API limit)', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a'.repeat(100) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, applications: [{ name: 'a'.repeat(101) }] })).toThrow( + "The 'name' field must be a string with 1 to 100 characters", + ); + }); + + it('rejects an empty name', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: '' }] })).toThrow( + "The 'name' field must be a string with 1 to 100 characters", + ); + }); + + it('rejects a flag that is not a boolean', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', functionsEnabled: 'yes' }] })).toThrow( + "The 'functionsEnabled' field must be a boolean", + ); + }); + + it('rejects unknown properties in an application', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', unknown: true }] })).toThrow( + 'No additional properties are allowed in an application', + ); + }); + + it('rejects applications that are not an array', () => { + expect(() => validateConfig({ version: 6, applications: {} })).toThrow( + "The 'applications' field must be an array of application items.", + ); + }); + }); + it('rejects properties the v6 schema does not know yet', () => { - expect(() => validateConfig({ version: 6, applications: [] })).toThrow( - 'Config can only contain the following properties: version, build', + expect(() => validateConfig({ version: 6, workloads: [] })).toThrow( + 'Config can only contain the following properties: version, build, functions, applications', ); }); @@ -58,3 +116,149 @@ describe('validateConfig (v6)', () => { expect(() => validateConfig({ version: 4, build: {} })).toThrow(); }); }); + +describe('validateConfig (v6) functions', () => { + it('accepts a complete function', () => { + expect(() => + validateConfig({ + version: 6, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + runtime: 'azion_js', + defaultArgs: { key: 'value' }, + executionEnvironment: 'firewall', + active: false, + }, + ], + }), + ).not.toThrow(); + }); + + it('requires name and path', () => { + expect(() => validateConfig({ version: 6, functions: [{ path: './a.js' }] })).toThrow(); + expect(() => validateConfig({ version: 6, functions: [{ name: 'a' }] })).toThrow(); + }); + + it('rejects an unknown runtime and execution environment', () => { + expect(() => validateConfig({ version: 6, functions: [{ name: 'a', path: './a.js', runtime: 'node' }] })).toThrow( + "The 'runtime' field must be 'azion_js'", + ); + expect(() => + validateConfig({ version: 6, functions: [{ name: 'a', path: './a.js', executionEnvironment: 'edge' }] }), + ).toThrow("The 'executionEnvironment' field must be 'application' or 'firewall'"); + }); + + it('does not accept bindings yet (v6 has no storage)', () => { + expect(() => + validateConfig({ + version: 6, + functions: [{ name: 'a', path: './a.js', bindings: { storage: { bucket: 'b', prefix: 'p' } } }], + }), + ).toThrow(); + }); +}); + +describe('validateConfig (v6) application functionsInstances and rules', () => { + const app = (extra: Record) => ({ version: 6, applications: [{ name: 'my-app', ...extra }] }); + const requestRule = (extra: Record = {}) => ({ + name: 'rule', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'deliver' }], + ...extra, + }); + + describe('functionsInstances', () => { + it('accepts an instance and requires name and ref', () => { + expect(() => + validateConfig(app({ functionsInstances: [{ name: 'i', ref: 'fn', args: { a: 1 }, active: true }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'i', ref: 10 }] }))).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'i' }] }))).toThrow( + "The 'name' and 'ref' fields are required in each function instance", + ); + }); + + it('limits the name to 100 characters', () => { + expect(() => validateConfig(app({ functionsInstances: [{ name: 'a'.repeat(100), ref: 'fn' }] }))).not.toThrow(); + expect(() => validateConfig(app({ functionsInstances: [{ name: 'a'.repeat(101), ref: 'fn' }] }))).toThrow( + "The 'name' field must be a string between 1 and 100 characters", + ); + }); + }); + + describe('rules', () => { + it('accepts request and response rules', () => { + expect(() => + validateConfig( + app({ + rules: { + request: [requestRule({ description: 'd', active: true })], + response: [requestRule({ behaviors: [{ type: 'add_response_header', attributes: { value: 'x: y' } }] })], + }, + }), + ), + ).not.toThrow(); + }); + + it('limits the rule name to 100 characters (v6 API limit, 250 in v4)', () => { + const rules = (name: string) => ({ rules: { request: [requestRule({ name })] } }); + expect(() => validateConfig(app(rules('a'.repeat(100))))).not.toThrow(); + expect(() => validateConfig(app(rules('a'.repeat(101))))).toThrow( + "The 'name' field must be a string between 1 and 100 characters.", + ); + }); + + it('validates the variables of each phase as the v6 API documents them', () => { + const criteria = (variable: string) => [[{ variable, conditional: 'if', operator: 'exists' }]]; + const request = (variable: string) => + app({ rules: { request: [requestRule({ criteria: criteria(variable) })] } }); + const response = (variable: string) => + app({ rules: { response: [requestRule({ criteria: criteria(variable) })] } }); + + // available in both phases in v6 (a single phase in v4) + expect(() => validateConfig(request('${tcpinfo_rtt}'))).not.toThrow(); + expect(() => validateConfig(response('${server_addr}'))).not.toThrow(); + expect(() => validateConfig(response('${ssl_client_verify}'))).not.toThrow(); + // response only + expect(() => validateConfig(response('${status}'))).not.toThrow(); + expect(() => validateConfig(request('${status}'))).toThrow(); + expect(() => validateConfig(request('${sent_http_x_header}'))).toThrow(); + expect(() => validateConfig(response('${sent_http_x_header}'))).not.toThrow(); + // v4 only + expect(() => validateConfig(response('${sent_http_name}'))).not.toThrow(); // matches sent_http_ + }); + + it('requires the argument only for the operators with value', () => { + const rule = (criterion: Record) => + app({ rules: { request: [requestRule({ criteria: [[criterion]] })] } }); + expect(() => validateConfig(rule({ variable: '${uri}', conditional: 'if', operator: 'matches' }))).toThrow(); + expect(() => + validateConfig(rule({ variable: '${uri}', conditional: 'if', operator: 'exists', argument: 'x' })), + ).toThrow(); + }); + + it('does not accept the firewall operators in an application rule', () => { + expect(() => + validateConfig( + app({ + rules: { + request: [ + requestRule({ + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'is_in_list', argument: '1' }]], + }), + ], + }, + }), + ), + ).toThrow(); + }); + + it('rejects a behavior that is not valid', () => { + expect(() => + validateConfig(app({ rules: { request: [requestRule({ behaviors: [{ type: 'unknown' }] })] } })), + ).toThrow(); + }); + }); +}); From 232298ea06682b18c377b41b279891cf5599c41e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 17:05:05 -0300 Subject: [PATCH 06/29] feat(presets): add the application, functions and rules to the javascript v6 config Add the function, the application with its rule and function instance, as the v4 config has. A test checks that the functions and the application of the v6 manifest are the same as the ones of the v4 manifest. --- packages/presets/src/presets/configs.test.ts | 13 +++++- .../src/presets/javascript/config.v6.ts | 46 ++++++++++++++++++- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 10c0dcec..9552b56f 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -52,7 +52,18 @@ describe('preset configs by API version', () => { expect(config.version).toBe(6); expect(() => validateConfig(config)).not.toThrow(); expect(config.build).toEqual(resolvePresetConfig(byName('javascript'), 4).build); - expect(processConfig(config)).toEqual({ version: 6, build: { entry: 'index.js' } }); + const manifest = processConfig(config); + expect(manifest.version).toBe(6); + expect(manifest.build).toEqual({ entry: 'index.js' }); + }); + + it('javascript: has the same functions and application in the manifest as the v4 config', () => { + const v4 = processConfig(resolvePresetConfig(byName('javascript'), 4)); + const v6 = processConfig(resolvePresetConfig(byName('javascript'), 6)); + + expect(v6.functions).toEqual(v4.functions); + expect(v6.applications).toEqual(v4.applications); + expect(v6.applications[0].modules.functions.enabled).toBe(true); }); }); diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts index 24871713..9541c225 100644 --- a/packages/presets/src/presets/javascript/config.v6.ts +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -1,11 +1,55 @@ import type { AzionConfigV6 } from '@aziontech/config'; -// TODO: add the remaining v6 resources (functions, applications, workloads...) once their schemas are defined +// TODO: add the remaining v6 resources (workloads, connectors, storage...) once their schemas are defined const config: AzionConfigV6 = { version: 6, build: { entry: 'index.js', }, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', // path to the edge function. This path is relative to the .edge folder. + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], }; export default config; From c56c7670f26b84d38007b11c76f05a9dd50ccac1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 17:41:27 -0300 Subject: [PATCH 07/29] feat(config): add workloads, environments, deployments, storage and connectors to API v6 Add the v6 schemas, types and process strategies, based on v4 and checked against the v6 API requests. Workloads: the domains and the certificate moved to the bindings (environment, deployment and domains), tls.ciphers is not nullable and the http protocol has item limits. Environments and deployments are config resources of their own; a binding references them by name and the manifest keeps the name in environment_id and deployment_id for the Azion CLI to resolve. The v4 deployments of a workload are not ported: the application a deployment serves is set by the release the CLI creates. Storage: the name follows the pattern of the API (a $PLACEHOLDER is also accepted, as the presets use them) and the prefix is optional. Connectors: the attributes must match the type, the prefix of a storage connector is optional, an HTTP connector only requires the addresses, an address can have load balancer modules, force_ipv6 is a DNS resolution, live ingest has a region and the module configs are not nullable. The rules validate the connector of set_connector again. The v6 accessor getStorage reads the first storage, as v4 does. --- .../config/src/versions/accessors.test.ts | 22 + packages/config/src/versions/registry.test.ts | 5 +- packages/config/src/versions/v6/constants.ts | 38 ++ packages/config/src/versions/v6/index.ts | 8 +- .../applicationProcessConfigStrategy.ts | 2 +- .../rulesProcessConfigStrategy.test.ts | 46 ++ .../application/rulesProcessConfigStrategy.ts | 34 +- .../connectorProcessConfigStrategy.test.ts | 229 ++++++++++ .../connectorProcessConfigStrategy.ts | 225 ++++++++++ .../deploymentProcessConfigStrategy.test.ts | 79 ++++ .../deploymentProcessConfigStrategy.ts | 67 +++ .../environmentProcessConfigStrategy.test.ts | 102 +++++ .../environmentProcessConfigStrategy.ts | 98 +++++ .../storageProcessConfigStrategy.test.ts | 54 +++ .../storageProcessConfigStrategy.ts | 41 ++ .../workloadProcessConfigStrategy.test.ts | 170 ++++++++ .../workloadProcessConfigStrategy.ts | 123 ++++++ .../src/versions/v6/processStrategy/index.ts | 10 + .../versions/v6/schemas/connectors/index.ts | 390 +++++++++++++++++ .../versions/v6/schemas/deployments/index.ts | 64 +++ .../versions/v6/schemas/environments/index.ts | 113 +++++ .../config/src/versions/v6/schemas/schema.ts | 14 +- .../src/versions/v6/schemas/storage/index.ts | 45 ++ .../versions/v6/schemas/workloads/index.ts | 204 +++++++++ packages/config/src/versions/v6/types.ts | 215 ++++++++- .../versions/v6/validateConfig/index.test.ts | 409 +++++++++++++++++- 26 files changed, 2795 insertions(+), 12 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/connectors/index.ts create mode 100644 packages/config/src/versions/v6/schemas/deployments/index.ts create mode 100644 packages/config/src/versions/v6/schemas/environments/index.ts create mode 100644 packages/config/src/versions/v6/schemas/storage/index.ts create mode 100644 packages/config/src/versions/v6/schemas/workloads/index.ts diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index 27b13b8f..f7420440 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -31,6 +31,28 @@ describe('version accessors', () => { prefix: '', }); expect(getStorage(v3)).toEqual({ bucket: 'bucket-3', prefix: 'p3' }); + expect(getStorage({ version: 6, storage: [{ name: 'bucket-6', prefix: 'p6', dir: './dist' }] })).toEqual({ + bucket: 'bucket-6', + prefix: 'p6', + }); + }); + + it('reads the first v6 storage and falls back to an empty prefix, as the prefix is optional in v6', () => { + expect(getStorage({ version: 6, storage: [{ name: 'bucket-6', dir: './dist' }] })).toEqual({ + bucket: 'bucket-6', + prefix: '', + }); + expect( + getStorage({ + version: 6, + storage: [ + { name: 'first-bucket', dir: './a' }, + { name: 'second-bucket', dir: './b' }, + ], + }), + ).toEqual({ bucket: 'first-bucket', prefix: '' }); + expect(getStorage({ version: 6 })).toBeUndefined(); + expect(getStorage({ version: 6, storage: [] })).toBeUndefined(); }); it('returns undefined when the config has no storage', () => { diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index a186367f..fd3bf7d7 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -139,7 +139,7 @@ describe('v6 support', () => { it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { expect(() => validateConfig(v6Config)).not.toThrow(); - expect(() => validateConfig({ version: 6, workloads: [] })).toThrow(); + expect(() => validateConfig({ version: 6, firewall: [] })).toThrow(); }); it('does not accept v6 on the v4 schema nor the other way around', () => { @@ -153,6 +153,9 @@ describe('v6 support', () => { build: v6Config.build, functions: [], applications: [], + environments: [], + deployments: [], + workloads: [], }); }); diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts index 99e9a608..b8e28477 100644 --- a/packages/config/src/versions/v6/constants.ts +++ b/packages/config/src/versions/v6/constants.ts @@ -91,3 +91,41 @@ export const COOKIE_BEHAVIORS = [ 'set_cookie', 'filter_response_cookie', ] as const; + +export const WORKLOAD_INFRASTRUCTURE = [1, 2] as const; + +export const WORKLOAD_TLS_CIPHERS = [1, 2, 3, 4, 5, 6, 7, 8] as const; + +export const WORKLOAD_TLS_VERSIONS = ['', 'tls_1_0', 'tls_1_1', 'tls_1_2', 'tls_1_3'] as const; + +export const WORKLOAD_MTLS_VERIFICATION = ['enforce', 'permissive'] as const; + +export const WORKLOAD_HTTP_VERSIONS = ['http1', 'http2', 'http3'] as const; + +export const ENVIRONMENT_LOG_VERBOSITY = ['normal', 'verbose'] as const; + +export const ENVIRONMENT_ROBOTS_POLICIES = ['index', 'noindex', 'respect_origin'] as const; + +export const ENVIRONMENT_BRANCH_TRACKING_MODES = ['branch_is', 'branch_starts_with', 'branch_ends_with'] as const; + +export const DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls'] as const; + +export const DEPLOYMENT_BINDING_POLICIES = ['STRICT', 'FLEXIBLE'] as const; + +export const WORKLOADS_ACCESS_TYPES = ['read_only', 'read_write', 'restricted'] as const; + +export const CONNECTOR_TYPES = ['http', 'storage', 'live_ingest'] as const; + +export const CONNECTOR_DNS_RESOLUTION = ['both', 'force_ipv4', 'force_ipv6'] as const; + +export const CONNECTOR_TRANSPORT_POLICY = ['preserve', 'force_https', 'force_http'] as const; + +export const CONNECTOR_HTTP_VERSION_POLICY = ['http1_1'] as const; + +export const CONNECTOR_LOAD_BALANCE_METHOD = ['round_robin', 'least_conn', 'ip_hash'] as const; + +export const CONNECTOR_SERVER_ROLES = ['primary', 'backup'] as const; + +export const CONNECTOR_HMAC_TYPE = ['aws4_hmac_sha256'] as const; + +export const CONNECTOR_LIVE_INGEST_REGIONS = ['us-east-1', 'us-east-2', 'br-east-1', 'br-east-2', 'br-east-3'] as const; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts index 3046366a..8a896568 100644 --- a/packages/config/src/versions/v6/index.ts +++ b/packages/config/src/versions/v6/index.ts @@ -7,8 +7,12 @@ import { validateManifest } from './validateManifest'; const accessors: ConfigVersionAccessors = { getApplicationName: (config) => (config as AzionConfigV6).applications?.[0]?.name, - // TODO: define where v6 keeps the storage and the firewall keys - getStorage: () => undefined, + getStorage: (config) => { + // TODO: multiple storage support + const storage = (config as AzionConfigV6).storage?.[0]; + return storage ? { bucket: storage.name, prefix: storage.prefix ?? '' } : undefined; + }, + // TODO: define the keys a firewall-only project must not inherit once the v6 config has firewall firewallReplacedKeys: [], }; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts index d236f100..25295599 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -42,7 +42,7 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { expect(() => strategy.transformToManifest(byId, [])).not.toThrow(); }); + describe('connector references', () => { + const connectorRules: AzionRules = { + request: [ + { + name: 'Deliver static assets', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '\\.js$' }]], + behaviors: [{ type: 'set_connector', attributes: { value: 'my-connector' } }], + }, + ], + }; + + it('should accept a set_connector that references a declared connector', () => { + expect(() => + strategy.transformToManifest(connectorRules, undefined, [ + { name: 'my-connector', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]), + ).not.toThrow(); + }); + + it('should throw when set_connector references a connector that is not declared', () => { + expect(() => + strategy.transformToManifest(connectorRules, undefined, [ + { name: 'other', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]), + ).toThrow( + 'Connector "my-connector" referenced in rule "Deliver static assets" is not defined in the connectors array.', + ); + }); + + it('should validate response rules too', () => { + expect(() => strategy.transformToManifest({ response: connectorRules.request }, undefined, [])).toThrow( + 'Connector "my-connector" referenced in rule', + ); + }); + + it('should not validate a connector referenced by id, nor when the config has no connectors', () => { + const byId: AzionRules = { + request: [ + { ...connectorRules.request![0], behaviors: [{ type: 'set_connector', attributes: { value: 10 } }] }, + ], + }; + expect(() => strategy.transformToManifest(byId, undefined, [])).not.toThrow(); + expect(() => strategy.transformToManifest(connectorRules)).not.toThrow(); + }); + }); + it('should not validate the function references when the config has no functions', () => { expect(() => strategy.transformToManifest(rules)).not.toThrow(); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts index 18ad31e0..c4423f4e 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts @@ -7,13 +7,12 @@ import type { RuleVariable, } from '../../../../../types'; import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; -import type { AzionConfigV6, AzionFunctionV6 } from '../../../types'; +import type { AzionConfigV6, AzionConnectorV6, AzionFunctionV6 } from '../../../types'; /** * RulesProcessConfigStrategy * @class RulesProcessConfigStrategy * @description This class is implementation of the Rules ProcessConfig Strategy for V6. - * TODO: validate the connectors referenced by `set_connector` once the v6 config has connectors. */ class RulesProcessConfigStrategy extends ProcessConfigStrategy { /** @@ -57,13 +56,42 @@ class RulesProcessConfigStrategy extends ProcessConfigStrategy { } } + /** + * Validates connector references in rules + */ + private validateConnectorReferences(applicationRules: AzionRules, connectors?: AzionConnectorV6[]) { + if (!connectors) return; + + const definedConnectors = new Set(connectors.map((c) => c.name)); + + for (const rule of [...(applicationRules.request ?? []), ...(applicationRules.response ?? [])]) { + for (const behavior of rule.behaviors) { + if (behavior.type === 'set_connector' && behavior.attributes) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof behavior.attributes.value === 'string' && !definedConnectors.has(behavior.attributes.value)) { + throw new Error( + `Connector "${behavior.attributes.value}" referenced in rule "${rule.name}" is not defined in the connectors array.`, + ); + } + } + } + } + } + /** * Transforms azion.config rules to API manifest format */ - transformToManifest(applicationRules: AzionRules, functions?: AzionFunctionV6[]): AzionManifestRule[] { + transformToManifest( + applicationRules: AzionRules, + functions?: AzionFunctionV6[], + connectors?: AzionConnectorV6[], + ): AzionManifestRule[] { // Validate function references this.validateFunctionReferences(applicationRules, functions); + // Validate connector references + this.validateConnectorReferences(applicationRules, connectors); + const payload: AzionManifestRule[] = []; if (!applicationRules || Object.keys(applicationRules).length === 0) { diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts new file mode 100644 index 00000000..b9175055 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts @@ -0,0 +1,229 @@ +import type { AzionConfigV6, AzionConnectorV6 } from '../../types'; +import ConnectorProcessConfigStrategy from './connectorProcessConfigStrategy'; + +describe('ConnectorProcessConfigStrategy (v6)', () => { + let strategy: ConnectorProcessConfigStrategy; + + const toManifest = (connectors: AzionConnectorV6[]) => + strategy.transformToManifest({ version: 6, connectors }) as Record[]; + + beforeEach(() => { + strategy = new ConnectorProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there are no connectors', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(toManifest([])).toBeUndefined(); + }); + + it('should map a storage connector, leaving the prefix out when it is not set', () => { + expect( + toManifest([ + { name: 'with-prefix', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'no-prefix', type: 'storage', active: false, attributes: { bucket: 'my-bucket' } }, + ]), + ).toEqual([ + { name: 'with-prefix', active: true, type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'no-prefix', active: false, type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]); + }); + + it('should map a live ingest connector', () => { + expect(toManifest([{ name: 'ingest', type: 'live_ingest', attributes: { region: 'br-east-1' } }])).toEqual([ + { name: 'ingest', active: true, type: 'live_ingest', attributes: { region: 'br-east-1' } }, + ]); + }); + + it('should apply the defaults to an http connector with only the addresses and no null module configs', () => { + const [connector] = toManifest([ + { name: 'origin', type: 'http', attributes: { addresses: [{ address: 'origin.example.com' }] } }, + ]); + + expect(connector).toEqual({ + name: 'origin', + active: true, + type: 'http', + attributes: { + addresses: [{ active: true, address: 'origin.example.com', http_port: 80, https_port: 443 }], + connection_options: { + dns_resolution: 'both', + transport_policy: 'preserve', + http_version_policy: 'http1_1', + host: '${host}', + path_prefix: '', + following_redirect: false, + real_ip_header: 'X-Real-IP', + real_port_header: 'X-Real-PORT', + }, + modules: { + load_balancer: { enabled: false }, + origin_shield: { enabled: false }, + }, + }, + }); + }); + + it('should map every field of an http connector to the manifest', () => { + const [connector] = toManifest([ + { + name: 'origin', + type: 'http', + active: false, + attributes: { + addresses: [ + { + active: false, + address: 'origin.example.com', + httpPort: 8080, + httpsPort: 8443, + modules: { loadBalancer: { serverRole: 'backup', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'force_ipv6', + transportPolicy: 'force_https', + httpVersionPolicy: 'http1_1', + host: 'example.com', + pathPrefix: '/api', + followingRedirect: true, + realIpHeader: 'X-Client-IP', + realPortHeader: 'X-Client-Port', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'ip_hash', maxRetries: 2, connectionTimeout: 10, readWriteTimeout: 20 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }, + }, + ]); + + expect(connector).toEqual({ + name: 'origin', + active: false, + type: 'http', + attributes: { + addresses: [ + { + active: false, + address: 'origin.example.com', + http_port: 8080, + https_port: 8443, + modules: { load_balancer: { server_role: 'backup', weight: 10 } }, + }, + ], + connection_options: { + dns_resolution: 'force_ipv6', + transport_policy: 'force_https', + http_version_policy: 'http1_1', + host: 'example.com', + path_prefix: '/api', + following_redirect: true, + real_ip_header: 'X-Client-IP', + real_port_header: 'X-Client-Port', + }, + modules: { + load_balancer: { + enabled: true, + config: { method: 'ip_hash', max_retries: 2, connection_timeout: 10, read_write_timeout: 20 }, + }, + origin_shield: { + enabled: true, + config: { + origin_ip_acl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', access_key: 'key', secret_key: 'secret' }, + }, + }, + }, + }, + }, + }, + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set connectors when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.connectors).toBeUndefined(); + }); + + it('should round trip storage, live ingest and http connectors through the manifest', () => { + const connectors: AzionConnectorV6[] = [ + { name: 'files', type: 'storage', active: true, attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'ingest', type: 'live_ingest', active: true, attributes: { region: 'us-east-2' } }, + { + name: 'origin', + type: 'http', + active: true, + attributes: { + addresses: [ + { + active: true, + address: 'origin.example.com', + httpPort: 80, + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 5 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'preserve', + httpVersionPolicy: 'http1_1', + host: '${host}', + pathPrefix: '', + followingRedirect: false, + realIpHeader: 'X-Real-IP', + realPortHeader: 'X-Real-PORT', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 0, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: false }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }, + }, + ]; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ connectors: toManifest(connectors) }, transformedPayload); + + expect(transformedPayload.connectors).toEqual(connectors); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts new file mode 100644 index 00000000..60a083a9 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts @@ -0,0 +1,225 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionConnectorV6 } from '../../types'; + +/** + * ConnectorProcessConfigStrategy V6 + * @class ConnectorProcessConfigStrategy + * @description Converts the v6 connectors (http, storage and live ingest) between the config and the manifest. + * The v6 API does not accept null in the module configs, so they are left out of the manifest when the config has none. + */ +class ConnectorProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config connectors to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const connectors = config?.connectors; + if (!connectors || connectors.length === 0) { + return; + } + + return connectors.map((connector: AzionConnectorV6) => { + const baseConnector = { + name: connector.name, + active: connector.active ?? true, + type: connector.type, + }; + + if (connector.type === 'storage') { + return { + ...baseConnector, + attributes: { + bucket: connector.attributes.bucket, + ...(connector.attributes.prefix !== undefined && { prefix: connector.attributes.prefix }), + }, + }; + } + + if (connector.type === 'live_ingest') { + return { + ...baseConnector, + attributes: { + region: connector.attributes.region, + }, + }; + } + + const { addresses, connectionOptions, modules } = connector.attributes; + const loadBalancer = modules?.loadBalancer; + const originShield = modules?.originShield; + const hmac = originShield?.config?.hmac; + + return { + ...baseConnector, + attributes: { + addresses: addresses.map((addr) => ({ + active: addr.active ?? true, + address: addr.address, + http_port: addr.httpPort ?? 80, + https_port: addr.httpsPort ?? 443, + ...(addr.modules?.loadBalancer && { + modules: { + load_balancer: { + ...(addr.modules.loadBalancer.serverRole && { server_role: addr.modules.loadBalancer.serverRole }), + ...(addr.modules.loadBalancer.weight !== undefined && { weight: addr.modules.loadBalancer.weight }), + }, + }, + }), + })), + connection_options: { + dns_resolution: connectionOptions?.dnsResolution ?? 'both', + transport_policy: connectionOptions?.transportPolicy ?? 'preserve', + http_version_policy: connectionOptions?.httpVersionPolicy ?? 'http1_1', + host: connectionOptions?.host ?? '${host}', + path_prefix: connectionOptions?.pathPrefix ?? '', + following_redirect: connectionOptions?.followingRedirect ?? false, + real_ip_header: connectionOptions?.realIpHeader ?? 'X-Real-IP', + real_port_header: connectionOptions?.realPortHeader ?? 'X-Real-PORT', + }, + modules: { + load_balancer: { + enabled: loadBalancer?.enabled ?? false, + ...(loadBalancer?.config && { + config: { + method: loadBalancer.config.method ?? 'round_robin', + max_retries: loadBalancer.config.maxRetries ?? 0, + connection_timeout: loadBalancer.config.connectionTimeout ?? 60, + read_write_timeout: loadBalancer.config.readWriteTimeout ?? 120, + }, + }), + }, + origin_shield: { + enabled: originShield?.enabled ?? false, + ...(originShield?.config && { + config: { + origin_ip_acl: { + enabled: originShield.config.originIpAcl?.enabled ?? false, + }, + ...(hmac && { + hmac: { + enabled: hmac.enabled ?? false, + ...(hmac.config && { + config: { + type: hmac.config.type, + attributes: { + region: hmac.config.attributes.region, + service: hmac.config.attributes.service ?? 's3', + access_key: hmac.config.attributes.accessKey, + secret_key: hmac.config.attributes.secretKey, + }, + }, + }), + }, + }), + }, + }), + }, + }, + }, + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config connectors + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { connectors?: any[] }, transformedPayload: AzionConfigV6) { + if (!payload.connectors || payload.connectors.length === 0) { + return; + } + + transformedPayload.connectors = payload.connectors.map((connector) => { + const baseConnector = { + name: connector.name, + active: connector.active, + type: connector.type, + }; + + if (connector.type === 'storage') { + return { + ...baseConnector, + attributes: { + bucket: connector.attributes.bucket, + prefix: connector.attributes.prefix, + }, + } as AzionConnectorV6; + } + + if (connector.type === 'live_ingest') { + return { + ...baseConnector, + attributes: { region: connector.attributes.region }, + } as AzionConnectorV6; + } + + const { addresses, connection_options: options, modules } = connector.attributes; + const loadBalancer = modules?.load_balancer; + const originShield = modules?.origin_shield; + const hmac = originShield?.config?.hmac; + + return { + ...baseConnector, + attributes: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + addresses: addresses.map((addr: any) => ({ + active: addr.active, + address: addr.address, + httpPort: addr.http_port, + httpsPort: addr.https_port, + modules: addr.modules?.load_balancer && { + loadBalancer: { + serverRole: addr.modules.load_balancer.server_role, + weight: addr.modules.load_balancer.weight, + }, + }, + })), + connectionOptions: options && { + dnsResolution: options.dns_resolution, + transportPolicy: options.transport_policy, + httpVersionPolicy: options.http_version_policy, + host: options.host, + pathPrefix: options.path_prefix, + followingRedirect: options.following_redirect, + realIpHeader: options.real_ip_header, + realPortHeader: options.real_port_header, + }, + modules: modules && { + loadBalancer: loadBalancer && { + enabled: loadBalancer.enabled, + config: loadBalancer.config && { + method: loadBalancer.config.method, + maxRetries: loadBalancer.config.max_retries, + connectionTimeout: loadBalancer.config.connection_timeout, + readWriteTimeout: loadBalancer.config.read_write_timeout, + }, + }, + originShield: originShield && { + enabled: originShield.enabled, + config: originShield.config && { + originIpAcl: originShield.config.origin_ip_acl && { + enabled: originShield.config.origin_ip_acl.enabled, + }, + hmac: hmac && { + enabled: hmac.enabled, + config: hmac.config && { + type: hmac.config.type, + attributes: { + region: hmac.config.attributes.region, + service: hmac.config.attributes.service, + accessKey: hmac.config.attributes.access_key, + secretKey: hmac.config.attributes.secret_key, + }, + }, + }, + }, + }, + }, + }, + } as AzionConnectorV6; + }); + + return transformedPayload.connectors; + } +} + +export default ConnectorProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts new file mode 100644 index 00000000..d024eae7 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts @@ -0,0 +1,79 @@ +import type { AzionConfigV6 } from '../../types'; +import DeploymentProcessConfigStrategy from './deploymentProcessConfigStrategy'; + +describe('DeploymentProcessConfigStrategy (v6)', () => { + let strategy: DeploymentProcessConfigStrategy; + + beforeEach(() => { + strategy = new DeploymentProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no deployments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults the API requires to a minimal deployment', () => { + expect(strategy.transformToManifest({ version: 6, deployments: [{ name: 'default-deployment' }] })).toEqual([ + { + name: 'default-deployment', + description: null, + binding_policy: 'FLEXIBLE', + strategy_defaults: {}, + }, + ]); + }); + + it('should map every field of the deployment to the manifest', () => { + const [deployment] = strategy.transformToManifest({ + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }); + + expect(deployment).toEqual({ + name: 'default-deployment', + description: 'Default', + binding_policy: 'STRICT', + strategy_defaults: { skew_protection: { enabled: true, default_ttl_seconds: 3600 } }, + deployment_policy: 'single_version', + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set deployments when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.deployments).toBeUndefined(); + }); + + it('should round trip a deployment through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ deployments: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.deployments).toEqual(config.deployments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts new file mode 100644 index 00000000..1f467e5f --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts @@ -0,0 +1,67 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionDeploymentV6 } from '../../types'; + +/** + * DeploymentProcessConfigStrategy + * @class DeploymentProcessConfigStrategy + * @description Converts the v6 deployments between the config and the manifest. + * The API requires `binding_policy`, `description` and `strategy_defaults`, so the manifest defaults them to a flexible + * binding, no description and no skew protection. + * The application a deployment serves is not part of it: the Azion CLI sets it when it creates a release. + */ +class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.deployments) || config.deployments.length === 0) { + return []; + } + + return config.deployments.map((deployment: AzionDeploymentV6) => { + const skewProtection = deployment.strategyDefaults?.skewProtection; + + return { + name: deployment.name, + description: deployment.description ?? null, + binding_policy: deployment.bindingPolicy ?? 'FLEXIBLE', + strategy_defaults: skewProtection + ? { + skew_protection: { + enabled: skewProtection.enabled, + default_ttl_seconds: skewProtection.defaultTtlSeconds, + }, + } + : {}, + ...(deployment.deploymentPolicy && { deployment_policy: deployment.deploymentPolicy }), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { deployments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.deployments) || payload.deployments.length === 0) { + return; + } + + transformedPayload.deployments = payload.deployments.map((deployment) => { + const skewProtection = deployment.strategy_defaults?.skew_protection; + + return { + name: deployment.name, + description: deployment.description, + bindingPolicy: deployment.binding_policy, + deploymentPolicy: deployment.deployment_policy, + strategyDefaults: skewProtection + ? { + skewProtection: { + enabled: skewProtection.enabled, + defaultTtlSeconds: skewProtection.default_ttl_seconds, + }, + } + : undefined, + }; + }); + + return transformedPayload.deployments; + } +} + +export default DeploymentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts new file mode 100644 index 00000000..8e64e1ac --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.test.ts @@ -0,0 +1,102 @@ +import type { AzionConfigV6 } from '../../types'; +import EnvironmentProcessConfigStrategy from './environmentProcessConfigStrategy'; + +describe('EnvironmentProcessConfigStrategy (v6)', () => { + let strategy: EnvironmentProcessConfigStrategy; + + beforeEach(() => { + strategy = new EnvironmentProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no environments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults the API requires to a minimal environment', () => { + expect(strategy.transformToManifest({ version: 6, environments: [{ name: 'production' }] })).toEqual([ + { + name: 'production', + description: null, + log_verbosity: 'normal', + robots_policy: 'respect_origin', + protection: {}, + branch_tracking: null, + }, + ]); + }); + + it('should map every field of the environment to the manifest', () => { + const [environment] = strategy.transformToManifest({ + version: 6, + environments: [ + { + name: 'staging', + description: 'Staging', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: true, idpId: 'idp', allowedDomains: ['azion.com'] }, + }, + branchTracking: { enabled: true, mode: 'branch_is', branchMatch: 'main' }, + deploymentPolicy: 'versioned_urls', + }, + ], + }); + + expect(environment).toEqual({ + name: 'staging', + description: 'Staging', + log_verbosity: 'verbose', + robots_policy: 'noindex', + protection: { + azion_authentication: { enabled: true }, + password_protection: { enabled: true, secret_id: 'secret' }, + ip_allowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + sso_enforcement: { enabled: true, idp_id: 'idp', allowed_domains: ['azion.com'] }, + }, + branch_tracking: { enabled: true, mode: 'branch_is', branch_match: 'main' }, + deployment_policy: 'versioned_urls', + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set environments when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.environments).toBeUndefined(); + }); + + it('should round trip an environment through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + environments: [ + { + name: 'staging', + description: 'Staging', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: true, idpId: 'idp', allowedDomains: ['azion.com'] }, + }, + branchTracking: { enabled: true, mode: 'branch_is', branchMatch: 'main' }, + deploymentPolicy: 'versioned_urls', + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ environments: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.environments).toEqual(config.environments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts new file mode 100644 index 00000000..c5995351 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts @@ -0,0 +1,98 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionEnvironmentV6 } from '../../types'; + +/** + * EnvironmentProcessConfigStrategy + * @class EnvironmentProcessConfigStrategy + * @description Converts the v6 environments between the config and the manifest. + * The API requires `log_verbosity`, `robots_policy`, `protection`, `branch_tracking` and `description`, so the manifest + * defaults them to the least intrusive values: normal logs, the robots policy of the origin, no protection, no branch + * tracking and no description. + */ +class EnvironmentProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.environments) || config.environments.length === 0) { + return []; + } + + return config.environments.map((environment: AzionEnvironmentV6) => { + const { protection, branchTracking } = environment; + + return { + name: environment.name, + description: environment.description ?? null, + log_verbosity: environment.logVerbosity ?? 'normal', + robots_policy: environment.robotsPolicy ?? 'respect_origin', + protection: { + ...(protection?.azionAuthentication && { azion_authentication: protection.azionAuthentication }), + ...(protection?.passwordProtection && { + password_protection: { + enabled: protection.passwordProtection.enabled, + secret_id: protection.passwordProtection.secretId, + }, + }), + ...(protection?.ipAllowlist && { ip_allowlist: protection.ipAllowlist }), + ...(protection?.ssoEnforcement && { + sso_enforcement: { + enabled: protection.ssoEnforcement.enabled, + idp_id: protection.ssoEnforcement.idpId, + allowed_domains: protection.ssoEnforcement.allowedDomains, + }, + }), + }, + branch_tracking: branchTracking + ? { + enabled: branchTracking.enabled, + mode: branchTracking.mode, + branch_match: branchTracking.branchMatch, + } + : null, + ...(environment.deploymentPolicy && { deployment_policy: environment.deploymentPolicy }), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { environments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.environments) || payload.environments.length === 0) { + return; + } + + transformedPayload.environments = payload.environments.map((environment) => { + const protection = environment.protection; + const branchTracking = environment.branch_tracking; + + return { + name: environment.name, + description: environment.description, + logVerbosity: environment.log_verbosity, + robotsPolicy: environment.robots_policy, + protection: protection && { + azionAuthentication: protection.azion_authentication, + passwordProtection: protection.password_protection && { + enabled: protection.password_protection.enabled, + secretId: protection.password_protection.secret_id, + }, + ipAllowlist: protection.ip_allowlist, + ssoEnforcement: protection.sso_enforcement && { + enabled: protection.sso_enforcement.enabled, + idpId: protection.sso_enforcement.idp_id, + allowedDomains: protection.sso_enforcement.allowed_domains, + }, + }, + branchTracking: branchTracking + ? { + enabled: branchTracking.enabled, + mode: branchTracking.mode, + branchMatch: branchTracking.branch_match, + } + : null, + deploymentPolicy: environment.deployment_policy, + }; + }); + + return transformedPayload.environments; + } +} + +export default EnvironmentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts new file mode 100644 index 00000000..a912f14a --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.test.ts @@ -0,0 +1,54 @@ +import type { AzionConfigV6 } from '../../types'; +import StorageProcessConfigStrategy from './storageProcessConfigStrategy'; + +describe('StorageProcessConfigStrategy (v6)', () => { + let strategy: StorageProcessConfigStrategy; + + beforeEach(() => { + strategy = new StorageProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no storage', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, storage: [] })).toBeUndefined(); + }); + + it('should default workloads_access to read_only and leave the prefix out when it is not set', () => { + expect(strategy.transformToManifest({ version: 6, storage: [{ name: 'my-bucket', dir: './dist' }] })).toEqual([ + { name: 'my-bucket', workloads_access: 'read_only', dir: './dist' }, + ]); + }); + + it('should map every field of the storage to the manifest', () => { + expect( + strategy.transformToManifest({ + version: 6, + storage: [{ name: 'my-bucket', dir: './dist', workloadsAccess: 'restricted', prefix: 'assets' }], + }), + ).toEqual([{ name: 'my-bucket', workloads_access: 'restricted', dir: './dist', prefix: 'assets' }]); + }); + }); + + describe('transformToConfig', () => { + it('should not set storage when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.storage).toBeUndefined(); + }); + + it('should map the manifest storage back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { storage: [{ name: 'my-bucket', workloads_access: 'read_write', dir: './dist', prefix: 'p' }] }, + transformedPayload, + ); + + expect(transformedPayload.storage).toEqual([ + { name: 'my-bucket', workloadsAccess: 'read_write', dir: './dist', prefix: 'p' }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts new file mode 100644 index 00000000..4ba4ffb7 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/storageProcessConfigStrategy.ts @@ -0,0 +1,41 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../types'; + +/** + * StorageProcessConfigStrategy V6 + * @class StorageProcessConfigStrategy + * @description Converts the v6 storage between the config and the manifest. + */ +class StorageProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.storage) || config?.storage.length === 0) { + return; + } + + return config.storage.map((item) => ({ + name: item.name, + workloads_access: item.workloadsAccess || 'read_only', + dir: item.dir, + ...(item.prefix !== undefined && { prefix: item.prefix }), + })); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const storageConfig = payload.storage; + if (!Array.isArray(storageConfig) || storageConfig.length === 0) { + return; + } + + transformedPayload.storage = storageConfig.map((item) => ({ + name: item.name, + workloadsAccess: item.workloads_access || 'read_only', + dir: item.dir, + prefix: item.prefix, + })); + + return transformedPayload.storage; + } +} + +export default StorageProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts new file mode 100644 index 00000000..29c100e0 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts @@ -0,0 +1,170 @@ +import type { AzionConfigV6 } from '../../types'; +import WorkloadProcessConfigStrategy from './workloadProcessConfigStrategy'; + +describe('WorkloadProcessConfigStrategy (v6)', () => { + let strategy: WorkloadProcessConfigStrategy; + + const declared: AzionConfigV6 = { + version: 6, + environments: [{ name: 'production' }], + deployments: [{ name: 'default-deployment' }], + }; + + beforeEach(() => { + strategy = new WorkloadProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no workloads', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, workloads: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal workload', () => { + const result = strategy.transformToManifest({ version: 6, workloads: [{ name: 'my-workload' }] }); + + expect(result).toEqual([ + { + name: 'my-workload', + active: true, + infrastructure: 1, + workload_domain_allow_access: true, + tls: { minimum_version: 'tls_1_3' }, + protocols: { + http: { + versions: ['http1', 'http2', 'http3'], + http_ports: [80], + https_ports: [443], + quic_ports: [443], + }, + }, + mtls: undefined, + bindings: [], + }, + ]); + }); + + it('should not send tls.ciphers when it is not set (the v6 API does not accept null)', () => { + const [withoutCiphers] = strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] }); + const [withCiphers] = strategy.transformToManifest({ + version: 6, + workloads: [{ name: 'w', tls: { ciphers: 3, minimumVersion: 'tls_1_2' } }], + }); + + expect(withoutCiphers.tls).not.toHaveProperty('ciphers'); + expect(withCiphers.tls).toEqual({ ciphers: 3, minimum_version: 'tls_1_2' }); + }); + + it('should map every field of the workload, the mtls and the bindings to the manifest', () => { + const [workload] = strategy.transformToManifest({ + ...declared, + workloads: [ + { + name: 'my-workload', + active: false, + infrastructure: 2, + workloadDomainAllowAccess: false, + protocols: { http: { versions: ['http2'], httpPorts: [8080], httpsPorts: [8443], quicPorts: [8443] } }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1] } }, + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'example.com', certificate: 7 }, { domain: 'www.example.com' }], + }, + ], + }, + ], + }); + + expect(workload).toEqual( + expect.objectContaining({ + active: false, + infrastructure: 2, + workload_domain_allow_access: false, + protocols: { http: { versions: ['http2'], http_ports: [8080], https_ports: [8443], quic_ports: [8443] } }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1] } }, + }), + ); + expect(workload.bindings).toEqual([ + { + environment_id: 'production', + deployment_id: 'default-deployment', + domains: [ + { domain: 'example.com', certificate: 7 }, + { domain: 'www.example.com', certificate: null }, + ], + }, + ]); + }); + + it('should throw when a binding references an environment that is not declared', () => { + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }], + }), + ).toThrow('Workload "w" binding references non-existent Environment "staging".'); + }); + + it('should throw when a binding references a deployment that is not declared', () => { + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'other' }] }], + }), + ).toThrow('Workload "w" binding references non-existent Deployment "other".'); + expect(() => + strategy.transformToManifest({ + version: 6, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'd' }] }], + }), + ).toThrow('non-existent Environment "production"'); + }); + }); + + describe('transformToConfig', () => { + it('should not set workloads when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.workloads).toBeUndefined(); + }); + + it('should map the manifest workloads and bindings back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + workloads: [ + { + name: 'my-workload', + active: true, + infrastructure: 1, + workload_domain_allow_access: true, + tls: { ciphers: 3, minimum_version: 'tls_1_2' }, + protocols: { http: { versions: ['http1'], http_ports: [80], https_ports: [443], quic_ports: null } }, + bindings: [ + { environment_id: 'ENV01', deployment_id: 'DEP01', domains: [{ domain: 'a.com', certificate: 1 }] }, + ], + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.workloads).toEqual([ + { + name: 'my-workload', + active: true, + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, + protocols: { http: { versions: ['http1'], httpPorts: [80], httpsPorts: [443], quicPorts: null } }, + mtls: undefined, + bindings: [{ environment: 'ENV01', deployment: 'DEP01', domains: [{ domain: 'a.com', certificate: 1 }] }], + }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts new file mode 100644 index 00000000..dd1a1450 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts @@ -0,0 +1,123 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; + +/** + * WorkloadProcessConfigStrategy V6 + * @class WorkloadProcessConfigStrategy + * @description Converts the v6 workloads between the config and the manifest. + * A binding references an environment and a deployment by the name it has in the config. The manifest keeps that name + * in `environment_id` and `deployment_id`, which the Azion CLI resolves to the ids of the API. + */ +class WorkloadProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that the environment and the deployment of the bindings are declared + */ + private validateBindingReferences(config: AzionConfigV6, workload: AzionWorkloadV6) { + workload.bindings?.forEach((binding) => { + if (!config.environments?.some((environment) => environment.name === binding.environment)) { + throw new Error( + `Workload "${workload.name}" binding references non-existent Environment "${binding.environment}".`, + ); + } + if (!config.deployments?.some((deployment) => deployment.name === binding.deployment)) { + throw new Error( + `Workload "${workload.name}" binding references non-existent Deployment "${binding.deployment}".`, + ); + } + }); + } + + transformToManifest(config: AzionConfigV6) { + const workloads = config?.workloads; + if (!workloads || workloads.length === 0) return []; + + return workloads.map((workload: AzionWorkloadV6) => { + this.validateBindingReferences(config, workload); + + return { + name: workload.name, + active: workload.active ?? true, + infrastructure: workload.infrastructure || 1, + workload_domain_allow_access: workload.workloadDomainAllowAccess ?? true, + tls: { + ...(workload.tls?.ciphers && { ciphers: workload.tls.ciphers }), + minimum_version: workload.tls?.minimumVersion || 'tls_1_3', + }, + protocols: { + http: { + versions: workload.protocols?.http?.versions || ['http1', 'http2', 'http3'], + http_ports: workload.protocols?.http?.httpPorts || [80], + https_ports: workload.protocols?.http?.httpsPorts || [443], + quic_ports: workload.protocols?.http?.quicPorts || [443], + }, + }, + mtls: workload.mtls + ? { + enabled: workload.mtls.enabled || false, + config: { + verification: workload.mtls.config.verification || 'enforce', + certificate: workload.mtls.config.certificate, + crl: workload.mtls.config.crl, + }, + } + : undefined, + bindings: (workload.bindings ?? []).map((binding) => ({ + environment_id: binding.environment, + deployment_id: binding.deployment, + domains: (binding.domains ?? []).map((item) => ({ + domain: item.domain, + certificate: item.certificate ?? null, + })), + })), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { workloads?: any[] }, transformedPayload: AzionConfigV6) { + if (!payload.workloads || payload.workloads.length === 0) { + return; + } + + transformedPayload.workloads = payload.workloads.map((workload) => ({ + name: workload.name, + active: workload.active, + infrastructure: workload.infrastructure, + workloadDomainAllowAccess: workload.workload_domain_allow_access, + tls: { + ciphers: workload.tls?.ciphers, + minimumVersion: workload.tls?.minimum_version, + }, + protocols: { + http: { + versions: workload.protocols?.http?.versions, + httpPorts: workload.protocols?.http?.http_ports, + httpsPorts: workload.protocols?.http?.https_ports, + quicPorts: workload.protocols?.http?.quic_ports, + }, + }, + mtls: workload.mtls + ? { + enabled: workload.mtls.enabled || false, + config: { + verification: workload.mtls.config.verification || 'enforce', + certificate: workload.mtls.config.certificate, + crl: workload.mtls.config.crl, + }, + } + : undefined, + bindings: workload.bindings?.map( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (binding: any) => ({ + environment: binding.environment_id, + deployment: binding.deployment_id, + domains: binding.domains, + }), + ), + })); + + return transformedPayload.workloads; + } +} + +export default WorkloadProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index e96aa739..70ff1ed6 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -2,7 +2,12 @@ import ProcessConfigContext from '../../shared/processStrategy/processConfigCont import type { AzionConfigV6 } from '../types'; import ApplicationProcessConfigStrategy from './implementations/application/applicationProcessConfigStrategy'; import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; +import ConnectorProcessConfigStrategy from './implementations/connectorProcessConfigStrategy'; +import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; +import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; +import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; +import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; function factoryProcessContext() { @@ -10,7 +15,12 @@ function factoryProcessContext() { processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('functions', new FunctionsProcessConfigStrategy()); + processConfigContext.setStrategy('storage', new StorageProcessConfigStrategy()); + processConfigContext.setStrategy('connectors', new ConnectorProcessConfigStrategy()); processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); + processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); + processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); + processConfigContext.setStrategy('workloads', new WorkloadProcessConfigStrategy()); // TODO: register the other v6 strategies (setStrategy) as the v6 resources are defined return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/connectors/index.ts b/packages/config/src/versions/v6/schemas/connectors/index.ts new file mode 100644 index 00000000..9895d72e --- /dev/null +++ b/packages/config/src/versions/v6/schemas/connectors/index.ts @@ -0,0 +1,390 @@ +import { + CONNECTOR_DNS_RESOLUTION, + CONNECTOR_HMAC_TYPE, + CONNECTOR_HTTP_VERSION_POLICY, + CONNECTOR_LIVE_INGEST_REGIONS, + CONNECTOR_LOAD_BALANCE_METHOD, + CONNECTOR_SERVER_ROLES, + CONNECTOR_TRANSPORT_POLICY, + CONNECTOR_TYPES, +} from '../../constants'; + +const storageAttributesSchema = { + type: 'object', + properties: { + bucket: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'bucket' field must be a string between 1 and 255 characters", + }, + prefix: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'prefix' field must be a string between 1 and 255 characters", + }, + }, + required: ['bucket'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in storage attributes', + required: "The 'bucket' field is required in storage attributes", + }, +}; + +const liveIngestAttributesSchema = { + type: 'object', + properties: { + region: { + type: 'string', + enum: CONNECTOR_LIVE_INGEST_REGIONS, + errorMessage: `The 'region' field must be one of: ${CONNECTOR_LIVE_INGEST_REGIONS.join(', ')}`, + }, + }, + required: ['region'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in live ingest attributes', + required: "The 'region' field is required in live ingest attributes", + }, +}; + +const httpAttributesSchema = { + type: 'object', + properties: { + addresses: { + type: 'array', + minItems: 1, + items: { + type: 'object', + properties: { + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + address: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'address' field must be a string between 1 and 255 characters", + }, + httpPort: { + type: 'integer', + minimum: 1, + maximum: 65535, + default: 80, + errorMessage: "The 'httpPort' must be between 1 and 65535", + }, + httpsPort: { + type: 'integer', + minimum: 1, + maximum: 65535, + default: 443, + errorMessage: "The 'httpsPort' must be between 1 and 65535", + }, + modules: { + type: 'object', + properties: { + loadBalancer: { + type: 'object', + properties: { + serverRole: { + type: 'string', + enum: CONNECTOR_SERVER_ROLES, + errorMessage: `The 'serverRole' must be one of: ${CONNECTOR_SERVER_ROLES.join(', ')}`, + }, + weight: { + type: 'integer', + minimum: 1, + maximum: 100, + default: 1, + errorMessage: "The 'weight' must be between 1 and 100", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: "The 'modules' field of an address must be an object", + }, + }, + required: ['address'], + additionalProperties: false, + }, + errorMessage: "The 'addresses' field must be an array of at least one address object", + }, + connectionOptions: { + type: 'object', + properties: { + dnsResolution: { + type: 'string', + enum: CONNECTOR_DNS_RESOLUTION, + default: 'both', + errorMessage: `The 'dnsResolution' must be one of: ${CONNECTOR_DNS_RESOLUTION.join(', ')}`, + }, + transportPolicy: { + type: 'string', + enum: CONNECTOR_TRANSPORT_POLICY, + default: 'preserve', + errorMessage: `The 'transportPolicy' must be one of: ${CONNECTOR_TRANSPORT_POLICY.join(', ')}`, + }, + httpVersionPolicy: { + type: 'string', + enum: CONNECTOR_HTTP_VERSION_POLICY, + default: 'http1_1', + errorMessage: "The 'httpVersionPolicy' must be http1_1", + }, + host: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + default: '${host}', + errorMessage: "The 'host' field must be a string between 1 and 255 characters", + }, + pathPrefix: { + type: 'string', + minLength: 0, + maxLength: 255, + pattern: '.*', + default: '', + errorMessage: "The 'pathPrefix' field must be a string between 0 and 255 characters", + }, + followingRedirect: { + type: 'boolean', + default: false, + errorMessage: "The 'followingRedirect' field must be a boolean", + }, + realIpHeader: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + default: 'X-Real-IP', + errorMessage: "The 'realIpHeader' field must be a string between 1 and 100 characters", + }, + realPortHeader: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + default: 'X-Real-PORT', + errorMessage: "The 'realPortHeader' field must be a string between 1 and 100 characters", + }, + }, + additionalProperties: false, + errorMessage: "The 'connectionOptions' field must be an object with valid connection options", + }, + modules: { + type: 'object', + properties: { + loadBalancer: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + method: { + type: 'string', + enum: CONNECTOR_LOAD_BALANCE_METHOD, + default: 'round_robin', + errorMessage: `The 'method' must be one of: ${CONNECTOR_LOAD_BALANCE_METHOD.join(', ')}`, + }, + maxRetries: { + type: 'integer', + minimum: 0, + maximum: 20, + default: 0, + errorMessage: "The 'maxRetries' must be between 0 and 20", + }, + connectionTimeout: { + type: 'integer', + minimum: 1, + maximum: 300, + default: 60, + errorMessage: "The 'connectionTimeout' must be between 1 and 300", + }, + readWriteTimeout: { + type: 'integer', + minimum: 1, + maximum: 600, + default: 120, + errorMessage: "The 'readWriteTimeout' must be between 1 and 600", + }, + }, + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + originShield: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + originIpAcl: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + }, + additionalProperties: false, + }, + hmac: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean", + }, + config: { + type: 'object', + properties: { + type: { + type: 'string', + enum: CONNECTOR_HMAC_TYPE, + errorMessage: "The 'type' must be one of: aws4_hmac_sha256", + }, + attributes: { + type: 'object', + properties: { + region: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'region' field must be a string between 1 and 255 characters", + }, + service: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + default: 's3', + errorMessage: "The 'service' field must be a string between 1 and 255 characters", + }, + accessKey: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'accessKey' field must be a string between 1 and 255 characters", + }, + secretKey: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'secretKey' field must be a string between 1 and 255 characters", + }, + }, + required: ['region', 'accessKey', 'secretKey'], + additionalProperties: false, + }, + }, + required: ['attributes'], + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + }, + required: ['enabled'], + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + }, + required: ['addresses'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in HTTP attributes', + required: "The 'addresses' field is required in HTTP attributes", + }, +}; + +/** + * Schema of the v6 connectors, from `ConnectorHTTPRequest`, `ConnectorStorageRequest` and `ConnectorLiveIngestRequest` + * of the v6 API. The attributes must match the type of the connector. + * Based on v4, checked against the v6 API: the storage prefix is optional, the HTTP attributes only require the + * addresses, an address can have load balancer modules, force_ipv6 is a DNS resolution, live ingest has a region + * and the module configs are not nullable. + */ +const connectorsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 255 characters", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + type: { + type: 'string', + enum: CONNECTOR_TYPES, + errorMessage: `The 'type' field must be one of: ${CONNECTOR_TYPES.join(', ')}`, + }, + attributes: { + type: 'object', + errorMessage: "The 'attributes' field must be an object", + }, + }, + required: ['name', 'type', 'attributes'], + additionalProperties: false, + allOf: [ + { + if: { properties: { type: { const: 'storage' } }, required: ['type'] }, + then: { properties: { attributes: storageAttributesSchema } }, + }, + { + if: { properties: { type: { const: 'http' } }, required: ['type'] }, + then: { properties: { attributes: httpAttributesSchema } }, + }, + { + if: { properties: { type: { const: 'live_ingest' } }, required: ['type'] }, + then: { properties: { attributes: liveIngestAttributesSchema } }, + }, + ], + errorMessage: { + additionalProperties: 'No additional properties are allowed in connector objects', + required: "The 'name', 'type' and 'attributes' fields are required in each connector", + }, + }, + errorMessage: "The 'connectors' field must be an array of connector objects", +}; + +export default connectorsSchema; diff --git a/packages/config/src/versions/v6/schemas/deployments/index.ts b/packages/config/src/versions/v6/schemas/deployments/index.ts new file mode 100644 index 00000000..78e1b67c --- /dev/null +++ b/packages/config/src/versions/v6/schemas/deployments/index.ts @@ -0,0 +1,64 @@ +import { DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES } from '../../constants'; + +/** + * Schema of the v6 deployments, from `DeploymentRequest` of the v6 API. + */ +const deploymentsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 3, + maxLength: 255, + errorMessage: "The 'name' field must be a string between 3 and 255 characters", + }, + description: { + type: ['string', 'null'], + errorMessage: "The 'description' field must be a string or null", + }, + bindingPolicy: { + type: 'string', + enum: DEPLOYMENT_BINDING_POLICIES, + errorMessage: `The 'bindingPolicy' field must be one of: ${DEPLOYMENT_BINDING_POLICIES.join(', ')}`, + }, + deploymentPolicy: { + type: 'string', + enum: DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, + }, + strategyDefaults: { + type: 'object', + properties: { + skewProtection: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + defaultTtlSeconds: { type: 'integer', minimum: 1, maximum: 2147483647 }, + }, + required: ['enabled', 'defaultTtlSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in skewProtection', + required: "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + }, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in strategyDefaults', + }, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in deployment objects', + required: { name: "The 'name' field is required in each deployment" }, + }, + }, + errorMessage: "The 'deployments' field must be an array of deployment objects", +}; + +export default deploymentsSchema; diff --git a/packages/config/src/versions/v6/schemas/environments/index.ts b/packages/config/src/versions/v6/schemas/environments/index.ts new file mode 100644 index 00000000..c456a681 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/environments/index.ts @@ -0,0 +1,113 @@ +import { + DEPLOYMENT_POLICIES, + ENVIRONMENT_BRANCH_TRACKING_MODES, + ENVIRONMENT_LOG_VERBOSITY, + ENVIRONMENT_ROBOTS_POLICIES, +} from '../../constants'; + +/** + * Schema of the v6 environments, from `EnvironmentRequest` of the v6 API. + */ +const environmentsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 3, + maxLength: 255, + errorMessage: "The 'name' field must be a string between 3 and 255 characters", + }, + description: { + type: ['string', 'null'], + errorMessage: "The 'description' field must be a string or null", + }, + logVerbosity: { + type: 'string', + enum: ENVIRONMENT_LOG_VERBOSITY, + errorMessage: `The 'logVerbosity' field must be one of: ${ENVIRONMENT_LOG_VERBOSITY.join(', ')}`, + }, + robotsPolicy: { + type: 'string', + enum: ENVIRONMENT_ROBOTS_POLICIES, + errorMessage: `The 'robotsPolicy' field must be one of: ${ENVIRONMENT_ROBOTS_POLICIES.join(', ')}`, + }, + protection: { + type: 'object', + properties: { + azionAuthentication: { + type: 'object', + properties: { enabled: { type: 'boolean' } }, + required: ['enabled'], + additionalProperties: false, + }, + passwordProtection: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + secretId: { type: ['string', 'null'], minLength: 1 }, + }, + required: ['enabled', 'secretId'], + additionalProperties: false, + }, + ipAllowlist: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + cidrs: { type: 'array', items: { type: 'string', minLength: 2, maxLength: 49 } }, + }, + required: ['enabled', 'cidrs'], + additionalProperties: false, + }, + ssoEnforcement: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + idpId: { type: ['string', 'null'], minLength: 1 }, + allowedDomains: { type: 'array', items: { type: 'string', minLength: 1 } }, + }, + required: ['enabled', 'idpId', 'allowedDomains'], + additionalProperties: false, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the environment protection', + }, + }, + branchTracking: { + type: ['object', 'null'], + properties: { + enabled: { type: 'boolean' }, + mode: { + type: 'string', + enum: ENVIRONMENT_BRANCH_TRACKING_MODES, + errorMessage: `The 'mode' field must be one of: ${ENVIRONMENT_BRANCH_TRACKING_MODES.join(', ')}`, + }, + branchMatch: { type: 'string', minLength: 1, maxLength: 255 }, + }, + required: ['enabled', 'mode', 'branchMatch'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in branchTracking', + required: "The 'enabled', 'mode' and 'branchMatch' fields are required in branchTracking", + }, + }, + deploymentPolicy: { + type: 'string', + enum: DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in environment objects', + required: { name: "The 'name' field is required in each environment" }, + }, + }, + errorMessage: "The 'environments' field must be an array of environment objects", +}; + +export default environmentsSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index 592f6bf9..eb2ebee4 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -1,10 +1,15 @@ import applicationsSchema from './applications'; import buildSchema from './build'; +import connectorsSchema from './connectors'; +import deploymentsSchema from './deployments'; +import environmentsSchema from './environments'; import functionsSchema from './functions'; +import storageSchema from './storage'; +import workloadsSchema from './workloads'; /** * JSON Schema of the v6 config. - * TODO: only `version`, `build`, `functions` and `applications` are accepted until the schemas of the other v6 resources are defined. + * TODO: only `version`, `build`, `functions`, `storage`, `connectors`, `applications`, `workloads`, `environments` and `deployments` are accepted until the schemas of the other v6 resources are defined. */ const azionConfigSchema = { $id: 'azionConfig', @@ -15,12 +20,17 @@ const azionConfigSchema = { version: { type: 'number', enum: [6] }, build: buildSchema, functions: functionsSchema, + storage: storageSchema, + connectors: connectorsSchema, applications: applicationsSchema, + workloads: workloadsSchema, + environments: environmentsSchema, + deployments: deploymentsSchema, }, additionalProperties: false, errorMessage: { additionalProperties: - 'Config can only contain the following properties: version, build, functions, applications', + 'Config can only contain the following properties: version, build, functions, storage, connectors, applications, workloads, environments, deployments', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/schemas/storage/index.ts b/packages/config/src/versions/v6/schemas/storage/index.ts new file mode 100644 index 00000000..8baa308c --- /dev/null +++ b/packages/config/src/versions/v6/schemas/storage/index.ts @@ -0,0 +1,45 @@ +import { WORKLOADS_ACCESS_TYPES } from '../../constants'; + +/** + * Schema of the v6 storage, from `BucketCreateRequest` of the v6 API: the name has 6 to 63 lowercase letters, digits + * and hyphens, and does not start nor end with a hyphen. A `$PLACEHOLDER` is also accepted, as the presets use them + * and the Azion CLI replaces them. + */ +const storageSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 6, + maxLength: 63, + pattern: '^(\\$[A-Z][A-Z0-9_]*|[a-z0-9][a-z0-9-]*[a-z0-9])$', + errorMessage: + "The 'name' field must be a string between 6 and 63 characters, with lowercase letters, digits and hyphens, and must not start or end with a hyphen.", + }, + dir: { + type: 'string', + errorMessage: "The 'dir' field must be a string.", + }, + workloadsAccess: { + type: 'string', + enum: WORKLOADS_ACCESS_TYPES, + errorMessage: "The 'workloadsAccess' field must be one of: read_only, read_write, restricted.", + }, + prefix: { + type: 'string', + errorMessage: "The 'prefix' field must be a string.", + }, + }, + required: ['name', 'dir'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in storage items.', + required: "The 'name' and 'dir' fields are required.", + }, + }, + errorMessage: "The 'storage' field must be an array of storage items.", +}; + +export default storageSchema; diff --git a/packages/config/src/versions/v6/schemas/workloads/index.ts b/packages/config/src/versions/v6/schemas/workloads/index.ts new file mode 100644 index 00000000..6d560b2e --- /dev/null +++ b/packages/config/src/versions/v6/schemas/workloads/index.ts @@ -0,0 +1,204 @@ +import { + WORKLOAD_HTTP_VERSIONS, + WORKLOAD_INFRASTRUCTURE, + WORKLOAD_MTLS_VERIFICATION, + WORKLOAD_TLS_CIPHERS, + WORKLOAD_TLS_VERSIONS, +} from '../../constants'; + +/** + * Schema of the v6 workloads. + * Based on v4, checked against `WorkloadRequest` of the v6 API: the domains and the certificate moved to the + * `bindings`, `tls.ciphers` is not nullable and the ports and versions of the http protocol have limits. + */ +const workloadsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 100 characters", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + infrastructure: { + type: 'integer', + enum: WORKLOAD_INFRASTRUCTURE, + default: 1, + errorMessage: "The 'infrastructure' must be either 1 or 2", + }, + workloadDomainAllowAccess: { + type: 'boolean', + default: true, + errorMessage: "The 'workloadDomainAllowAccess' field must be a boolean", + }, + tls: { + type: 'object', + properties: { + ciphers: { + type: 'integer', + enum: WORKLOAD_TLS_CIPHERS, + errorMessage: "The 'ciphers' must be an integer between 1-8", + }, + minimumVersion: { + type: ['string', 'null'], + enum: [...WORKLOAD_TLS_VERSIONS, null], + default: 'tls_1_3', + errorMessage: "The 'minimumVersion' must be a valid TLS version or null", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: + 'No additional properties are allowed in tls. The certificate is set per domain in the bindings', + }, + }, + protocols: { + type: 'object', + properties: { + http: { + type: 'object', + properties: { + versions: { + type: 'array', + items: { + type: 'string', + enum: WORKLOAD_HTTP_VERSIONS, + }, + maxItems: 3, + default: ['http1', 'http2', 'http3'], + }, + httpPorts: { + type: 'array', + items: { type: 'integer' }, + minItems: 1, + maxItems: 4, + default: [80], + }, + httpsPorts: { + type: 'array', + items: { type: 'integer' }, + minItems: 1, + maxItems: 12, + default: [443], + }, + quicPorts: { + type: ['array', 'null'], + items: { type: 'integer' }, + maxItems: 12, + }, + }, + required: ['versions', 'httpPorts', 'httpsPorts'], + additionalProperties: false, + }, + }, + default: { + http: { + versions: ['http1', 'http2', 'http3'], + httpPorts: [80], + httpsPorts: [443], + quicPorts: [443], + }, + }, + additionalProperties: false, + }, + mtls: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + }, + config: { + type: 'object', + properties: { + verification: { + type: 'string', + enum: WORKLOAD_MTLS_VERIFICATION, + default: 'enforce', + }, + certificate: { + type: ['integer', 'null'], + minimum: 1, + }, + crl: { + type: ['array', 'null'], + items: { type: 'integer' }, + maxItems: 100, + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + bindings: { + type: 'array', + items: { + type: 'object', + properties: { + environment: { + type: 'string', + minLength: 1, + errorMessage: "The 'environment' field must be the name of an environment declared in 'environments'", + }, + deployment: { + type: 'string', + minLength: 1, + errorMessage: "The 'deployment' field must be the name of a deployment declared in 'deployments'", + }, + domains: { + type: 'array', + items: { + type: 'object', + properties: { + domain: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The 'domain' field must be a string between 1 and 250 characters", + }, + certificate: { + type: ['integer', 'null'], + minimum: 1, + errorMessage: "The 'certificate' must be an integer >= 1 or null", + }, + }, + required: ['domain'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in binding domains', + required: { domain: "The 'domain' field is required in each binding domain" }, + }, + }, + errorMessage: "The 'domains' field must be an array of domain objects", + }, + }, + required: ['environment', 'deployment'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in binding objects', + required: "The 'environment' and 'deployment' fields are required in each binding", + }, + }, + errorMessage: "The 'bindings' field must be an array of binding objects", + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in workload items', + required: { name: "The 'name' field is required in workloads" }, + }, + }, + errorMessage: "The 'workloads' field must be an array of workload items.", +}; + +export default workloadsSchema; diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index ff72b214..cbe78110 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -1,4 +1,29 @@ -import type { AzionBuild, AzionFunction, AzionFunctionInstance, AzionRules } from '../../types'; +import type { + AzionBuild, + AzionFunction, + AzionFunctionInstance, + AzionRules, + AzionWorkloadMTLS, + AzionWorkloadProtocols, + WorkloadInfrastructure, + WorkloadTLSCipher, + WorkloadTLSVersion, +} from '../../types'; +import type { + CONNECTOR_DNS_RESOLUTION, + CONNECTOR_HMAC_TYPE, + CONNECTOR_HTTP_VERSION_POLICY, + CONNECTOR_LIVE_INGEST_REGIONS, + CONNECTOR_LOAD_BALANCE_METHOD, + CONNECTOR_SERVER_ROLES, + CONNECTOR_TRANSPORT_POLICY, + DEPLOYMENT_BINDING_POLICIES, + DEPLOYMENT_POLICIES, + ENVIRONMENT_BRANCH_TRACKING_MODES, + ENVIRONMENT_LOG_VERBOSITY, + ENVIRONMENT_ROBOTS_POLICIES, + WORKLOADS_ACCESS_TYPES, +} from './constants'; /** * Function of the Azion API v6. @@ -31,6 +56,184 @@ export type AzionApplicationV6 = { functionsInstances?: AzionFunctionInstance[]; }; +/** + * TLS of a workload of the Azion API v6. The certificate is set per domain, in the bindings. + */ +export type AzionWorkloadTLSV6 = { + ciphers?: WorkloadTLSCipher; + minimumVersion?: WorkloadTLSVersion | null; +}; + +/** + * Domain served by a workload binding. + */ +export type AzionWorkloadBindingDomainV6 = { + /** Domain name */ + domain: string; + /** Digital certificate ID */ + certificate?: number | null; +}; + +/** + * Binding of a workload to an environment and a deployment. + */ +export type AzionWorkloadBindingV6 = { + /** Name of an environment declared in `environments` */ + environment: string; + /** Name of a deployment declared in `deployments` */ + deployment: string; + /** Domains served by the binding */ + domains?: AzionWorkloadBindingDomainV6[]; +}; + +/** + * Workload of the Azion API v6. + */ +export type AzionWorkloadV6 = { + name: string; + active?: boolean; + infrastructure?: WorkloadInfrastructure; + tls?: AzionWorkloadTLSV6; + protocols?: AzionWorkloadProtocols; + mtls?: AzionWorkloadMTLS; + workloadDomainAllowAccess?: boolean; + /** Environments and deployments the workload is bound to, with the domains of each binding */ + bindings?: AzionWorkloadBindingV6[]; +}; + +/** + * Environment of the Azion API v6. + */ +export type AzionEnvironmentV6 = { + /** Environment name */ + name: string; + description?: string | null; + logVerbosity?: (typeof ENVIRONMENT_LOG_VERBOSITY)[number]; + robotsPolicy?: (typeof ENVIRONMENT_ROBOTS_POLICIES)[number]; + protection?: { + azionAuthentication?: { enabled: boolean }; + passwordProtection?: { enabled: boolean; secretId: string | null }; + ipAllowlist?: { enabled: boolean; cidrs: string[] }; + ssoEnforcement?: { enabled: boolean; idpId: string | null; allowedDomains: string[] }; + }; + branchTracking?: { + enabled: boolean; + mode: (typeof ENVIRONMENT_BRANCH_TRACKING_MODES)[number]; + branchMatch: string; + } | null; + deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; +}; + +/** + * Deployment of the Azion API v6. + */ +export type AzionDeploymentV6 = { + /** Deployment name */ + name: string; + description?: string | null; + bindingPolicy?: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; + deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; + strategyDefaults?: { + skewProtection?: { enabled: boolean; defaultTtlSeconds: number }; + }; +}; + +/** + * Storage (bucket) of the Azion API v6. + */ +export type AzionStorageV6 = { + /** Storage name */ + name: string; + /** Access of the workloads to the storage */ + workloadsAccess?: (typeof WORKLOADS_ACCESS_TYPES)[number]; + /** Local directory whose files are uploaded to the storage */ + dir: string; + /** Prefix the files are uploaded under, which the storage connectors read from */ + prefix?: string; +}; + +/** + * Address of an HTTP connector. + */ +export type AzionConnectorAddressV6 = { + active?: boolean; + /** IPv4/IPv6 address or CNAME */ + address: string; + httpPort?: number; + httpsPort?: number; + /** Address modules */ + modules?: { + loadBalancer?: { + serverRole?: (typeof CONNECTOR_SERVER_ROLES)[number]; + weight?: number; + }; + }; +}; + +/** + * Attributes of an HTTP connector. + */ +export type AzionConnectorHttpAttributesV6 = { + addresses: AzionConnectorAddressV6[]; + connectionOptions?: { + dnsResolution?: (typeof CONNECTOR_DNS_RESOLUTION)[number]; + transportPolicy?: (typeof CONNECTOR_TRANSPORT_POLICY)[number]; + httpVersionPolicy?: (typeof CONNECTOR_HTTP_VERSION_POLICY)[number]; + host?: string; + pathPrefix?: string; + followingRedirect?: boolean; + realIpHeader?: string; + realPortHeader?: string; + }; + modules?: { + loadBalancer?: { + enabled: boolean; + config?: { + method?: (typeof CONNECTOR_LOAD_BALANCE_METHOD)[number]; + maxRetries?: number; + connectionTimeout?: number; + readWriteTimeout?: number; + }; + }; + originShield?: { + enabled: boolean; + config?: { + originIpAcl?: { enabled?: boolean }; + hmac?: { + enabled: boolean; + config?: { + type?: (typeof CONNECTOR_HMAC_TYPE)[number]; + attributes: { + region: string; + service?: string; + accessKey: string; + secretKey: string; + }; + }; + }; + }; + }; + }; +}; + +type AzionConnectorBaseV6 = { + /** Connector name */ + name: string; + /** Indicates if the connector is active */ + active?: boolean; +}; + +/** + * Connector of the Azion API v6. + */ +export type AzionConnectorV6 = + | (AzionConnectorBaseV6 & { type: 'http'; attributes: AzionConnectorHttpAttributesV6 }) + | (AzionConnectorBaseV6 & { type: 'storage'; attributes: { bucket: string; prefix?: string } }) + | (AzionConnectorBaseV6 & { + type: 'live_ingest'; + attributes: { region: (typeof CONNECTOR_LIVE_INGEST_REGIONS)[number] }; + }); + /** * Config of the Azion API v6. * TODO: structure placeholder. Add the remaining v6 resources once their schemas are defined. @@ -42,6 +245,16 @@ export type AzionConfigV6 = { build?: AzionBuild; /** Functions */ functions?: AzionFunctionV6[]; + /** Storage buckets */ + storage?: AzionStorageV6[]; + /** Connectors */ + connectors?: AzionConnectorV6[]; /** Applications */ applications?: AzionApplicationV6[]; + /** Workloads */ + workloads?: AzionWorkloadV6[]; + /** Environments */ + environments?: AzionEnvironmentV6[]; + /** Deployments */ + deployments?: AzionDeploymentV6[]; }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 699d4c6b..ef66ff1c 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -107,8 +107,8 @@ describe('validateConfig (v6)', () => { }); it('rejects properties the v6 schema does not know yet', () => { - expect(() => validateConfig({ version: 6, workloads: [] })).toThrow( - 'Config can only contain the following properties: version, build, functions, applications', + expect(() => validateConfig({ version: 6, firewall: [] })).toThrow( + 'Config can only contain the following properties: version, build, functions, storage, connectors, applications, workloads, environments, deployments', ); }); @@ -262,3 +262,408 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { }); }); }); + +describe('validateConfig (v6) workloads, environments and deployments', () => { + const workload = (extra: Record = {}) => ({ + version: 6, + workloads: [{ name: 'my-workload', ...extra }], + }); + const environment = (extra: Record = {}) => ({ + version: 6, + environments: [{ name: 'production', ...extra }], + }); + const deployment = (extra: Record = {}) => ({ + version: 6, + deployments: [{ name: 'default-deployment', ...extra }], + }); + + describe('workloads', () => { + it('accepts a complete workload', () => { + expect(() => + validateConfig( + workload({ + active: true, + infrastructure: 2, + workloadDomainAllowAccess: false, + tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, + protocols: { + http: { versions: ['http1', 'http2'], httpPorts: [80, 8080], httpsPorts: [443], quicPorts: null }, + }, + mtls: { enabled: true, config: { verification: 'permissive', certificate: 10, crl: [1, 2] } }, + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'example.com', certificate: 7 }, { domain: 'www.example.com' }], + }, + ], + }), + ), + ).not.toThrow(); + }); + + it('requires only the name', () => { + expect(() => validateConfig({ version: 6, workloads: [{ active: true }] })).toThrow( + "The 'name' field is required in workloads", + ); + expect(() => validateConfig(workload())).not.toThrow(); + }); + + it('limits the name to 100 characters', () => { + expect(() => validateConfig({ version: 6, workloads: [{ name: 'a'.repeat(100) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, workloads: [{ name: 'a'.repeat(101) }] })).toThrow( + "The 'name' field must be a string between 1 and 100 characters", + ); + }); + + it('moved the domains and the certificate to the bindings', () => { + expect(() => validateConfig(workload({ domains: ['example.com'] }))).toThrow( + 'No additional properties are allowed in workload items', + ); + expect(() => validateConfig(workload({ tls: { certificate: 1 } }))).toThrow( + 'The certificate is set per domain in the bindings', + ); + }); + + it('does not accept a null tls.ciphers nor one out of range', () => { + expect(() => validateConfig(workload({ tls: { ciphers: null } }))).toThrow( + "The 'ciphers' must be an integer between 1-8", + ); + expect(() => validateConfig(workload({ tls: { ciphers: 9 } }))).toThrow(); + }); + + it('applies the limits of the http protocol of the v6 API', () => { + const http = (extra: Record) => + workload({ protocols: { http: { versions: ['http1'], httpPorts: [80], httpsPorts: [443], ...extra } } }); + + expect(() => validateConfig(http({}))).not.toThrow(); + expect(() => validateConfig(http({ httpPorts: [] }))).toThrow(); + expect(() => validateConfig(http({ httpPorts: [80, 81, 82, 83, 84] }))).toThrow(); + expect(() => validateConfig(http({ httpsPorts: Array.from({ length: 13 }, (_, i) => 443 + i) }))).toThrow(); + expect(() => validateConfig(http({ quicPorts: Array.from({ length: 13 }, (_, i) => 443 + i) }))).toThrow(); + expect(() => validateConfig(http({ versions: ['http1', 'http2', 'http3', 'http1'] }))).toThrow(); + }); + + it('requires environment and deployment in a binding', () => { + expect(() => validateConfig(workload({ bindings: [{ environment: 'production' }] }))).toThrow( + "The 'environment' and 'deployment' fields are required in each binding", + ); + expect(() => validateConfig(workload({ bindings: [{ deployment: 'default-deployment' }] }))).toThrow(); + }); + + it('requires the domain in a binding domain and rejects unknown properties', () => { + const binding = (domains: unknown[]) => + workload({ bindings: [{ environment: 'production', deployment: 'default-deployment', domains }] }); + + expect(() => validateConfig(binding([{ certificate: 1 }]))).toThrow( + "The 'domain' field is required in each binding domain", + ); + expect(() => validateConfig(binding([{ domain: 'a.com', unknown: true }]))).toThrow( + 'No additional properties are allowed in binding domains', + ); + }); + }); + + describe('environments', () => { + it('accepts a complete environment', () => { + expect(() => + validateConfig( + environment({ + description: 'Production', + logVerbosity: 'verbose', + robotsPolicy: 'noindex', + protection: { + azionAuthentication: { enabled: true }, + passwordProtection: { enabled: true, secretId: 'secret' }, + ipAllowlist: { enabled: true, cidrs: ['10.0.0.0/8'] }, + ssoEnforcement: { enabled: false, idpId: null, allowedDomains: [] }, + }, + branchTracking: { enabled: true, mode: 'branch_starts_with', branchMatch: 'release/' }, + deploymentPolicy: 'versioned_urls', + }), + ), + ).not.toThrow(); + expect(() => validateConfig(environment({ description: null, branchTracking: null }))).not.toThrow(); + }); + + it('limits the name to 3-255 characters and requires it', () => { + expect(() => validateConfig({ version: 6, environments: [{ description: 'x' }] })).toThrow( + "The 'name' field is required in each environment", + ); + expect(() => validateConfig({ version: 6, environments: [{ name: 'ab' }] })).toThrow( + "The 'name' field must be a string between 3 and 255 characters", + ); + expect(() => validateConfig({ version: 6, environments: [{ name: 'a'.repeat(256) }] })).toThrow(); + }); + + it('rejects values out of the enums', () => { + expect(() => validateConfig(environment({ logVerbosity: 'debug' }))).toThrow( + "The 'logVerbosity' field must be one of: normal, verbose", + ); + expect(() => validateConfig(environment({ robotsPolicy: 'all' }))).toThrow( + "The 'robotsPolicy' field must be one of: index, noindex, respect_origin", + ); + expect(() => validateConfig(environment({ deploymentPolicy: 'multiple' }))).toThrow( + "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", + ); + expect(() => + validateConfig(environment({ branchTracking: { enabled: true, mode: 'branch_matches', branchMatch: 'a' } })), + ).toThrow("The 'mode' field must be one of: branch_is, branch_starts_with, branch_ends_with"); + }); + + it('requires the fields of branchTracking and of the protections', () => { + expect(() => validateConfig(environment({ branchTracking: { enabled: true } }))).toThrow( + "The 'enabled', 'mode' and 'branchMatch' fields are required in branchTracking", + ); + expect(() => validateConfig(environment({ protection: { ipAllowlist: { enabled: true } } }))).toThrow(); + expect(() => validateConfig(environment({ protection: { unknown: {} } }))).toThrow( + 'No additional properties are allowed in the environment protection', + ); + }); + }); + + describe('deployments', () => { + it('accepts a complete deployment', () => { + expect(() => + validateConfig( + deployment({ + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }), + ), + ).not.toThrow(); + }); + + it('limits the name to 3-255 characters and requires it', () => { + expect(() => validateConfig({ version: 6, deployments: [{ bindingPolicy: 'STRICT' }] })).toThrow( + "The 'name' field is required in each deployment", + ); + expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab' }] })).toThrow( + "The 'name' field must be a string between 3 and 255 characters", + ); + }); + + it('rejects values out of the enums and invalid skew protection', () => { + expect(() => validateConfig(deployment({ bindingPolicy: 'strict' }))).toThrow( + "The 'bindingPolicy' field must be one of: STRICT, FLEXIBLE", + ); + expect(() => validateConfig(deployment({ deploymentPolicy: 'rolling' }))).toThrow( + "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", + ); + expect(() => validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true } } }))).toThrow( + "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + ); + expect(() => + validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 0 } } })), + ).toThrow(); + }); + }); +}); + +describe('validateConfig (v6) storage and connectors', () => { + const storage = (extra: Record = {}) => ({ + version: 6, + storage: [{ name: 'my-bucket', dir: './dist', ...extra }], + }); + const connector = (extra: Record) => ({ + version: 6, + connectors: [{ name: 'my-connector', ...extra }], + }); + const http = (attributes: Record = {}) => + connector({ type: 'http', attributes: { addresses: [{ address: 'origin.example.com' }], ...attributes } }); + + describe('storage', () => { + it('accepts a complete storage', () => { + expect(() => validateConfig(storage({ workloadsAccess: 'read_write', prefix: 'assets' }))).not.toThrow(); + }); + + it('requires only name and dir (the prefix is optional in v6)', () => { + expect(() => validateConfig(storage())).not.toThrow(); + expect(() => validateConfig({ version: 6, storage: [{ dir: './dist' }] })).toThrow( + "The 'name' and 'dir' fields are required.", + ); + expect(() => validateConfig({ version: 6, storage: [{ name: 'my-bucket' }] })).toThrow(); + }); + + it('applies the name rules of the v6 API (lowercase letters, digits, hyphens, 6 to 63 characters)', () => { + const name = (value: string) => validateConfig({ version: 6, storage: [{ name: value, dir: './dist' }] }); + + expect(() => name('my-bucket-01')).not.toThrow(); + expect(() => name('a'.repeat(63))).not.toThrow(); + expect(() => name('short')).toThrow(); + expect(() => name('a'.repeat(64))).toThrow(); + expect(() => name('My-Bucket')).toThrow(); + expect(() => name('my_bucket')).toThrow(); + expect(() => name('-my-bucket')).toThrow(); + expect(() => name('my-bucket-')).toThrow(); + }); + + it('accepts a $PLACEHOLDER as the name, as the presets use them', () => { + expect(() => validateConfig({ version: 6, storage: [{ name: '$BUCKET_NAME', dir: './dist' }] })).not.toThrow(); + }); + + it('rejects an unknown workloadsAccess and unknown properties', () => { + expect(() => validateConfig(storage({ workloadsAccess: 'write_only' }))).toThrow( + "The 'workloadsAccess' field must be one of: read_only, read_write, restricted.", + ); + expect(() => validateConfig(storage({ unknown: true }))).toThrow( + 'No additional properties are allowed in storage items.', + ); + }); + }); + + describe('connectors', () => { + it('accepts a storage connector with and without prefix', () => { + expect(() => + validateConfig(connector({ type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } })), + ).not.toThrow(); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'my-bucket' } }))).not.toThrow(); + }); + + it('requires the bucket and does not accept an empty prefix in a storage connector', () => { + expect(() => validateConfig(connector({ type: 'storage', attributes: {} }))).toThrow( + "The 'bucket' field is required in storage attributes", + ); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'b', prefix: '' } }))).toThrow( + "The 'prefix' field must be a string between 1 and 255 characters", + ); + }); + + it('accepts a live ingest connector and validates its region', () => { + expect(() => + validateConfig(connector({ type: 'live_ingest', attributes: { region: 'br-east-1' } })), + ).not.toThrow(); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: { region: 'eu-west-1' } }))).toThrow( + "The 'region' field must be one of: us-east-1, us-east-2, br-east-1, br-east-2, br-east-3", + ); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: {} }))).toThrow( + "The 'region' field is required in live ingest attributes", + ); + }); + + it('accepts an http connector with only the addresses', () => { + expect(() => validateConfig(http())).not.toThrow(); + }); + + it('accepts a complete http connector', () => { + expect(() => + validateConfig( + http({ + addresses: [ + { + active: true, + address: 'origin.example.com', + httpPort: 8080, + httpsPort: 8443, + modules: { loadBalancer: { serverRole: 'backup', weight: 50 } }, + }, + ], + connectionOptions: { + dnsResolution: 'force_ipv6', + transportPolicy: 'force_https', + httpVersionPolicy: 'http1_1', + host: '${host}', + pathPrefix: '/api', + followingRedirect: true, + realIpHeader: 'X-Real-IP', + realPortHeader: 'X-Real-PORT', + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'least_conn', maxRetries: 3, connectionTimeout: 30, readWriteTimeout: 60 }, + }, + originShield: { + enabled: true, + config: { + originIpAcl: { enabled: true }, + hmac: { + enabled: true, + config: { + type: 'aws4_hmac_sha256', + attributes: { region: 'us-east-1', service: 's3', accessKey: 'key', secretKey: 'secret' }, + }, + }, + }, + }, + }, + }), + ), + ).not.toThrow(); + }); + + it('requires at least one address with an address', () => { + expect(() => validateConfig(connector({ type: 'http', attributes: {} }))).toThrow( + "The 'addresses' field is required in HTTP attributes", + ); + expect(() => validateConfig(http({ addresses: [] }))).toThrow( + "The 'addresses' field must be an array of at least one address object", + ); + expect(() => validateConfig(http({ addresses: [{ httpPort: 80 }] }))).toThrow(); + }); + + it('accepts force_ipv6 (new in v6) and rejects the other values of dnsResolution', () => { + expect(() => validateConfig(http({ connectionOptions: { dnsResolution: 'force_ipv6' } }))).not.toThrow(); + expect(() => validateConfig(http({ connectionOptions: { dnsResolution: 'ipv6' } }))).toThrow( + "The 'dnsResolution' must be one of: both, force_ipv4, force_ipv6", + ); + }); + + it('validates the load balancer of an address (serverRole and weight)', () => { + const address = (loadBalancer: Record) => + http({ addresses: [{ address: 'o.example.com', modules: { loadBalancer } }] }); + + expect(() => validateConfig(address({ serverRole: 'primary', weight: 1 }))).not.toThrow(); + expect(() => validateConfig(address({ serverRole: 'secondary' }))).toThrow( + "The 'serverRole' must be one of: primary, backup", + ); + expect(() => validateConfig(address({ weight: 101 }))).toThrow("The 'weight' must be between 1 and 100"); + expect(() => validateConfig(address({ weight: 0 }))).toThrow(); + }); + + it('does not accept null in the module configs and requires enabled and the hmac attributes', () => { + expect(() => validateConfig(http({ modules: { loadBalancer: { enabled: true, config: null } } }))).toThrow(); + expect(() => validateConfig(http({ modules: { loadBalancer: {} } }))).toThrow(); + expect(() => + validateConfig( + http({ modules: { originShield: { enabled: true, config: { hmac: { enabled: true, config: {} } } } } }), + ), + ).toThrow(); + expect(() => + validateConfig(http({ modules: { originShield: { enabled: true, config: { hmac: { config: {} } } } } })), + ).toThrow(); + }); + + it('validates the limits of the load balancer config', () => { + const config = (value: Record) => + http({ modules: { loadBalancer: { enabled: true, config: value } } }); + + expect(() => validateConfig(config({ maxRetries: 21 }))).toThrow("The 'maxRetries' must be between 0 and 20"); + expect(() => validateConfig(config({ connectionTimeout: 301 }))).toThrow(); + expect(() => validateConfig(config({ readWriteTimeout: 601 }))).toThrow(); + expect(() => validateConfig(config({ method: 'random' }))).toThrow(); + }); + + it('ties the attributes to the type of the connector', () => { + expect(() => + validateConfig(connector({ type: 'storage', attributes: { addresses: [{ address: 'a.com' }] } })), + ).toThrow(); + expect(() => validateConfig(connector({ type: 'http', attributes: { bucket: 'my-bucket' } }))).toThrow(); + expect(() => validateConfig(connector({ type: 'live_ingest', attributes: { bucket: 'my-bucket' } }))).toThrow(); + }); + + it('requires name, type and attributes and rejects an unknown type and unknown properties', () => { + expect(() => + validateConfig({ version: 6, connectors: [{ type: 'storage', attributes: { bucket: 'b' } }] }), + ).toThrow("The 'name', 'type' and 'attributes' fields are required in each connector"); + expect(() => validateConfig(connector({ type: 'ftp', attributes: {} }))).toThrow( + "The 'type' field must be one of: http, storage, live_ingest", + ); + expect(() => validateConfig(connector({ type: 'storage', attributes: { bucket: 'b' }, unknown: true }))).toThrow( + 'No additional properties are allowed in connector objects', + ); + }); + }); +}); From a53d6c09506ec8c9e2e612068d409f20f8cacd7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 30 Oct 2026 17:41:44 -0300 Subject: [PATCH 08/29] feat(presets): add the v6 config to the react preset and the workload to the javascript one react: add the build, the storage, the storage connector, the application with the SPA rules, an environment, a deployment and the workload bound to them, as the v4 config has. The cache settings of the application are left out until the v6 config has them. javascript: add the environment, the deployment and the workload bound to them. Tests check that the storage, the connectors and the rules of the react v6 manifest are the same as the ones of the v4 manifest. --- packages/presets/src/presets/configs.test.ts | 44 +++++++++++-- .../src/presets/javascript/config.v6.ts | 26 +++++++- .../presets/src/presets/react/config.v6.ts | 64 +++++++++++++++++++ packages/presets/src/presets/react/index.ts | 9 ++- 4 files changed, 137 insertions(+), 6 deletions(-) create mode 100644 packages/presets/src/presets/react/config.v6.ts diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 9552b56f..5e338ce9 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -40,11 +40,15 @@ describe('preset configs by API version', () => { }); describe('v6', () => { - it('is declared by javascript only for now', () => { - const withV6 = presets.filter((preset) => preset.configs?.[6]).map((preset) => preset.metadata.name); - expect(withV6).toEqual(['javascript']); + it('is declared by javascript and react only for now', () => { + const withV6 = presets + .filter((preset) => preset.configs?.[6]) + .map((preset) => preset.metadata.name) + .sort(); + expect(withV6).toEqual(['javascript', 'react']); expect(getPresetApiVersions(byName('javascript'))).toEqual([3, 4, 6]); - expect(() => resolvePresetConfig(byName('react'), 6)).toThrow('does not support config version 6'); + expect(getPresetApiVersions(byName('react'))).toEqual([3, 4, 6]); + expect(() => resolvePresetConfig(byName('vue'), 6)).toThrow('does not support config version 6'); }); it('javascript: validates and keeps the build of the v4 config', () => { @@ -65,6 +69,38 @@ describe('preset configs by API version', () => { expect(v6.applications).toEqual(v4.applications); expect(v6.applications[0].modules.functions.enabled).toBe(true); }); + + it('react: validates and has the same storage, connectors and rules in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('react'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('react'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(v4.connectors); + expect(v6.applications[0].rules).toEqual(v4.applications[0].rules); + // the rules deliver the static assets from the storage connector + expect(JSON.stringify(v6.applications[0].rules)).toContain('"set_connector"'); + expect(v6.connectors.map((connector: { name: string }) => connector.name)).toEqual(['$CONNECTOR_NAME']); + }); + + it('javascript: binds the workload to an environment and a deployment declared in the config', () => { + const manifest = processConfig(resolvePresetConfig(byName('javascript'), 6)); + + expect(manifest.environments.map((environment: { name: string }) => environment.name)).toEqual([ + '$ENVIRONMENT_NAME', + ]); + expect(manifest.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); + expect(manifest.workloads).toHaveLength(1); + expect(manifest.workloads[0]).toEqual( + expect.objectContaining({ name: '$WORKLOAD_NAME', active: true, infrastructure: 1 }), + ); + expect(manifest.workloads[0].bindings).toEqual([ + { environment_id: '$ENVIRONMENT_NAME', deployment_id: '$DEPLOYMENT_NAME', domains: [] }, + ]); + }); }); describe.each(goldenPresets)('%s (v3)', (name) => { diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts index 9541c225..ef37cbb6 100644 --- a/packages/presets/src/presets/javascript/config.v6.ts +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -1,6 +1,6 @@ import type { AzionConfigV6 } from '@aziontech/config'; -// TODO: add the remaining v6 resources (workloads, connectors, storage...) once their schemas are defined +// TODO: add the remaining v6 resources (connectors, storage...) once their schemas are defined const config: AzionConfigV6 = { version: 6, build: { @@ -50,6 +50,30 @@ const config: AzionConfigV6 = { ], }, ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], }; export default config; diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts new file mode 100644 index 00000000..6dd5b1a5 --- /dev/null +++ b/packages/presets/src/presets/react/config.v6.ts @@ -0,0 +1,64 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +// TODO: add the cache settings of the application once the v6 config has them +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/react/index.ts b/packages/presets/src/presets/react/index.ts index 26634814..ba557dfa 100644 --- a/packages/presets/src/presets/react/index.ts +++ b/packages/presets/src/presets/react/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const react: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const react: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; From 0819361566c000df542835dc317aca9b642903ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 09:04:09 -0300 Subject: [PATCH 09/29] feat(config): add the function bindings to API v6 The bindings of a function (storage) work as in v4: the schema accepts the bucket by name or by id with its prefix, the manifest carries them and the strategy checks that a bucket referenced by name is declared in the storage (an id is not validated). The bindings are a concept of the manifest the Azion CLI reads, not a field of the v6 function request. --- .../functionsProcessConfigStrategy.test.ts | 38 +++++++++++++++++++ .../functionsProcessConfigStrategy.ts | 38 ++++++++++++++----- .../versions/v6/schemas/functions/index.ts | 31 ++++++++++++++- packages/config/src/versions/v6/types.ts | 3 +- .../versions/v6/validateConfig/index.test.ts | 34 +++++++++++++---- 5 files changed, 125 insertions(+), 19 deletions(-) diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts index 5965fcc0..98ba29d6 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts @@ -60,6 +60,44 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { }); }); + describe('bindings', () => { + const withBinding = (bucket: string, storage?: AzionConfigV6['storage']): AzionConfigV6 => ({ + version: 6, + storage, + functions: [ + { name: 'my-function', path: './functions/index.js', bindings: { storage: { bucket, prefix: 'p' } } }, + ], + }); + + it('should write the bindings to the manifest', () => { + const [func] = strategy.transformToManifest( + withBinding('my-bucket', [{ name: 'my-bucket', dir: './dist', prefix: 'p' }]), + ); + + expect(func.bindings).toEqual({ storage: { bucket: 'my-bucket', prefix: 'p' } }); + }); + + it('should leave the bindings out of the manifest when the function has none', () => { + const [func] = strategy.transformToManifest({ version: 6, functions: [{ name: 'f', path: './f.js' }] }); + + expect(func.bindings).toBeUndefined(); + }); + + it('should throw when the storage bucket of a binding is not defined', () => { + const message = + 'Function "my-function" references storage bucket "my-bucket" which is not defined in the storage configuration.'; + + expect(() => strategy.transformToManifest(withBinding('my-bucket'))).toThrow(message); + expect(() => + strategy.transformToManifest(withBinding('my-bucket', [{ name: 'other-bucket', dir: './dist' }])), + ).toThrow(message); + }); + + it('should not validate a bucket referenced by id', () => { + expect(() => strategy.transformToManifest(withBinding(10 as unknown as string))).not.toThrow(); + }); + }); + describe('transformToConfig', () => { it('should not set functions when the manifest has none', () => { const transformedPayload: AzionConfigV6 = { version: 6 }; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts index 0e414471..c124ac56 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts @@ -6,9 +6,21 @@ import type { AzionConfigV6 } from '../../types'; * FunctionsProcessConfigStrategy V6 * @class FunctionsProcessConfigStrategy * @description This class is implementation of the Functions Process Config Strategy for API V6. - * TODO: validate and convert `bindings` (storage) once the v6 config has storage. */ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate storage binding reference + */ + private validateStorageBinding(config: AzionConfigV6, bucketNameOrId: string | number, functionName: string) { + if (typeof bucketNameOrId === 'string') { + if (!Array.isArray(config?.storage) || !config.storage.find((storage) => storage.name === bucketNameOrId)) { + throw new Error( + `Function "${functionName}" references storage bucket "${bucketNameOrId}" which is not defined in the storage configuration.`, + ); + } + } + } + /** * Transform azion.config Functions to V6 manifest format */ @@ -17,14 +29,22 @@ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy ({ - name: func.name, - runtime: func.runtime || 'azion_js', - default_args: func.defaultArgs || {}, - execution_environment: func.executionEnvironment || 'application', - active: func.active ?? true, - path: func.path, - })); + return config.functions.map((func) => { + // Validate storage binding if exists + if (func.bindings?.storage?.bucket) { + this.validateStorageBinding(config, func.bindings.storage.bucket, func.name); + } + + return { + name: func.name, + runtime: func.runtime || 'azion_js', + default_args: func.defaultArgs || {}, + execution_environment: func.executionEnvironment || 'application', + active: func.active ?? true, + path: func.path, + bindings: func.bindings, + }; + }); } /** diff --git a/packages/config/src/versions/v6/schemas/functions/index.ts b/packages/config/src/versions/v6/schemas/functions/index.ts index 9659f145..4146bec2 100644 --- a/packages/config/src/versions/v6/schemas/functions/index.ts +++ b/packages/config/src/versions/v6/schemas/functions/index.ts @@ -1,4 +1,3 @@ -// TODO: add `bindings` (storage) once the v6 config has storage const functionsSchema = { type: 'array', items: { @@ -37,6 +36,36 @@ const functionsSchema = { default: true, errorMessage: "The 'active' field must be a boolean", }, + bindings: { + type: 'object', + properties: { + storage: { + type: 'object', + properties: { + bucket: { + type: ['string', 'number'], + errorMessage: "The 'bucket' field must be a string or number", + }, + prefix: { + type: 'string', + errorMessage: "The 'prefix' field must be a string", + }, + }, + required: ['bucket', 'prefix'], + additionalProperties: false, + errorMessage: { + type: "The 'storage' field must be an object", + additionalProperties: 'No additional properties are allowed in the storage object binding.', + required: "The 'bucket' and 'prefix' fields are required in the storage object binding.", + }, + }, + }, + additionalProperties: false, + errorMessage: { + type: "The 'bindings' field must be an object", + additionalProperties: 'No additional properties are allowed in the bindings object', + }, + }, }, required: ['name', 'path'], additionalProperties: false, diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index cbe78110..3c4024b4 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -27,9 +27,8 @@ import type { /** * Function of the Azion API v6. - * TODO: add `bindings` (storage) once the v6 config has storage. */ -export type AzionFunctionV6 = Omit; +export type AzionFunctionV6 = AzionFunction; /** * Application of the Azion API v6. diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index ef66ff1c..99fefd4d 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -150,13 +150,33 @@ describe('validateConfig (v6) functions', () => { ).toThrow("The 'executionEnvironment' field must be 'application' or 'firewall'"); }); - it('does not accept bindings yet (v6 has no storage)', () => { - expect(() => - validateConfig({ - version: 6, - functions: [{ name: 'a', path: './a.js', bindings: { storage: { bucket: 'b', prefix: 'p' } } }], - }), - ).toThrow(); + describe('bindings', () => { + const binding = (bindings: unknown) => ({ + version: 6, + functions: [{ name: 'my-function', path: './functions/index.js', bindings }], + }); + + it('accepts a storage binding with the bucket as a name or an id', () => { + expect(() => validateConfig(binding({ storage: { bucket: 'my-bucket', prefix: 'assets' } }))).not.toThrow(); + expect(() => validateConfig(binding({ storage: { bucket: 10, prefix: '' } }))).not.toThrow(); + expect(() => validateConfig(binding({}))).not.toThrow(); + }); + + it('requires the bucket and the prefix of a storage binding', () => { + expect(() => validateConfig(binding({ storage: { bucket: 'my-bucket' } }))).toThrow( + "The 'bucket' and 'prefix' fields are required in the storage object binding.", + ); + expect(() => validateConfig(binding({ storage: { prefix: 'assets' } }))).toThrow(); + }); + + it('rejects unknown properties in the bindings and in the storage binding', () => { + expect(() => validateConfig(binding({ kv: {} }))).toThrow( + 'No additional properties are allowed in the bindings object', + ); + expect(() => + validateConfig(binding({ storage: { bucket: 'my-bucket', prefix: 'assets', unknown: true } })), + ).toThrow('No additional properties are allowed in the storage object binding.'); + }); }); }); From 77042ed3f586fdf30670bd35a44b50fd40ca3588 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 09:04:29 -0300 Subject: [PATCH 10/29] feat(config): add the application cache settings to API v6 Add the v6 schema and process strategy of the application cache, based on v4 and checked against CacheSettingRequest of the v6 API: the structure is the same, the max age is between 0 and 31536000 (1 year) and the tiered cache topology is not nullable. A max age can be a mathematical expression, which the schema cannot check, so the strategy checks the range after evaluating it. --- .../applicationProcessConfigStrategy.test.ts | 26 +++ .../applicationProcessConfigStrategy.ts | 9 +- .../cacheProcessConfigStrategy.test.ts | 138 ++++++++++++ .../application/cacheProcessConfigStrategy.ts | 178 +++++++++++++++ .../versions/v6/schemas/applications/index.ts | 207 +++++++++++++++++- packages/config/src/versions/v6/types.ts | 5 +- .../versions/v6/validateConfig/index.test.ts | 79 +++++++ 7 files changed, 639 insertions(+), 3 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts index 2532b8e6..e074ddcc 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts @@ -92,6 +92,32 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(application.functions_instances).toEqual([{ name: 'instance', function: 'fn', args: {}, active: true }]); }); + it('should write the cache settings to the manifest as cache_settings and read them back', () => { + const withCache: AzionConfigV6 = { + version: 6, + applications: [{ name: 'my-app', cache: [{ name: 'my-cache', browser: { maxAgeSeconds: 7200 } }] }], + }; + const [application] = strategy.transformToManifest(withCache); + + expect(application.cache_settings).toHaveLength(1); + expect(application.cache_settings[0]).toEqual( + expect.objectContaining({ name: 'my-cache', browser_cache: { behavior: 'override', max_age: 7200 } }), + ); + + const transformedPayload: AzionConfigV6 = { version: 6 }; + strategy.transformToConfig({ applications: [application] }, transformedPayload); + + expect(transformedPayload.applications?.[0].cache?.[0]).toEqual( + expect.objectContaining({ name: 'my-cache', browser: { maxAgeSeconds: 7200 } }), + ); + }); + + it('should not write cache_settings when the application has no cache', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('cache_settings'); + }); + it('should enable the functions module when the application has function instances', () => { const [application] = strategy.transformToManifest(config); expect(application.modules.functions.enabled).toBe(true); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts index 25295599..2ea5b476 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -1,5 +1,6 @@ import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; import type { AzionApplicationV6, AzionConfigV6 } from '../../../types'; +import CacheProcessConfigStrategy from './cacheProcessConfigStrategy'; import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; @@ -7,9 +8,10 @@ import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; * ApplicationProcessConfigStrategy * @class ApplicationProcessConfigStrategy * @description Converts the v6 applications between the config and the manifest. - * TODO: convert the remaining resources of an application (cache settings, device groups). + * TODO: convert the remaining resources of an application (device groups). */ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { + private cacheStrategy = new CacheProcessConfigStrategy(); private rulesStrategy = new RulesProcessConfigStrategy(); private functionInstancesStrategy = new FunctionInstancesProcessConfigStrategy(); @@ -41,6 +43,10 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { + let strategy: CacheProcessConfigStrategy; + + beforeEach(() => { + strategy = new CacheProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no cache settings', () => { + expect(strategy.transformToManifest([])).toEqual([]); + expect(strategy.transformToManifest(undefined as unknown as AzionCache[])).toEqual([]); + }); + + it('should apply the defaults to a minimal cache setting', () => { + expect(strategy.transformToManifest([{ name: 'my-cache' }])).toEqual([ + { + name: 'my-cache', + browser_cache: { behavior: 'honor', max_age: 0 }, + modules: { + cache: { + behavior: 'honor', + max_age: 60, + stale_cache: { enabled: false }, + large_file_cache: { enabled: false, offset: 1024 }, + tiered_cache: { enabled: false }, + }, + application_accelerator: { + cache_vary_by_method: [], + cache_vary_by_querystring: { behavior: 'ignore', fields: [], sort_enabled: false }, + cache_vary_by_cookies: { behavior: 'ignore', cookie_names: [] }, + cache_vary_by_devices: { behavior: 'ignore', device_group: [] }, + }, + }, + }, + ]); + }); + + it('should map every field of the cache setting to the manifest', () => { + const [cache] = strategy.transformToManifest([ + { + name: 'my-cache', + stale: true, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'br-east-1' }, + methods: { post: true, options: true }, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 86400 }, + cacheByCookie: { option: 'allowlist', list: ['session'] }, + cacheByQueryString: { option: 'denylist', list: ['utm'] }, + }, + ]); + + expect(cache).toEqual({ + name: 'my-cache', + browser_cache: { behavior: 'override', max_age: 7200 }, + modules: { + cache: { + behavior: 'override', + max_age: 86400, + stale_cache: { enabled: true }, + large_file_cache: { enabled: false, offset: 1024 }, + tiered_cache: { enabled: true, topology: 'br-east-1' }, + }, + application_accelerator: { + cache_vary_by_method: ['post', 'options'], + cache_vary_by_querystring: { behavior: 'denylist', fields: ['utm'], sort_enabled: true }, + cache_vary_by_cookies: { behavior: 'allowlist', cookie_names: ['session'] }, + cache_vary_by_devices: { behavior: 'ignore', device_group: [] }, + }, + }, + }); + }); + + it('should evaluate a mathematical expression as the max age', () => { + const [cache] = strategy.transformToManifest([ + { name: 'my-cache', browser: { maxAgeSeconds: '60 * 60' }, edge: { maxAgeSeconds: '60 * 60 * 24 * 7' } }, + ]); + + expect(cache.browser_cache.max_age).toBe(3600); + expect(cache.modules.cache.max_age).toBe(604800); + }); + + it('should accept the limits of the max age and throw out of them (v6 API: 0 to 31536000)', () => { + const withMaxAge = (browser: number | string, edge: number | string) => + strategy.transformToManifest([ + { name: 'my-cache', browser: { maxAgeSeconds: browser }, edge: { maxAgeSeconds: edge } }, + ]); + + expect(() => withMaxAge(0, 31536000)).not.toThrow(); + expect(() => withMaxAge('60 * 60 * 24 * 365', 10)).not.toThrow(); + expect(() => withMaxAge('60 * 60 * 24 * 366', 10)).toThrow( + 'Cache "my-cache" has browser.maxAgeSeconds "60 * 60 * 24 * 366" which is not a number of seconds between 0 and 31536000.', + ); + expect(() => withMaxAge(10, 31536001)).toThrow('edge.maxAgeSeconds'); + expect(() => withMaxAge(-1, 10)).toThrow('browser.maxAgeSeconds'); + expect(() => withMaxAge('1 / 0', 10)).toThrow('which is not a number of seconds'); + }); + + it('should throw when the max age is not a mathematical expression', () => { + expect(() => + strategy.transformToManifest([{ name: 'my-cache', browser: { maxAgeSeconds: 'process.exit()' } }]), + ).toThrow('Expression is not purely mathematical: process.exit()'); + }); + + it('should leave the topology out when the tiered cache is not enabled', () => { + const [cache] = strategy.transformToManifest([ + { name: 'my-cache', tieredCache: { enabled: false, topology: 'us-east-1' } }, + ]); + + expect(cache.modules.cache.tiered_cache).toEqual({ enabled: false }); + }); + }); + + describe('transformToConfig', () => { + it('should return an empty array when there is nothing to convert', () => { + expect(strategy.transformToConfig([])).toEqual([]); + }); + + it('should round trip a cache setting through the manifest', () => { + const cache: AzionCache = { + name: 'my-cache', + stale: true, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 86400 }, + methods: { post: true, options: false }, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'allowlist', list: ['q'] }, + cacheByCookie: { option: 'denylist', list: ['c'] }, + }; + + expect(strategy.transformToConfig(strategy.transformToManifest([cache]))).toEqual([cache]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts new file mode 100644 index 00000000..1975b1d7 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/cacheProcessConfigStrategy.ts @@ -0,0 +1,178 @@ +import { all, create } from 'mathjs'; +import type { AzionCache } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +const math = create(all); + +const MAX_AGE_SECONDS = 31536000; + +/** + * CacheProcessConfigStrategy V6 + * @class CacheProcessConfigStrategy + * @description This class is implementation of the Cache ProcessConfig Strategy for API V6. + */ +class CacheProcessConfigStrategy extends ProcessConfigStrategy { + // Helper function to safely evaluate mathematical expressions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private evaluateMathExpression = (expression: any) => { + if (typeof expression === 'number') { + return expression; + } + if (/^[0-9+\-*/.() ]+$/.test(expression)) { + return math.evaluate(expression); + } + throw new Error(`Expression is not purely mathematical: ${expression}`); + }; + + // The v6 API accepts a max age from 0 to 1 year, and an expression is only evaluated here + private evaluateMaxAge = (expression: unknown, field: string, cacheName: string) => { + const seconds = this.evaluateMathExpression(expression); + if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0 || seconds > MAX_AGE_SECONDS) { + throw new Error( + `Cache "${cacheName}" has ${field} "${String(expression)}" which is not a number of seconds between 0 and ${MAX_AGE_SECONDS}.`, + ); + } + return seconds; + }; + + /** + * Transform azion.config cache settings to V6 manifest format + */ + transformToManifest(applicationCache: AzionCache[]) { + if (!Array.isArray(applicationCache) || applicationCache.length === 0) { + return []; + } + + return applicationCache.map((cache) => { + const maxAgeSecondsBrowser = cache?.browser + ? this.evaluateMaxAge(cache.browser.maxAgeSeconds, 'browser.maxAgeSeconds', cache.name) + : 0; + const maxAgeSecondsEdge = cache?.edge + ? this.evaluateMaxAge(cache.edge.maxAgeSeconds, 'edge.maxAgeSeconds', cache.name) + : 60; + + // Build cache_vary_by_method array based on methods configuration + const cacheVaryByMethod: string[] = []; + if (cache?.methods?.post) cacheVaryByMethod.push('post'); + if (cache?.methods?.options) cacheVaryByMethod.push('options'); + + // Build cache_vary_by_querystring object + const cacheVaryByQuerystring = { + behavior: cache?.cacheByQueryString?.option || 'ignore', + fields: cache?.cacheByQueryString?.list || [], + sort_enabled: cache?.queryStringSort || false, + }; + + // Build cache_vary_by_cookies object + const cacheVaryByCookies = { + behavior: cache?.cacheByCookie?.option || 'ignore', + cookie_names: cache?.cacheByCookie?.list || [], + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const cachePayload: any = { + name: cache.name, + browser_cache: { + behavior: cache?.browser ? 'override' : 'honor', + max_age: maxAgeSecondsBrowser, + }, + modules: { + cache: { + behavior: cache?.edge ? 'override' : 'honor', + max_age: maxAgeSecondsEdge, + stale_cache: { + enabled: cache?.stale || false, + }, + large_file_cache: { + enabled: false, // Default for now, could be extended later + offset: 1024, // Default offset + }, + tiered_cache: { + enabled: cache?.tieredCache?.enabled || false, + }, + }, + application_accelerator: { + cache_vary_by_method: cacheVaryByMethod, + cache_vary_by_querystring: cacheVaryByQuerystring, + cache_vary_by_cookies: cacheVaryByCookies, + cache_vary_by_devices: { + behavior: 'ignore', // Default behavior + device_group: [], + }, + }, + }, + }; + + if (cache?.tieredCache?.enabled === true) { + cachePayload.modules.cache.tiered_cache.topology = cache.tieredCache.topology; + } + + return cachePayload; + }); + } + + /** + * Transform V6 manifest format back to azion.config cache settings + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(cacheSettings: any[]) { + if (!Array.isArray(cacheSettings) || cacheSettings.length === 0) { + return []; + } + + return cacheSettings.map((cache) => { + const maxAgeSecondsBrowser = cache.browser_cache?.max_age + ? this.evaluateMathExpression(cache.browser_cache.max_age) + : 0; + const maxAgeSecondsEdge = cache.modules?.cache?.max_age + ? this.evaluateMathExpression(cache.modules.cache.max_age) + : 60; + + const cacheSetting: AzionCache = { + name: cache.name, + stale: cache.modules?.cache?.stale_cache?.enabled || false, + browser: { + maxAgeSeconds: maxAgeSecondsBrowser, + }, + edge: { + maxAgeSeconds: maxAgeSecondsEdge, + }, + methods: { + post: cache.modules?.application_accelerator?.cache_vary_by_method?.includes('post') || false, + options: cache.modules?.application_accelerator?.cache_vary_by_method?.includes('options') || false, + }, + queryStringSort: cache.modules?.application_accelerator?.cache_vary_by_querystring?.sort_enabled || false, + tieredCache: { + enabled: cache.modules?.cache?.tiered_cache?.enabled || false, + }, + }; + + if (cacheSetting.tieredCache && cacheSetting.tieredCache.enabled === true) { + cacheSetting.tieredCache.topology = cache.modules?.cache?.tiered_cache?.topology; + } + + // Handle cache by query string + if (cache.modules?.application_accelerator?.cache_vary_by_querystring) { + const queryStringConfig = cache.modules.application_accelerator.cache_vary_by_querystring; + cacheSetting.cacheByQueryString = { + option: queryStringConfig.behavior, + list: queryStringConfig.fields || [], + }; + } + + // Handle cache by cookie + if (cache.modules?.application_accelerator?.cache_vary_by_cookies) { + const cookieConfig = cache.modules.application_accelerator.cache_vary_by_cookies; + cacheSetting.cacheByCookie = { + option: cookieConfig.behavior, + list: cookieConfig.cookie_names || [], + }; + } + + return cacheSetting; + }); + } +} + +export default CacheProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/schemas/applications/index.ts b/packages/config/src/versions/v6/schemas/applications/index.ts index 6e211785..5043d090 100644 --- a/packages/config/src/versions/v6/schemas/applications/index.ts +++ b/packages/config/src/versions/v6/schemas/applications/index.ts @@ -136,7 +136,8 @@ const createRuleSchema = (isRequestPhase = false) => ({ * Schema of the v6 applications. * Based on v4, checked against the requests of the v6 API: `name` has at most 100 characters in an application * (`ApplicationRequest`) and in a rule (`RequestPhaseRuleRequest`, `ResponsePhaseRuleRequest`). - * TODO: add the remaining resources of an application (cache settings, device groups). + * Cache: `maxAgeSeconds` is between 0 and 31536000 (1 year) and `tieredCache.topology` is not nullable, as in `CacheSettingRequest`. + * TODO: add the remaining resources of an application (device groups). */ const applicationsSchema = { type: 'array', @@ -179,6 +180,210 @@ const applicationsSchema = { default: false, errorMessage: "The 'imageProcessorEnabled' field must be a boolean", }, + cache: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The 'name' field must be a string with 1 to 250 characters", + }, + stale: { + type: 'boolean', + errorMessage: "The 'stale' field must be a boolean.", + }, + queryStringSort: { + type: 'boolean', + errorMessage: "The 'queryStringSort' field must be a boolean.", + }, + tieredCache: { + type: 'object', + properties: { + enabled: { + type: 'boolean', + default: false, + errorMessage: "The 'enabled' field must be a boolean.", + }, + topology: { + type: 'string', + enum: ['nearest-region', 'us-east-1', 'br-east-1'], + default: 'nearest-region', + errorMessage: "The 'topology' field must be one of 'nearest-region', 'br-east-1' or 'us-east-1'.", + }, + }, + required: ['enabled'], + if: { + properties: { enabled: { const: true } }, + }, + then: { + required: ['enabled', 'topology'], + errorMessage: { + required: "When 'enabled' is true, 'topology' is required in the 'tiered_cache' object.", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'tiered_cache' object.", + }, + }, + methods: { + type: 'object', + properties: { + post: { + type: 'boolean', + errorMessage: "The 'post' field must be a boolean.", + }, + options: { + type: 'boolean', + errorMessage: "The 'options' field must be a boolean.", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'methods' object.", + }, + }, + browser: { + type: 'object', + properties: { + maxAgeSeconds: { + oneOf: [ + { + type: 'number', + minimum: 0, + maximum: 31536000, + errorMessage: + "The 'maxAgeSeconds' field must be a number between 0 and 31536000 or a valid mathematical expression.", + }, + { + type: 'string', + pattern: '^[0-9+*/.() -]+$', + errorMessage: "The 'maxAgeSeconds' field must be a valid mathematical expression.", + }, + ], + }, + }, + required: ['maxAgeSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'browser' object.", + required: "The 'maxAgeSeconds' field is required in the 'browser' object.", + }, + }, + edge: { + type: 'object', + properties: { + maxAgeSeconds: { + oneOf: [ + { + type: 'number', + minimum: 0, + maximum: 31536000, + errorMessage: + "The 'maxAgeSeconds' field must be a number between 0 and 31536000 or a valid mathematical expression.", + }, + { + type: 'string', + pattern: '^[0-9+*/.() -]+$', + errorMessage: "The 'maxAgeSeconds' field must be a valid mathematical expression.", + }, + ], + }, + }, + required: ['maxAgeSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'edge' object.", + required: "The 'maxAgeSeconds' field is required in the 'edge' object.", + }, + }, + cacheByCookie: { + type: 'object', + properties: { + option: { + type: 'string', + enum: ['ignore', 'all', 'allowlist', 'denylist'], + errorMessage: "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + }, + list: { + type: 'array', + items: { + type: 'string', + errorMessage: "Each item in 'list' must be a string.", + }, + errorMessage: { + type: "The 'list' field must be an array of strings.", + }, + }, + }, + required: ['option'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'cacheByCookie' object.", + required: "The 'option' field is required in the 'cacheByCookie' object.", + }, + if: { + properties: { + option: { enum: ['allowlist', 'denylist'] }, + }, + }, + then: { + required: ['list'], + errorMessage: { + required: "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + }, + }, + }, + cacheByQueryString: { + type: 'object', + properties: { + option: { + type: 'string', + enum: ['ignore', 'all', 'allowlist', 'denylist'], + errorMessage: "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + }, + list: { + type: 'array', + items: { + type: 'string', + errorMessage: "Each item in 'list' must be a string.", + }, + errorMessage: { + type: "The 'list' field must be an array of strings.", + }, + }, + }, + required: ['option'], + additionalProperties: false, + errorMessage: { + additionalProperties: "No additional properties are allowed in the 'cacheByQueryString' object.", + required: "The 'option' field is required in the 'cacheByQueryString' object.", + }, + if: { + properties: { + option: { enum: ['allowlist', 'denylist'] }, + }, + }, + then: { + required: ['list'], + errorMessage: { + required: "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + }, + }, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in cache item objects.', + required: "The 'name' field is required in each cache item.", + }, + }, + errorMessage: "The 'cache' field must be an array of cache setting items.", + }, rules: { type: 'object', properties: { diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 3c4024b4..9b0cb27c 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -1,5 +1,6 @@ import type { AzionBuild, + AzionCache, AzionFunction, AzionFunctionInstance, AzionRules, @@ -32,7 +33,7 @@ export type AzionFunctionV6 = AzionFunction; /** * Application of the Azion API v6. - * TODO: add the remaining resources of an application (cache settings, device groups). + * TODO: add the remaining resources of an application (device groups). */ export type AzionApplicationV6 = { /** Application name */ @@ -49,6 +50,8 @@ export type AzionApplicationV6 = { active?: boolean; /** Enable debug mode */ debug?: boolean; + /** Cache settings */ + cache?: AzionCache[]; /** Rules configuration */ rules?: AzionRules; /** Function instances */ diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 99fefd4d..c6d62558 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -687,3 +687,82 @@ describe('validateConfig (v6) storage and connectors', () => { }); }); }); + +describe('validateConfig (v6) application cache', () => { + const cache = (value: Record) => ({ + version: 6, + applications: [{ name: 'my-app', cache: [{ name: 'my-cache', ...value }] }], + }); + + it('accepts a complete cache setting', () => { + expect(() => + validateConfig( + cache({ + stale: true, + queryStringSort: true, + tieredCache: { enabled: true, topology: 'us-east-1' }, + methods: { post: true, options: false }, + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: '60 * 60 * 24' }, + cacheByCookie: { option: 'allowlist', list: ['session'] }, + cacheByQueryString: { option: 'denylist', list: ['utm'] }, + }), + ), + ).not.toThrow(); + expect(() => validateConfig(cache({}))).not.toThrow(); + }); + + it('requires the name and limits it to 250 characters', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', cache: [{ stale: true }] }] })).toThrow( + "The 'name' field is required in each cache item.", + ); + expect(() => validateConfig(cache({ name: 'a'.repeat(250) }))).not.toThrow(); + expect(() => validateConfig(cache({ name: 'a'.repeat(251) }))).toThrow( + "The 'name' field must be a string with 1 to 250 characters", + ); + }); + + it('limits a numeric max age to 0..31536000 (the v6 API limit) and accepts an expression', () => { + expect(() => + validateConfig(cache({ browser: { maxAgeSeconds: 0 }, edge: { maxAgeSeconds: 31536000 } })), + ).not.toThrow(); + expect(() => validateConfig(cache({ browser: { maxAgeSeconds: 31536001 } }))).toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: -1 } }))).toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: '60 * 60' } }))).not.toThrow(); + expect(() => validateConfig(cache({ edge: { maxAgeSeconds: 'abc' } }))).toThrow( + "The 'maxAgeSeconds' field must be a valid mathematical expression.", + ); + }); + + it('requires the topology when the tiered cache is enabled and does not accept null', () => { + expect(() => validateConfig(cache({ tieredCache: { enabled: true } }))).toThrow( + "When 'enabled' is true, 'topology' is required in the 'tiered_cache' object.", + ); + expect(() => validateConfig(cache({ tieredCache: { enabled: false } }))).not.toThrow(); + expect(() => validateConfig(cache({ tieredCache: { enabled: false, topology: null } }))).toThrow( + "The 'topology' field must be one of 'nearest-region', 'br-east-1' or 'us-east-1'.", + ); + expect(() => validateConfig(cache({ tieredCache: { enabled: true, topology: 'eu-west-1' } }))).toThrow(); + }); + + it('validates the cache by cookie and by query string', () => { + expect(() => validateConfig(cache({ cacheByCookie: { option: 'sometimes' } }))).toThrow( + "The 'option' field must be one of 'ignore', 'all', 'allowlist' or 'denylist'.", + ); + expect(() => validateConfig(cache({ cacheByQueryString: { list: ['q'] } }))).toThrow( + "The 'option' field is required in the 'cacheByQueryString' object.", + ); + expect(() => validateConfig(cache({ cacheByQueryString: { option: 'allowlist' } }))).toThrow( + "The 'list' field is required when 'option' is 'allowlist' or 'denylist'.", + ); + }); + + it('rejects unknown properties in a cache setting', () => { + expect(() => validateConfig(cache({ unknown: true }))).toThrow( + 'No additional properties are allowed in cache item objects.', + ); + expect(() => validateConfig(cache({ methods: { get: true } }))).toThrow( + "No additional properties are allowed in the 'methods' object.", + ); + }); +}); From 11429bc99cb08a6e4e5ed6cef7791880d0fe3dcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 09:04:48 -0300 Subject: [PATCH 11/29] feat(presets): add the v6 config to the opennextjs preset and the cache to the react one opennextjs: add the build, the storage, the storage connector, the function with its storage binding, the application with the cache and the rules, an environment, a deployment and the workload bound to them, as the v4 config has. react: add the cache settings of the application, which the v6 config supports now. Tests check that the storage, the connectors, the functions and the application of the opennextjs and react v6 manifests are the same as the ones of the v4 manifests. --- packages/presets/src/presets/configs.test.ts | 26 ++- .../src/presets/opennextjs/config.v6.ts | 184 ++++++++++++++++++ .../presets/src/presets/opennextjs/index.ts | 8 +- .../presets/src/presets/react/config.v6.ts | 12 +- 4 files changed, 224 insertions(+), 6 deletions(-) create mode 100644 packages/presets/src/presets/opennextjs/config.v6.ts diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 5e338ce9..0d3fb118 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -40,12 +40,13 @@ describe('preset configs by API version', () => { }); describe('v6', () => { - it('is declared by javascript and react only for now', () => { + it('is declared by javascript, opennextjs and react only for now', () => { const withV6 = presets .filter((preset) => preset.configs?.[6]) .map((preset) => preset.metadata.name) .sort(); - expect(withV6).toEqual(['javascript', 'react']); + expect(withV6).toEqual(['javascript', 'opennextjs', 'react']); + expect(getPresetApiVersions(byName('opennextjs'))).toEqual([3, 4, 6]); expect(getPresetApiVersions(byName('javascript'))).toEqual([3, 4, 6]); expect(getPresetApiVersions(byName('react'))).toEqual([3, 4, 6]); expect(() => resolvePresetConfig(byName('vue'), 6)).toThrow('does not support config version 6'); @@ -70,7 +71,7 @@ describe('preset configs by API version', () => { expect(v6.applications[0].modules.functions.enabled).toBe(true); }); - it('react: validates and has the same storage, connectors and rules in the manifest as the v4 config', () => { + it('react: validates and has the same storage, connectors and application in the manifest as the v4 config', () => { const config = resolvePresetConfig(byName('react'), 6); expect(() => validateConfig(config)).not.toThrow(); @@ -80,12 +81,29 @@ describe('preset configs by API version', () => { expect(v6.version).toBe(6); expect(v6.storage).toEqual(v4.storage); expect(v6.connectors).toEqual(v4.connectors); - expect(v6.applications[0].rules).toEqual(v4.applications[0].rules); + expect(v6.applications).toEqual(v4.applications); + expect(v6.applications[0].cache_settings).toHaveLength(1); // the rules deliver the static assets from the storage connector expect(JSON.stringify(v6.applications[0].rules)).toContain('"set_connector"'); expect(v6.connectors.map((connector: { name: string }) => connector.name)).toEqual(['$CONNECTOR_NAME']); }); + it('opennextjs: validates and has the same storage, connectors, functions and application in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('opennextjs'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('opennextjs'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(v4.connectors); + // the function keeps the storage binding + expect(v6.functions).toEqual(v4.functions); + expect(v6.functions[0].bindings).toEqual({ storage: { bucket: '$BUCKET_NAME', prefix: '$BUCKET_PREFIX' } }); + expect(v6.applications).toEqual(v4.applications); + }); + it('javascript: binds the workload to an environment and a deployment declared in the config', () => { const manifest = processConfig(resolvePresetConfig(byName('javascript'), 6)); diff --git a/packages/presets/src/presets/opennextjs/config.v6.ts b/packages/presets/src/presets/opennextjs/config.v6.ts new file mode 100644 index 00000000..61c231f3 --- /dev/null +++ b/packages/presets/src/presets/opennextjs/config.v6.ts @@ -0,0 +1,184 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: '.open-next/worker.js', + polyfills: true, + bundler: 'esbuild', + preset: 'opennextjs', + } as AzionBuild, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_write', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/worker.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Set storage origin for all requests _next_static and set cache policy', + description: 'Serve Next.js static assets through edge connector and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_next/static/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Serve static assets through edge connector and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/opennextjs/index.ts b/packages/presets/src/presets/opennextjs/index.ts index b1f961cf..650b2616 100644 --- a/packages/presets/src/presets/opennextjs/index.ts +++ b/packages/presets/src/presets/opennextjs/index.ts @@ -1,7 +1,13 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; import prebuild from './prebuild'; -export const opennextjs: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, prebuild }; +export const opennextjs: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + prebuild, +}; diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts index 6dd5b1a5..2444fb32 100644 --- a/packages/presets/src/presets/react/config.v6.ts +++ b/packages/presets/src/presets/react/config.v6.ts @@ -1,7 +1,6 @@ import type { AzionConfigV6 } from '@aziontech/config'; import { createSPARules } from '@aziontech/config/rules'; -// TODO: add the cache settings of the application once the v6 config has them const config: AzionConfigV6 = { version: 6, build: { @@ -29,6 +28,17 @@ const config: AzionConfigV6 = { applications: [ { name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], rules: createSPARules({ connector: '$CONNECTOR_NAME', application: '$APPLICATION_NAME', From 9c3873471dde9a795c38ec467e85fb9c239f7301 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 10:15:30 -0300 Subject: [PATCH 12/29] feat(config): require the environment and deployment policies in API v6 The creation of an environment (EnvironmentCreateRequest) requires deployment_policy and the creation of a deployment (DeploymentCreateRequest) requires binding_policy. Earlier these were checked against the replacement requests (EnvironmentRequest and DeploymentRequest), where they are optional. The config now requires deploymentPolicy on each environment and bindingPolicy on each deployment, with no default: the API does not accept changing the deployment policy of an environment afterwards. The presets declare single_version and FLEXIBLE. --- .../deploymentProcessConfigStrategy.test.ts | 21 +++++++++-- .../deploymentProcessConfigStrategy.ts | 7 ++-- .../environmentProcessConfigStrategy.test.ts | 20 +++++++++-- .../environmentProcessConfigStrategy.ts | 9 ++--- .../workloadProcessConfigStrategy.test.ts | 4 +-- .../versions/v6/schemas/deployments/index.ts | 10 ++++-- .../versions/v6/schemas/environments/index.ts | 10 ++++-- packages/config/src/versions/v6/types.ts | 6 ++-- .../versions/v6/validateConfig/index.test.ts | 36 ++++++++++++++----- packages/presets/src/presets/configs.test.ts | 6 ++++ .../src/presets/javascript/config.v6.ts | 2 ++ .../src/presets/opennextjs/config.v6.ts | 2 ++ .../presets/src/presets/react/config.v6.ts | 2 ++ 13 files changed, 105 insertions(+), 30 deletions(-) diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts index d024eae7..a2f53993 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts @@ -13,8 +13,13 @@ describe('DeploymentProcessConfigStrategy (v6)', () => { expect(strategy.transformToManifest({ version: 6 })).toEqual([]); }); - it('should apply the defaults the API requires to a minimal deployment', () => { - expect(strategy.transformToManifest({ version: 6, deployments: [{ name: 'default-deployment' }] })).toEqual([ + it('should write the binding policy and apply the defaults the API requires to the other fields', () => { + expect( + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + }), + ).toEqual([ { name: 'default-deployment', description: null, @@ -24,6 +29,18 @@ describe('DeploymentProcessConfigStrategy (v6)', () => { ]); }); + it('should write the binding policy that the config declares', () => { + const policies = (['STRICT', 'FLEXIBLE'] as const).map( + (bindingPolicy) => + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy }], + })?.[0].binding_policy, + ); + + expect(policies).toEqual(['STRICT', 'FLEXIBLE']); + }); + it('should map every field of the deployment to the manifest', () => { const [deployment] = strategy.transformToManifest({ version: 6, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts index 1f467e5f..9670622c 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts @@ -5,8 +5,9 @@ import type { AzionConfigV6, AzionDeploymentV6 } from '../../types'; * DeploymentProcessConfigStrategy * @class DeploymentProcessConfigStrategy * @description Converts the v6 deployments between the config and the manifest. - * The API requires `binding_policy`, `description` and `strategy_defaults`, so the manifest defaults them to a flexible - * binding, no description and no skew protection. + * The creation of a deployment requires `binding_policy`, which the config must declare. The replacement of a + * deployment also requires `description` and `strategy_defaults`, so the manifest defaults them to no description and + * no skew protection. * The application a deployment serves is not part of it: the Azion CLI sets it when it creates a release. */ class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { @@ -21,7 +22,7 @@ class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { expect(strategy.transformToManifest({ version: 6 })).toEqual([]); }); - it('should apply the defaults the API requires to a minimal environment', () => { - expect(strategy.transformToManifest({ version: 6, environments: [{ name: 'production' }] })).toEqual([ + it('should write the deployment policy and apply the defaults the API requires to the other fields', () => { + expect( + strategy.transformToManifest({ + version: 6, + environments: [{ name: 'production', deploymentPolicy: 'single_version' }], + }), + ).toEqual([ { name: 'production', description: null, @@ -22,10 +27,21 @@ describe('EnvironmentProcessConfigStrategy (v6)', () => { robots_policy: 'respect_origin', protection: {}, branch_tracking: null, + deployment_policy: 'single_version', }, ]); }); + it('should write the deployment policy that the config declares', () => { + const policies = (['single_version', 'versioned_urls'] as const).map( + (deploymentPolicy) => + strategy.transformToManifest({ version: 6, environments: [{ name: 'production', deploymentPolicy }] })?.[0] + .deployment_policy, + ); + + expect(policies).toEqual(['single_version', 'versioned_urls']); + }); + it('should map every field of the environment to the manifest', () => { const [environment] = strategy.transformToManifest({ version: 6, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts index c5995351..b584e3be 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/environmentProcessConfigStrategy.ts @@ -5,9 +5,10 @@ import type { AzionConfigV6, AzionEnvironmentV6 } from '../../types'; * EnvironmentProcessConfigStrategy * @class EnvironmentProcessConfigStrategy * @description Converts the v6 environments between the config and the manifest. - * The API requires `log_verbosity`, `robots_policy`, `protection`, `branch_tracking` and `description`, so the manifest - * defaults them to the least intrusive values: normal logs, the robots policy of the origin, no protection, no branch - * tracking and no description. + * The creation of an environment requires `deployment_policy`, which the config must declare because the API does not + * accept changing it afterwards. The replacement of an environment also requires `log_verbosity`, `robots_policy`, + * `protection`, `branch_tracking` and `description`, so the manifest defaults them to the least intrusive values: + * normal logs, the robots policy of the origin, no protection, no branch tracking and no description. */ class EnvironmentProcessConfigStrategy extends ProcessConfigStrategy { transformToManifest(config: AzionConfigV6) { @@ -47,7 +48,7 @@ class EnvironmentProcessConfigStrategy extends ProcessConfigStrategy { const declared: AzionConfigV6 = { version: 6, - environments: [{ name: 'production' }], - deployments: [{ name: 'default-deployment' }], + environments: [{ name: 'production', deploymentPolicy: 'single_version' }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], }; beforeEach(() => { diff --git a/packages/config/src/versions/v6/schemas/deployments/index.ts b/packages/config/src/versions/v6/schemas/deployments/index.ts index 78e1b67c..555530f0 100644 --- a/packages/config/src/versions/v6/schemas/deployments/index.ts +++ b/packages/config/src/versions/v6/schemas/deployments/index.ts @@ -1,7 +1,8 @@ import { DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES } from '../../constants'; /** - * Schema of the v6 deployments, from `DeploymentRequest` of the v6 API. + * Schema of the v6 deployments, from `DeploymentCreateRequest` and `DeploymentRequest` of the v6 API. + * `bindingPolicy` is required, as in the creation of a deployment. */ const deploymentsSchema = { type: 'array', @@ -51,11 +52,14 @@ const deploymentsSchema = { }, }, }, - required: ['name'], + required: ['name', 'bindingPolicy'], additionalProperties: false, errorMessage: { additionalProperties: 'No additional properties are allowed in deployment objects', - required: { name: "The 'name' field is required in each deployment" }, + required: { + name: "The 'name' field is required in each deployment", + bindingPolicy: "The 'bindingPolicy' field is required in each deployment", + }, }, }, errorMessage: "The 'deployments' field must be an array of deployment objects", diff --git a/packages/config/src/versions/v6/schemas/environments/index.ts b/packages/config/src/versions/v6/schemas/environments/index.ts index c456a681..15fe9b3f 100644 --- a/packages/config/src/versions/v6/schemas/environments/index.ts +++ b/packages/config/src/versions/v6/schemas/environments/index.ts @@ -6,7 +6,8 @@ import { } from '../../constants'; /** - * Schema of the v6 environments, from `EnvironmentRequest` of the v6 API. + * Schema of the v6 environments, from `EnvironmentCreateRequest` and `EnvironmentRequest` of the v6 API. + * `deploymentPolicy` is required, as in the creation of an environment, and the API does not accept changing it later. */ const environmentsSchema = { type: 'array', @@ -100,11 +101,14 @@ const environmentsSchema = { errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, }, }, - required: ['name'], + required: ['name', 'deploymentPolicy'], additionalProperties: false, errorMessage: { additionalProperties: 'No additional properties are allowed in environment objects', - required: { name: "The 'name' field is required in each environment" }, + required: { + name: "The 'name' field is required in each environment", + deploymentPolicy: "The 'deploymentPolicy' field is required in each environment", + }, }, }, errorMessage: "The 'environments' field must be an array of environment objects", diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 9b0cb27c..442e1383 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -123,7 +123,8 @@ export type AzionEnvironmentV6 = { mode: (typeof ENVIRONMENT_BRANCH_TRACKING_MODES)[number]; branchMatch: string; } | null; - deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; + /** How the releases of the environment are served. Required by the API, and it cannot be changed afterwards */ + deploymentPolicy: (typeof DEPLOYMENT_POLICIES)[number]; }; /** @@ -133,7 +134,8 @@ export type AzionDeploymentV6 = { /** Deployment name */ name: string; description?: string | null; - bindingPolicy?: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; + /** Whether a release can swap the resources of the deployment. Required by the API */ + bindingPolicy: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; strategyDefaults?: { skewProtection?: { enabled: boolean; defaultTtlSeconds: number }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index c6d62558..e52c4ddb 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -290,11 +290,11 @@ describe('validateConfig (v6) workloads, environments and deployments', () => { }); const environment = (extra: Record = {}) => ({ version: 6, - environments: [{ name: 'production', ...extra }], + environments: [{ name: 'production', deploymentPolicy: 'single_version', ...extra }], }); const deployment = (extra: Record = {}) => ({ version: 6, - deployments: [{ name: 'default-deployment', ...extra }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE', ...extra }], }); describe('workloads', () => { @@ -407,13 +407,23 @@ describe('validateConfig (v6) workloads, environments and deployments', () => { }); it('limits the name to 3-255 characters and requires it', () => { - expect(() => validateConfig({ version: 6, environments: [{ description: 'x' }] })).toThrow( - "The 'name' field is required in each environment", - ); - expect(() => validateConfig({ version: 6, environments: [{ name: 'ab' }] })).toThrow( - "The 'name' field must be a string between 3 and 255 characters", + expect(() => + validateConfig({ version: 6, environments: [{ description: 'x', deploymentPolicy: 'single_version' }] }), + ).toThrow("The 'name' field is required in each environment"); + expect(() => + validateConfig({ version: 6, environments: [{ name: 'ab', deploymentPolicy: 'single_version' }] }), + ).toThrow("The 'name' field must be a string between 3 and 255 characters"); + expect(() => + validateConfig({ version: 6, environments: [{ name: 'a'.repeat(256), deploymentPolicy: 'single_version' }] }), + ).toThrow(); + }); + + it('requires the deploymentPolicy (the API requires it and does not accept changing it later)', () => { + expect(() => validateConfig({ version: 6, environments: [{ name: 'production' }] })).toThrow( + "The 'deploymentPolicy' field is required in each environment", ); - expect(() => validateConfig({ version: 6, environments: [{ name: 'a'.repeat(256) }] })).toThrow(); + expect(() => validateConfig(environment({ deploymentPolicy: 'single_version' }))).not.toThrow(); + expect(() => validateConfig(environment({ deploymentPolicy: 'versioned_urls' }))).not.toThrow(); }); it('rejects values out of the enums', () => { @@ -460,11 +470,19 @@ describe('validateConfig (v6) workloads, environments and deployments', () => { expect(() => validateConfig({ version: 6, deployments: [{ bindingPolicy: 'STRICT' }] })).toThrow( "The 'name' field is required in each deployment", ); - expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab' }] })).toThrow( + expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab', bindingPolicy: 'FLEXIBLE' }] })).toThrow( "The 'name' field must be a string between 3 and 255 characters", ); }); + it('requires the bindingPolicy (the creation of a deployment requires it)', () => { + expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( + "The 'bindingPolicy' field is required in each deployment", + ); + expect(() => validateConfig(deployment({ bindingPolicy: 'STRICT' }))).not.toThrow(); + expect(() => validateConfig(deployment({ bindingPolicy: 'FLEXIBLE' }))).not.toThrow(); + }); + it('rejects values out of the enums and invalid skew protection', () => { expect(() => validateConfig(deployment({ bindingPolicy: 'strict' }))).toThrow( "The 'bindingPolicy' field must be one of: STRICT, FLEXIBLE", diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 0d3fb118..1292fbc0 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -110,7 +110,13 @@ describe('preset configs by API version', () => { expect(manifest.environments.map((environment: { name: string }) => environment.name)).toEqual([ '$ENVIRONMENT_NAME', ]); + expect( + manifest.environments.map((environment: { deployment_policy: string }) => environment.deployment_policy), + ).toEqual(['single_version']); expect(manifest.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); + expect(manifest.deployments.map((deployment: { binding_policy: string }) => deployment.binding_policy)).toEqual([ + 'FLEXIBLE', + ]); expect(manifest.workloads).toHaveLength(1); expect(manifest.workloads[0]).toEqual( expect.objectContaining({ name: '$WORKLOAD_NAME', active: true, infrastructure: 1 }), diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts index ef37cbb6..87fbc714 100644 --- a/packages/presets/src/presets/javascript/config.v6.ts +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -53,12 +53,14 @@ const config: AzionConfigV6 = { environments: [ { name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', }, ], // the application a deployment serves is set by the Azion CLI when it creates the release deployments: [ { name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', }, ], workloads: [ diff --git a/packages/presets/src/presets/opennextjs/config.v6.ts b/packages/presets/src/presets/opennextjs/config.v6.ts index 61c231f3..e7e60d94 100644 --- a/packages/presets/src/presets/opennextjs/config.v6.ts +++ b/packages/presets/src/presets/opennextjs/config.v6.ts @@ -158,12 +158,14 @@ const config: AzionConfigV6 = { environments: [ { name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', }, ], // the application a deployment serves is set by the Azion CLI when it creates the release deployments: [ { name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', }, ], workloads: [ diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts index 2444fb32..041bdbd9 100644 --- a/packages/presets/src/presets/react/config.v6.ts +++ b/packages/presets/src/presets/react/config.v6.ts @@ -48,12 +48,14 @@ const config: AzionConfigV6 = { environments: [ { name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', }, ], // the application a deployment serves is set by the Azion CLI when it creates the release deployments: [ { name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', }, ], workloads: [ From 90b2e7a8a4151c8e1e738f2cb09918e56ce827de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 10:15:51 -0300 Subject: [PATCH 13/29] feat(config): add firewall, waf, network list and custom pages to API v6 Add the v6 schemas, types and process strategies, based on v4 and checked against the v6 API requests. Firewall: names have at most 250 characters (rules, 100), the criterion argument is required unless the operator is exists or does_not_exist, a rule can have up to 10 criteria, bypass is a behavior without arguments, the mode of set_waf is logging or blocking, the rate limit and the status code of a custom response are integers, and the function instances accept active. The strategy writes active and debugRules, reads back the keys it writes and validates that the network list of is_in_list and is_not_in_list is declared. WAF: the request has no id nor productVersion, the engine settings and the sensitivity of a threshold are optional and active is new. Network list: each item has 1 to 250 characters, and the items of asn and countries follow the formats the API documents. The manifest reads the network_list key back, which the v4 strategy did not. Custom pages: at most 23 pages, the connector id is between 1 and 2147483647 and the uri has no pattern. The connector of a page must be declared. --- packages/config/src/versions/registry.test.ts | 18 +- packages/config/src/versions/v6/constants.ts | 90 ++++ .../customPagesProcessConfigStrategy.test.ts | 165 ++++++ .../customPagesProcessConfigStrategy.ts | 101 ++++ .../firewallProcessConfigStrategy.test.ts | 337 ++++++++++++ .../secure/firewallProcessConfigStrategy.ts | 264 ++++++++++ .../networkListProcessConfigStrategy.test.ts | 56 ++ .../networkListProcessConfigStrategy.ts | 49 ++ .../secure/wafProcessConfigStrategy.test.ts | 105 ++++ .../secure/wafProcessConfigStrategy.ts | 70 +++ .../src/versions/v6/processStrategy/index.ts | 8 + .../versions/v6/schemas/customPages/index.ts | 111 ++++ .../v6/schemas/firewall/behaviors/index.ts | 208 ++++++++ .../firewall/functionsInstances/index.ts | 36 ++ .../src/versions/v6/schemas/firewall/index.ts | 183 +++++++ .../versions/v6/schemas/networkList/index.ts | 85 +++ .../config/src/versions/v6/schemas/schema.ts | 12 +- .../src/versions/v6/schemas/waf/index.ts | 110 ++++ packages/config/src/versions/v6/types.ts | 150 ++++++ .../versions/v6/validateConfig/index.test.ts | 494 +++++++++++++++++- 20 files changed, 2646 insertions(+), 6 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/customPages/index.ts create mode 100644 packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts create mode 100644 packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts create mode 100644 packages/config/src/versions/v6/schemas/firewall/index.ts create mode 100644 packages/config/src/versions/v6/schemas/networkList/index.ts create mode 100644 packages/config/src/versions/v6/schemas/waf/index.ts diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index fd3bf7d7..081384f5 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -139,7 +139,7 @@ describe('v6 support', () => { it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { expect(() => validateConfig(v6Config)).not.toThrow(); - expect(() => validateConfig({ version: 6, firewall: [] })).toThrow(); + expect(() => validateConfig({ version: 6, purge: [] })).toThrow(); }); it('does not accept v6 on the v4 schema nor the other way around', () => { @@ -153,6 +153,8 @@ describe('v6 support', () => { build: v6Config.build, functions: [], applications: [], + firewall: [], + custom_pages: [], environments: [], deployments: [], workloads: [], @@ -176,12 +178,24 @@ describe('v6 support', () => { ]); }); + it('processes the v6 network lists into the network_list key of the manifest', () => { + const manifest = processConfig({ + ...v6Config, + networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }], + }); + + expect(manifest.network_list).toEqual([ + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'], active: true }, + ]); + }); + it('forwards the version to manifest helpers', () => { expect(() => validateManifest({}, undefined, { version: 6 })).not.toThrow(); expect(() => convertJsonConfigToObject('{', { version: 6 })).toThrow('Invalid JSON configuration.'); - expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6, applications: [] }); + expect(convertJsonConfigToObject('{}', { version: 6 })).toEqual({ version: 6, firewall: [], applications: [] }); expect(convertJsonConfigToObject(JSON.stringify(processConfig(v6Config)), { version: 6 })).toEqual({ ...v6Config, + firewall: [], applications: [], }); }); diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts index b8e28477..7c25f8f7 100644 --- a/packages/config/src/versions/v6/constants.ts +++ b/packages/config/src/versions/v6/constants.ts @@ -129,3 +129,93 @@ export const CONNECTOR_SERVER_ROLES = ['primary', 'backup'] as const; export const CONNECTOR_HMAC_TYPE = ['aws4_hmac_sha256'] as const; export const CONNECTOR_LIVE_INGEST_REGIONS = ['us-east-1', 'us-east-2', 'br-east-1', 'br-east-2', 'br-east-3'] as const; + +export const FIREWALL_VARIABLES = [ + 'header_accept', + 'header_accept_encoding', + 'header_accept_language', + 'header_cookie', + 'header_origin', + 'header_referer', + 'header_user_agent', + 'host', + 'network', + 'request_args', + 'request_method', + 'request_uri', + 'scheme', + 'client_certificate_validation', + 'ssl_verification_status', +] as const; + +export const FIREWALL_RULE_OPERATORS = [ + 'is_equal', + 'is_not_equal', + 'starts_with', + 'does_not_start_with', + 'matches', + 'does_not_match', + 'exists', + 'does_not_exist', + 'is_in_list', + 'is_not_in_list', +] as const; + +export const FIREWALL_RULE_CONDITIONAL = ['if', 'and', 'or'] as const; + +export const FIREWALL_NO_ARGS_BEHAVIORS = ['deny', 'drop', 'bypass'] as const; + +export const FIREWALL_RATE_LIMIT_TYPES = ['second', 'minute'] as const; + +export const FIREWALL_RATE_LIMIT_BY = ['client_ip', 'global'] as const; + +export const FIREWALL_WAF_MODES = ['logging', 'blocking'] as const; + +export const WAF_ENGINE_VERSIONS = ['2021-Q3'] as const; + +export const WAF_ENGINE_TYPES = ['score'] as const; + +export const WAF_RULESETS = [1] as const; + +export const WAF_THREAT_TYPES = [ + 'cross_site_scripting', + 'directory_traversal', + 'evading_tricks', + 'file_upload', + 'identified_attack', + 'remote_file_inclusion', + 'sql_injection', + 'unwanted_access', +] as const; + +export const WAF_SENSITIVITY = ['highest', 'high', 'medium', 'low', 'lowest'] as const; + +export const NETWORK_LIST_TYPES = ['ip_cidr', 'asn', 'countries'] as const; + +export const CUSTOM_PAGE_ERROR_CODES = [ + 'default', + '400', + '401', + '403', + '404', + '405', + '406', + '408', + '409', + '410', + '411', + '414', + '415', + '416', + '426', + '429', + '431', + '500', + '501', + '502', + '503', + '504', + '505', +] as const; + +export const CUSTOM_PAGE_TYPES = ['page_connector'] as const; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts new file mode 100644 index 00000000..7d594be5 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts @@ -0,0 +1,165 @@ +import type { AzionConfigV6, AzionCustomPageV6 } from '../../types'; +import CustomPagesProcessConfigStrategy from './customPagesProcessConfigStrategy'; + +describe('CustomPagesProcessConfigStrategy (v6)', () => { + let strategy: CustomPagesProcessConfigStrategy; + + const connectors: AzionConfigV6['connectors'] = [ + { name: 'my-connector', type: 'storage', attributes: { bucket: 'my-bucket' } }, + ]; + const withPages = (customPages: AzionCustomPageV6[], extra: Partial = {}): AzionConfigV6 => ({ + version: 6, + connectors, + customPages, + ...extra, + }); + + beforeEach(() => { + strategy = new CustomPagesProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no custom pages', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, customPages: [] })).toEqual([]); + }); + + it('should apply the defaults to a minimal page', () => { + expect( + strategy.transformToManifest( + withPages([ + { name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 'my-connector' } } }] }, + ]), + ), + ).toEqual([ + { + name: 'errors', + active: true, + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 0, uri: null, custom_status_code: null }, + }, + }, + ], + }, + ]); + }); + + it('should map every field of the custom page to the manifest', () => { + expect( + strategy.transformToManifest( + withPages([ + { + name: 'errors', + active: false, + pages: [ + { + code: 'default', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 300, uri: '/error.html', customStatusCode: 200 }, + }, + }, + { code: '500', page: { attributes: { connector: 'my-connector', uri: '/500.html' } } }, + ], + }, + ]), + ), + ).toEqual([ + { + name: 'errors', + active: false, + pages: [ + { + code: 'default', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 300, uri: '/error.html', custom_status_code: 200 }, + }, + }, + { + code: '500', + page: { + type: 'page_connector', + attributes: { connector: 'my-connector', ttl: 0, uri: '/500.html', custom_status_code: null }, + }, + }, + ], + }, + ]); + }); + + it('should keep a connector referenced by id as a string, without validating it', () => { + const [customPage] = strategy.transformToManifest({ + version: 6, + customPages: [{ name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 10 } } }] }], + }); + + expect(customPage.pages[0].page.attributes.connector).toBe('10'); + }); + + it('should throw when the connector of a page is not declared', () => { + const pages: AzionCustomPageV6[] = [ + { name: 'errors', pages: [{ code: '404', page: { attributes: { connector: 'missing' } } }] }, + ]; + const message = 'Custom page "errors" with error code "404" references non-existent Connector "missing".'; + + expect(() => strategy.transformToManifest(withPages(pages))).toThrow(message); + expect(() => strategy.transformToManifest(withPages(pages, { connectors: undefined }))).toThrow(message); + }); + }); + + describe('transformToConfig', () => { + it('should not set custom pages when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ custom_pages: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.customPages).toBeUndefined(); + }); + + it('should map the custom_pages of the manifest back to the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { + custom_pages: [ + { + name: 'errors', + active: true, + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 10, ttl: 60, uri: '/404.html', custom_status_code: 404 }, + }, + }, + ], + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.customPages).toEqual([ + { + name: 'errors', + active: true, + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 10, ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts new file mode 100644 index 00000000..d3c0c189 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts @@ -0,0 +1,101 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionConnectorV6, AzionCustomPageV6 } from '../../types'; + +/** + * CustomPagesProcessConfigStrategy V6 + * @class CustomPagesProcessConfigStrategy + * @description Converts the v6 custom pages between the config (`customPages`) and the manifest (`custom_pages`). + * The connector of a page is kept in the manifest as the name (or the id as a string) the config has, which the Azion + * CLI resolves to the id of the API. + */ +class CustomPagesProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate Connector references + */ + private validateConnectorReference( + connectors: AzionConnectorV6[] | undefined, + connectorNameOrId: string | number, + customPageName: string, + errorCode: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof connectorNameOrId === 'string') { + if (!Array.isArray(connectors) || !connectors.find((connector) => connector.name === connectorNameOrId)) { + throw new Error( + `Custom page "${customPageName}" with error code "${errorCode}" references non-existent Connector "${connectorNameOrId}".`, + ); + } + } + } + + /** + * Transform azion.config Custom Pages to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const customPages = config?.customPages; + if (!Array.isArray(customPages) || customPages.length === 0) { + return []; + } + + return customPages.map((customPage: AzionCustomPageV6) => { + // Validate connector references + customPage.pages.forEach((pageEntry) => { + this.validateConnectorReference( + config.connectors, + pageEntry.page.attributes.connector, + customPage.name, + pageEntry.code, + ); + }); + + return { + name: customPage.name, + active: customPage.active ?? true, + pages: customPage.pages.map((pageEntry) => ({ + code: pageEntry.code, + page: { + type: pageEntry.page.type || 'page_connector', + attributes: { + connector: String(pageEntry.page.attributes.connector), + ttl: pageEntry.page.attributes.ttl ?? 0, + uri: pageEntry.page.attributes.uri || null, + custom_status_code: pageEntry.page.attributes.customStatusCode || null, + }, + }, + })), + }; + }); + } + + /** + * Transform V6 manifest format back to azion.config Custom Pages + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { custom_pages?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.custom_pages) || payload.custom_pages.length === 0) { + return; + } + + transformedPayload.customPages = payload.custom_pages.map((customPage) => ({ + name: customPage.name, + active: customPage.active, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + pages: customPage.pages.map((pageEntry: any) => ({ + code: pageEntry.code, + page: { + type: pageEntry.page.type, + attributes: { + connector: pageEntry.page.attributes.connector, // Keep as it comes from the API + ttl: pageEntry.page.attributes.ttl, + uri: pageEntry.page.attributes.uri, + customStatusCode: pageEntry.page.attributes.custom_status_code, + }, + }, + })), + })); + + return transformedPayload.customPages; + } +} + +export default CustomPagesProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts new file mode 100644 index 00000000..b1d92001 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts @@ -0,0 +1,337 @@ +import type { AzionConfigV6, AzionFirewallBehaviorV6, AzionFirewallV6 } from '../../../types'; +import FirewallProcessConfigStrategy from './firewallProcessConfigStrategy'; + +describe('FirewallProcessConfigStrategy (v6)', () => { + let strategy: FirewallProcessConfigStrategy; + + const withFirewall = (firewall: AzionFirewallV6, extra: Partial = {}): AzionConfigV6 => ({ + version: 6, + firewall: [firewall], + ...extra, + }); + const withBehaviors = (behaviors: AzionFirewallBehaviorV6[]) => + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors, + }, + ], + }); + + beforeEach(() => { + strategy = new FirewallProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no firewalls', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should apply the defaults to a firewall with only the name', () => { + expect(strategy.transformToManifest(withFirewall({ name: 'my-firewall' }))).toEqual([ + { + name: 'my-firewall', + modules: { + functions: { enabled: true }, + network_protection: { enabled: true }, + waf: { enabled: false }, + }, + debug: false, + active: true, + }, + ]); + }); + + it('should write active and debugRules to the manifest (v4 ignored them)', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ name: 'my-firewall', active: false, debugRules: true, functions: false, waf: true }), + ); + + expect(firewall).toEqual( + expect.objectContaining({ + active: false, + debug: true, + modules: { + functions: { enabled: false }, + network_protection: { enabled: true }, + waf: { enabled: true }, + }, + }), + ); + }); + + it('should wrap the variables of the criteria in ${} and keep them in one group', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + description: 'Block admin', + criteria: [ + { variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }, + { variable: '${host}', conditional: 'and', operator: 'exists' }, + ], + behaviors: [{ type: 'deny' }], + }, + ], + }), + ); + + expect(firewall.rules_engine).toEqual([ + { + name: 'rule', + description: 'Block admin', + active: true, + behaviors: [{ type: 'deny' }], + criteria: [ + [ + { variable: '${request_uri}', conditional: 'if', operator: 'starts_with', argument: '/admin' }, + { variable: '${host}', conditional: 'and', operator: 'exists' }, + ], + ], + }, + ]); + }); + + it('should build a matches criterion from match and variable', () => { + const [firewall] = strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [{ name: 'rule', match: '^/api', variable: 'request_uri', behaviors: [{ type: 'drop' }] }], + }), + ); + + expect(firewall.rules_engine[0].criteria).toEqual([ + [{ variable: '${request_uri}', operator: 'matches', conditional: 'if', argument: '^/api' }], + ]); + }); + + it('should accept a bypass behavior (new in v6) and keep run_function as it is', () => { + const [firewall] = strategy.transformToManifest( + withFirewall( + { + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'host', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }, { type: 'bypass' }], + }, + ], + }, + { functions: [{ name: 'fn', path: './fn.js' }] }, + ), + ); + + expect(firewall.rules_engine[0].behaviors).toEqual([ + { type: 'run_function', attributes: { value: 'fn' } }, + { type: 'bypass' }, + ]); + }); + + it('should map set_waf, set_rate_limit and set_custom_response to the manifest', () => { + const [firewall] = strategy.transformToManifest( + withBehaviors([{ type: 'set_waf', attributes: { mode: 'logging', wafId: 'my-waf' } }]), + ); + expect(firewall.rules_engine[0].behaviors).toEqual([ + { type: 'set_waf', attributes: { mode: 'logging', waf_id: 'my-waf' } }, + ]); + + const [rateLimit] = strategy.transformToManifest( + withBehaviors([ + { + type: 'set_rate_limit', + attributes: { type: 'minute', limitBy: 'client_ip', averageRateLimit: 100, maximumBurstSize: 20 }, + }, + ]), + ); + expect(rateLimit.rules_engine[0].behaviors).toEqual([ + { + type: 'set_rate_limit', + attributes: { type: 'minute', limit_by: 'client_ip', average_rate_limit: 100, maximum_burst_size: 20 }, + }, + ]); + + const [custom] = strategy.transformToManifest( + withBehaviors([ + { + type: 'set_custom_response', + attributes: { statusCode: 403, contentType: 'text/plain', contentBody: 'Forbidden' }, + }, + ]), + ); + expect(custom.rules_engine[0].behaviors).toEqual([ + { + type: 'set_custom_response', + attributes: { status_code: 403, content_type: 'text/plain', content_body: 'Forbidden' }, + }, + ]); + }); + + it('should leave out the optional attributes of the rate limit and of the custom response', () => { + const [rateLimit] = strategy.transformToManifest( + withBehaviors([{ type: 'set_rate_limit', attributes: { limitBy: 'global', averageRateLimit: 5 } }]), + ); + expect(rateLimit.rules_engine[0].behaviors[0].attributes).toEqual({ limit_by: 'global', average_rate_limit: 5 }); + + const [custom] = strategy.transformToManifest( + withBehaviors([{ type: 'set_custom_response', attributes: { statusCode: 404 } }]), + ); + expect(custom.rules_engine[0].behaviors[0].attributes).toEqual({ status_code: 404 }); + }); + + it('should throw when a terminal behavior is combined with another one', () => { + const terminal = (type: 'deny' | 'drop') => + strategy.transformToManifest( + withBehaviors([{ type }, { type: 'set_rate_limit', attributes: { limitBy: 'global', averageRateLimit: 5 } }]), + ); + + expect(() => terminal('deny')).toThrow("The behavior 'deny' is a terminal behavior and must be used alone."); + expect(() => terminal('drop')).toThrow("The behavior 'drop' is a terminal behavior and must be used alone."); + expect(() => + strategy.transformToManifest( + withBehaviors([{ type: 'set_custom_response', attributes: { statusCode: 403 } }, { type: 'bypass' }]), + ), + ).toThrow("The behavior 'set_custom_response' is a terminal behavior"); + }); + + describe('network list references', () => { + const withList = ( + operator: 'is_in_list' | 'is_not_in_list', + argument: string | number, + extra: Partial = {}, + ) => + withFirewall( + { + name: 'my-firewall', + rules: [ + { + name: 'Block list', + criteria: [{ variable: 'network', conditional: 'if', operator, argument }], + behaviors: [{ type: 'deny' }], + }, + ], + }, + extra, + ); + + it('should accept a rule that references a declared network list', () => { + const networkList = [{ name: 'blocked-ips', type: 'ip_cidr' as const, items: ['10.0.0.0/8'] }]; + + expect(() => + strategy.transformToManifest(withList('is_in_list', 'blocked-ips', { networkList })), + ).not.toThrow(); + expect(() => + strategy.transformToManifest(withList('is_not_in_list', 'blocked-ips', { networkList })), + ).not.toThrow(); + }); + + it('should throw when the network list is not declared', () => { + const message = 'Firewall rule "Block list" references non-existent Network List "blocked-ips".'; + + expect(() => strategy.transformToManifest(withList('is_in_list', 'blocked-ips'))).toThrow(message); + expect(() => + strategy.transformToManifest( + withList('is_not_in_list', 'blocked-ips', { + networkList: [{ name: 'other', type: 'asn', items: ['1'] }], + }), + ), + ).toThrow(message); + }); + + it('should not validate a network list referenced by id', () => { + expect(() => strategy.transformToManifest(withList('is_in_list', 10))).not.toThrow(); + }); + + it('should not validate the argument of the other operators', () => { + expect(() => + strategy.transformToManifest( + withFirewall({ + name: 'my-firewall', + rules: [ + { + name: 'rule', + criteria: [{ variable: 'host', conditional: 'if', operator: 'is_equal', argument: 'blocked-ips' }], + behaviors: [{ type: 'deny' }], + }, + ], + }), + ), + ).not.toThrow(); + }); + }); + + it('should write the function instances, with active, and validate the function', () => { + const firewall: AzionFirewallV6 = { + name: 'my-firewall', + functionsInstances: [ + { name: 'instance', ref: 'fn', args: { a: 1 } }, + { name: 'off', ref: 10, active: false }, + ], + }; + + expect( + strategy.transformToManifest(withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }))[0] + .functions_instances, + ).toEqual([ + { name: 'instance', args: { a: 1 }, active: true, function: 'fn' }, + { name: 'off', args: {}, active: false, function: 10 }, + ]); + expect(() => strategy.transformToManifest(withFirewall(firewall))).toThrow( + 'Function instance "instance" references non-existent Function "fn".', + ); + }); + }); + + describe('transformToConfig', () => { + it('should set an empty array when the manifest has no firewall', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toEqual([]); + expect(transformedPayload.firewall).toEqual([]); + }); + + it('should round trip a firewall through the manifest', () => { + const firewall: AzionFirewallV6 = { + name: 'my-firewall', + active: true, + debugRules: true, + functions: true, + networkProtection: true, + waf: true, + rules: [ + { + name: 'rule', + description: 'Block admin', + active: true, + criteria: [{ variable: '${request_uri}', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [ + { type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }, + { + type: 'set_rate_limit', + attributes: { type: 'second', limitBy: 'global', averageRateLimit: 10, maximumBurstSize: 2 }, + }, + ], + }, + { + name: 'deny', + active: true, + criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'deny' }], + }, + ], + functionsInstances: [{ name: 'instance', ref: 'fn', args: { a: 1 }, active: true }], + }; + const config = withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }); + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ firewall: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.firewall).toEqual([firewall]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts new file mode 100644 index 00000000..5bf56247 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts @@ -0,0 +1,264 @@ +import type { AzionFunction } from '../../../../../types'; +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { + AzionConfigV6, + AzionFirewallBehaviorV6, + AzionFirewallRuleV6, + AzionFirewallV6, + AzionNetworkListV6, +} from '../../../types'; + +/** + * FirewallProcessConfigStrategy V6 + * @class FirewallProcessConfigStrategy + * @description Converts the v6 firewalls between the config and the manifest. + * Unlike v4, the `active` and `debugRules` of the firewall are written to the manifest. + */ +class FirewallProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that referenced Function exists + */ + private validateFunctionReference( + functions: AzionFunction[] | undefined, + functionNameOrId: string | number, + instanceName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof functionNameOrId === 'string') { + if (!Array.isArray(functions) || !functions.find((func) => func.name === functionNameOrId)) { + throw new Error(`Function instance "${instanceName}" references non-existent Function "${functionNameOrId}".`); + } + } + } + + /** + * Validate that the network list referenced by is_in_list and is_not_in_list exists + */ + private validateNetworkListReference( + networkLists: AzionNetworkListV6[] | undefined, + networkListNameOrId: string | number, + ruleName: string, + ) { + // Only validate if it's a string (name), skip validation for numbers (IDs) + if (typeof networkListNameOrId === 'string') { + if (!Array.isArray(networkLists) || !networkLists.find((list) => list.name === networkListNameOrId)) { + throw new Error(`Firewall rule "${ruleName}" references non-existent Network List "${networkListNameOrId}".`); + } + } + } + + transformToManifest(config: AzionConfigV6) { + if (!config.firewall || !Array.isArray(config.firewall)) { + return []; + } + + return config.firewall.map((fw: AzionFirewallV6) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const payload: any = { + name: fw.name, + modules: { + functions: { + enabled: fw.functions ?? true, + }, + network_protection: { + enabled: fw.networkProtection ?? true, + }, + waf: { + enabled: fw.waf ?? false, + }, + }, + debug: fw.debugRules ?? false, + active: fw.active ?? true, + }; + + if (fw.rules && fw.rules.length > 0) { + fw.rules.forEach((rule: AzionFirewallRuleV6) => + rule.criteria?.forEach((criterion) => { + if ( + (criterion.operator === 'is_in_list' || criterion.operator === 'is_not_in_list') && + criterion.argument !== undefined && + criterion.argument !== null + ) { + this.validateNetworkListReference(config.networkList, criterion.argument, rule.name); + } + }), + ); + + payload.rules_engine = fw.rules.map((rule: AzionFirewallRuleV6) => ({ + name: rule.name, + description: rule.description || '', + active: rule.active ?? true, + behaviors: this.transformBehaviorsToManifest(rule.behaviors), + criteria: rule.criteria + ? [ + rule.criteria.map((criterion) => ({ + variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, + conditional: criterion.conditional, + operator: criterion.operator, + ...('argument' in criterion && { argument: criterion.argument }), + })), + ] + : [ + [ + { + variable: rule.variable?.startsWith('${') ? rule.variable : `\${${rule.variable}}`, + operator: 'matches', + conditional: 'if', + argument: rule.match, + }, + ], + ], + })); + } + + if (fw.functionsInstances && fw.functionsInstances.length > 0) { + payload.functions_instances = fw.functionsInstances.map((instance) => { + this.validateFunctionReference(config.functions, instance.ref, instance.name); + return { + name: instance.name, + args: instance.args || {}, + active: instance.active ?? true, + function: instance.ref, + }; + }); + } + + return payload; + }); + } + + private transformBehaviorsToManifest(behaviorArray: AzionFirewallBehaviorV6[]) { + // Runtime validation: deny, drop, and set_custom_response are terminal behaviors + // and cannot be combined with other behaviors + if (behaviorArray.length > 1) { + const firstBehavior = behaviorArray[0]; + const hasTerminalBehavior = + firstBehavior.type === 'deny' || firstBehavior.type === 'drop' || firstBehavior.type === 'set_custom_response'; + + if (hasTerminalBehavior) { + throw new Error( + `The behavior '${firstBehavior.type}' is a terminal behavior and must be used alone. ` + + `It cannot be combined with other behaviors in the same rule.`, + ); + } + } + + return behaviorArray.map((behavior) => { + switch (behavior.type) { + case 'set_waf': + return { + type: 'set_waf', + attributes: { + mode: behavior.attributes.mode, + waf_id: behavior.attributes.wafId, + }, + }; + case 'set_rate_limit': + return { + type: 'set_rate_limit', + attributes: { + ...(behavior.attributes.type && { type: behavior.attributes.type }), + limit_by: behavior.attributes.limitBy, + average_rate_limit: behavior.attributes.averageRateLimit, + ...(behavior.attributes.maximumBurstSize !== undefined && { + maximum_burst_size: behavior.attributes.maximumBurstSize, + }), + }, + }; + case 'set_custom_response': + return { + type: 'set_custom_response', + attributes: { + status_code: behavior.attributes.statusCode, + ...(behavior.attributes.contentType !== undefined && { content_type: behavior.attributes.contentType }), + ...(behavior.attributes.contentBody !== undefined && { content_body: behavior.attributes.contentBody }), + }, + }; + default: + // run_function, deny, drop and bypass keep their shape + return behavior; + } + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + if (!payload.firewall || !Array.isArray(payload.firewall)) { + transformedPayload.firewall = []; + return transformedPayload.firewall; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.firewall = payload.firewall.map((fw: any) => { + const firewallConfig: AzionFirewallV6 = { + name: fw?.name, + active: fw?.active ?? true, + functions: fw?.modules?.functions?.enabled ?? false, + networkProtection: fw?.modules?.network_protection?.enabled ?? false, + waf: fw?.modules?.waf?.enabled ?? false, + debugRules: fw?.debug ?? false, + }; + + if (fw.rules_engine && fw.rules_engine.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firewallConfig.rules = fw.rules_engine.map((rule: any) => ({ + name: rule.name, + description: rule.description || undefined, + active: rule.active ?? true, + behaviors: this.transformBehaviorsToConfig(rule.behaviors), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + criteria: rule.criteria?.[0]?.map((criterion: any) => ({ ...criterion })) || [], + })); + } + + if (fw.functions_instances && fw.functions_instances.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firewallConfig.functionsInstances = fw.functions_instances.map((instance: any) => ({ + name: instance.name, + args: instance.args || {}, + active: instance.active ?? true, + ref: instance.function, + })); + } + + return firewallConfig; + }); + return transformedPayload.firewall; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private transformBehaviorsToConfig(behaviors: any[]): AzionFirewallBehaviorV6[] { + return behaviors.map((b) => { + switch (b.type) { + case 'set_waf': + return { type: 'set_waf', attributes: { mode: b.attributes.mode, wafId: b.attributes.waf_id } }; + case 'set_rate_limit': + return { + type: 'set_rate_limit', + attributes: { + type: b.attributes.type, + limitBy: b.attributes.limit_by, + averageRateLimit: b.attributes.average_rate_limit, + maximumBurstSize: b.attributes.maximum_burst_size, + }, + }; + case 'set_custom_response': + return { + type: 'set_custom_response', + attributes: { + statusCode: b.attributes.status_code, + contentType: b.attributes.content_type, + contentBody: b.attributes.content_body, + }, + }; + case 'run_function': + return { type: 'run_function', attributes: b.attributes }; + default: + // deny, drop and bypass + return { type: b.type }; + } + }); + } +} + +export default FirewallProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts new file mode 100644 index 00000000..1e1957f8 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts @@ -0,0 +1,56 @@ +import type { AzionConfigV6 } from '../../../types'; +import NetworkListProcessConfigStrategy from './networkListProcessConfigStrategy'; + +describe('NetworkListProcessConfigStrategy (v6)', () => { + let strategy: NetworkListProcessConfigStrategy; + + beforeEach(() => { + strategy = new NetworkListProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there are no network lists', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, networkList: [] })).toBeUndefined(); + }); + + it('should map a network list to the manifest and default active to true', () => { + expect( + strategy.transformToManifest({ + version: 6, + networkList: [ + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'] }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'], active: false }, + { name: 'blocked-asns', type: 'asn', items: ['13335'] }, + ], + }), + ).toEqual([ + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'], active: true }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'], active: false }, + { name: 'blocked-asns', type: 'asn', items: ['13335'], active: true }, + ]); + }); + }); + + describe('transformToConfig', () => { + it('should not set network lists when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ network_list: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.networkList).toBeUndefined(); + }); + + it('should read the network_list key of the manifest back into the config (v4 read the wrong key)', () => { + const config: AzionConfigV6 = { + version: 6, + networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'], active: true }], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ network_list: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.networkList).toEqual(config.networkList); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts new file mode 100644 index 00000000..d0116d41 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts @@ -0,0 +1,49 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +/** + * NetworkListProcessConfigStrategy V6 + * @class NetworkListProcessConfigStrategy + * @description Converts the v6 network lists between the config (`networkList`) and the manifest (`network_list`). + */ +class NetworkListProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config Network List to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const networkList = config?.networkList; + if (!Array.isArray(networkList) || networkList.length === 0) { + return; + } + + return networkList.map((network) => ({ + name: network.name, + type: network.type, + items: network.items, + active: network.active ?? true, + })); + } + + /** + * Transform V6 manifest format back to azion.config Network List + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const networkList = payload?.network_list; + if (!Array.isArray(networkList) || networkList.length === 0) { + return; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.networkList = networkList.map((network: any) => ({ + name: network.name, + type: network.type, + items: network.items, + active: network.active, + })); + + return transformedPayload.networkList; + } +} + +export default NetworkListProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts new file mode 100644 index 00000000..0419e7e3 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.test.ts @@ -0,0 +1,105 @@ +import type { AzionConfigV6 } from '../../../types'; +import WafProcessConfigStrategy from './wafProcessConfigStrategy'; + +describe('WafProcessConfigStrategy (v6)', () => { + let strategy: WafProcessConfigStrategy; + + beforeEach(() => { + strategy = new WafProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no waf', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, waf: [] })).toBeUndefined(); + }); + + it('should apply the defaults of the API to a waf with only the name', () => { + expect(strategy.transformToManifest({ version: 6, waf: [{ name: 'my-waf' }] })).toEqual([ + { + name: 'my-waf', + engine_settings: { + engine_version: '2021-Q3', + type: 'score', + attributes: { rulesets: [1], thresholds: [] }, + }, + }, + ]); + }); + + it('should map every field of the waf to the manifest', () => { + expect( + strategy.transformToManifest({ + version: 6, + waf: [ + { + name: 'my-waf', + active: false, + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'high' }, { threat: 'file_upload' }], + }, + }, + }, + ], + }), + ).toEqual([ + { + name: 'my-waf', + active: false, + engine_settings: { + engine_version: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'high' }, { threat: 'file_upload' }], + }, + }, + }, + ]); + }); + + it('should not write product_version (it is not in the v6 request)', () => { + const [waf] = strategy.transformToManifest({ version: 6, waf: [{ name: 'my-waf' }] }) ?? []; + + expect(waf).not.toHaveProperty('product_version'); + }); + }); + + describe('transformToConfig', () => { + it('should not set waf when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.waf).toBeUndefined(); + }); + + it('should round trip a waf through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + waf: [ + { + name: 'my-waf', + active: true, + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'cross_site_scripting', sensitivity: 'low' }], + }, + }, + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ waf: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.waf).toEqual(config.waf); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts new file mode 100644 index 00000000..c28eaba8 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts @@ -0,0 +1,70 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6 } from '../../../types'; + +/** + * WafProcessConfigStrategy V6 + * @class WafProcessConfigStrategy + * @description Converts the v6 wafs between the config and the manifest. + * The engine settings are optional: the manifest defaults them to the ones of the API (engine 2021-Q3, type score, + * ruleset 1 and no thresholds). A threshold without sensitivity is left to the API. + */ +class WafProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config WAF to V6 manifest format + */ + transformToManifest(config: AzionConfigV6) { + const waf = config?.waf; + if (!Array.isArray(waf) || waf.length === 0) { + return; + } + + return waf.map((wafConfig) => ({ + name: wafConfig.name, + ...(wafConfig.active !== undefined && { active: wafConfig.active }), + engine_settings: { + engine_version: wafConfig.engineSettings?.engineVersion ?? '2021-Q3', + type: wafConfig.engineSettings?.type ?? 'score', + attributes: { + rulesets: wafConfig.engineSettings?.attributes?.rulesets ?? [1], + thresholds: (wafConfig.engineSettings?.attributes?.thresholds ?? []).map((threshold) => ({ + threat: threshold.threat, + ...(threshold.sensitivity && { sensitivity: threshold.sensitivity }), + })), + }, + }, + })); + } + + /** + * Transform V6 manifest format back to azion.config WAF + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const waf = payload?.waf; + if (!Array.isArray(waf) || waf.length === 0) { + return; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformedPayload.waf = waf.map((wafItem: any) => ({ + name: wafItem.name, + active: wafItem.active, + engineSettings: wafItem.engine_settings && { + engineVersion: wafItem.engine_settings.engine_version, + type: wafItem.engine_settings.type, + attributes: wafItem.engine_settings.attributes && { + rulesets: wafItem.engine_settings.attributes.rulesets, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + thresholds: wafItem.engine_settings.attributes.thresholds?.map((threshold: any) => ({ + threat: threshold.threat, + sensitivity: threshold.sensitivity, + })), + }, + }, + })); + + return transformedPayload.waf; + } +} + +export default WafProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index 70ff1ed6..87666b7a 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -3,9 +3,13 @@ import type { AzionConfigV6 } from '../types'; import ApplicationProcessConfigStrategy from './implementations/application/applicationProcessConfigStrategy'; import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; import ConnectorProcessConfigStrategy from './implementations/connectorProcessConfigStrategy'; +import CustomPagesProcessConfigStrategy from './implementations/customPagesProcessConfigStrategy'; import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; +import FirewallProcessConfigStrategy from './implementations/secure/firewallProcessConfigStrategy'; +import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; +import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; @@ -15,8 +19,12 @@ function factoryProcessContext() { processConfigContext.setStrategy('version', new VersionProcessConfigStrategy()); processConfigContext.setStrategy('build', new BuildProcessConfigStrategy()); processConfigContext.setStrategy('functions', new FunctionsProcessConfigStrategy()); + processConfigContext.setStrategy('network_list', new NetworkListProcessConfigStrategy()); + processConfigContext.setStrategy('waf', new WafProcessConfigStrategy()); processConfigContext.setStrategy('storage', new StorageProcessConfigStrategy()); + processConfigContext.setStrategy('firewall', new FirewallProcessConfigStrategy()); processConfigContext.setStrategy('connectors', new ConnectorProcessConfigStrategy()); + processConfigContext.setStrategy('custom_pages', new CustomPagesProcessConfigStrategy()); processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); diff --git a/packages/config/src/versions/v6/schemas/customPages/index.ts b/packages/config/src/versions/v6/schemas/customPages/index.ts new file mode 100644 index 00000000..5fdee758 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/customPages/index.ts @@ -0,0 +1,111 @@ +import { CUSTOM_PAGE_ERROR_CODES, CUSTOM_PAGE_TYPES } from '../../constants'; + +/** + * Schema of the v6 custom pages, based on v4 and checked against `CustomPageRequest` of the v6 API: at most 23 pages + * (one for each error code), the connector id is between 1 and 2147483647 and the `uri` has no pattern. + */ +const customPagesSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 255 characters", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + pages: { + type: 'array', + minItems: 1, + maxItems: 23, + items: { + type: 'object', + properties: { + code: { + type: 'string', + enum: CUSTOM_PAGE_ERROR_CODES, + errorMessage: "The 'code' field must be a valid error code", + }, + page: { + type: 'object', + properties: { + type: { + type: 'string', + enum: CUSTOM_PAGE_TYPES, + default: 'page_connector', + errorMessage: "The 'type' field must be a valid page type", + }, + attributes: { + type: 'object', + properties: { + connector: { + type: ['string', 'number'], + minimum: 1, + maximum: 2147483647, + errorMessage: + "The 'connector' field must be a string or a number between 1 and 2147483647 referencing a connector name or ID", + }, + ttl: { + type: 'integer', + minimum: 0, + maximum: 31536000, + default: 0, + errorMessage: "The 'ttl' field must be an integer between 0 and 31536000", + }, + uri: { + type: ['string', 'null'], + minLength: 1, + maxLength: 250, + errorMessage: "The 'uri' field must be a string between 1 and 250 characters or null", + }, + customStatusCode: { + type: ['integer', 'null'], + minimum: 100, + maximum: 599, + errorMessage: "The 'customStatusCode' field must be an integer between 100 and 599 or null", + }, + }, + required: ['connector'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page attributes', + required: "The 'connector' field is required in page attributes", + }, + }, + }, + required: ['attributes'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page configuration', + required: "The 'attributes' field is required in page configuration", + }, + }, + }, + required: ['code', 'page'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in page entry', + required: "The 'code' and 'page' fields are required in each page entry", + }, + }, + errorMessage: "The 'pages' field must be an array of 1 to 23 page configurations", + }, + }, + required: ['name', 'pages'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in custom page objects', + required: "The 'name' and 'pages' fields are required in each custom page", + }, + }, + errorMessage: "The 'customPages' field must be an array of custom page objects", +}; + +export default customPagesSchema; diff --git a/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts b/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts new file mode 100644 index 00000000..eba35989 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/behaviors/index.ts @@ -0,0 +1,208 @@ +import { + FIREWALL_NO_ARGS_BEHAVIORS, + FIREWALL_RATE_LIMIT_BY, + FIREWALL_RATE_LIMIT_TYPES, + FIREWALL_WAF_MODES, +} from '../../../constants'; + +const setRateLimitBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_rate_limit'], + errorMessage: "The 'type' field must be a valid set_rate_limit behavior type.", + }, + attributes: { + type: 'object', + properties: { + type: { + type: 'string', + enum: FIREWALL_RATE_LIMIT_TYPES, + default: 'second', + errorMessage: `The rate limit type must be one of: ${FIREWALL_RATE_LIMIT_TYPES.join(', ')}`, + }, + limitBy: { + type: 'string', + enum: FIREWALL_RATE_LIMIT_BY, + errorMessage: `The rate limit must be applied by one of: ${FIREWALL_RATE_LIMIT_BY.join(', ')}`, + }, + averageRateLimit: { + type: 'integer', + minimum: 1, + maximum: 2147483647, + errorMessage: 'The averageRateLimit must be an integer between 1 and 2147483647', + }, + maximumBurstSize: { + type: ['integer', 'null'], + minimum: 1, + maximum: 2147483647, + errorMessage: 'The maximumBurstSize must be an integer between 1 and 2147483647 or null', + }, + }, + required: ['limitBy', 'averageRateLimit'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in set_rate_limit behavior attributes.', + required: "The 'limitBy' and 'averageRateLimit' fields are required in set_rate_limit behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const setWafRuleSetBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_waf'], + errorMessage: "The 'type' field must be a valid set_waf behavior type.", + }, + attributes: { + type: 'object', + properties: { + mode: { + type: 'string', + enum: FIREWALL_WAF_MODES, + errorMessage: `The mode must be one of: ${FIREWALL_WAF_MODES.join(', ')}`, + }, + wafId: { + type: ['string', 'number'], + errorMessage: 'The wafId must be a string or number', + }, + }, + required: ['mode', 'wafId'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the set_waf object', + required: "Both 'mode' and 'wafId' fields are required in set_waf attributes", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const setCustomResponseBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['set_custom_response'], + errorMessage: "The 'type' field must be a valid set_custom_response behavior type.", + }, + attributes: { + type: 'object', + properties: { + statusCode: { + type: 'integer', + minimum: 200, + maximum: 499, + errorMessage: 'The statusCode must be an integer between 200 and 499', + }, + contentType: { + type: 'string', + maxLength: 255, + errorMessage: 'The contentType must be a string of at most 255 characters', + }, + contentBody: { + type: 'string', + maxLength: 500, + errorMessage: 'The contentBody must be a string of at most 500 characters', + }, + }, + required: ['statusCode'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the setCustomResponse object', + required: "The 'statusCode' field is required in setCustomResponse", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +const noArgsBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: FIREWALL_NO_ARGS_BEHAVIORS, + errorMessage: "The 'type' field must be a valid firewall no-args behavior type.", + }, + }, + required: ['type'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in firewall no-args behaviors.', + required: "The 'type' field is required in firewall no-args behaviors.", + }, +}; + +const runFunctionBehaviorSchema = { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['run_function'], + errorMessage: "The 'type' field must be 'run_function' for this behavior.", + }, + attributes: { + type: 'object', + properties: { + value: { + oneOf: [ + { + type: 'string', + minLength: 1, + maxLength: 255, + pattern: '.*', + errorMessage: "The 'value' field must be a string between 1 and 255 characters.", + }, + { + type: 'number', + minimum: 1, + errorMessage: "The 'value' field must be a positive number.", + }, + ], + errorMessage: "The 'value' field must be a string or positive number.", + }, + }, + required: ['value'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in run_function behavior attributes.', + required: "The 'value' field is required in run_function behavior attributes.", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, +}; + +/** + * Behaviors of a firewall rule, from `FirewallBehaviorRequest` of the v6 API: `bypass` is a behavior without + * arguments, the mode of `set_waf` is logging or blocking, and the rate limit and the status code are integers. + */ +const firewallBehaviorSchema = { + if: { type: 'object', properties: { type: { const: 'run_function' } }, required: ['type'] }, + then: runFunctionBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_waf' } }, required: ['type'] }, + then: setWafRuleSetBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_rate_limit' } }, required: ['type'] }, + then: setRateLimitBehaviorSchema, + else: { + if: { type: 'object', properties: { type: { const: 'set_custom_response' } }, required: ['type'] }, + then: setCustomResponseBehaviorSchema, + else: noArgsBehaviorSchema, + }, + }, + }, +}; + +export default firewallBehaviorSchema; diff --git a/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts new file mode 100644 index 00000000..9e7fb74c --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts @@ -0,0 +1,36 @@ +/** + * Schema of the function instances of a v6 firewall, from `FirewallFunctionInstanceRequest` of the v6 API: + * the request also has `active`. + */ +const firewallFunctionsInstances = { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: 'The name must be a string between 1 and 100 characters long', + }, + args: { + type: 'object', + default: {}, + errorMessage: "The 'args' field must be an object", + }, + ref: { + type: ['string', 'number'], + errorMessage: "The 'ref' field must be a string or number referencing an existing Function name or ID", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + }, + required: ['name', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the firewallFunctionsInstance object', + }, +}; + +export default firewallFunctionsInstances; diff --git a/packages/config/src/versions/v6/schemas/firewall/index.ts b/packages/config/src/versions/v6/schemas/firewall/index.ts new file mode 100644 index 00000000..fdca4911 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/firewall/index.ts @@ -0,0 +1,183 @@ +import { FIREWALL_RULE_CONDITIONAL, FIREWALL_RULE_OPERATORS, FIREWALL_VARIABLES } from '../../constants'; +import firewallBehaviorSchema from './behaviors'; +import firewallFunctionsInstances from './functionsInstances'; + +/** + * Schema of the v6 firewalls, based on v4 and checked against `FirewallRequest` and `FirewallRuleRequest` of the v6 API. + */ +const firewall = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + errorMessage: "The firewall configuration must have a 'name' field of type string (1-250 characters)", + }, + active: { + type: 'boolean', + errorMessage: "The firewall's 'active' field must be a boolean", + }, + debugRules: { + type: 'boolean', + errorMessage: "The firewall's 'debugRules' field must be a boolean", + }, + functions: { + type: 'boolean', + errorMessage: "The firewall's 'functions' field must be a boolean", + }, + networkProtection: { + type: 'boolean', + errorMessage: "The firewall's 'networkProtection' field must be a boolean", + }, + waf: { + type: 'boolean', + errorMessage: "The firewall's 'waf' field must be a boolean", + }, + rules: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 100, + errorMessage: "Each firewall rule must have a 'name' field of type string (1-100 characters)", + }, + description: { + type: 'string', + maxLength: 1000, + errorMessage: "The rule's 'description' field must be a string of at most 1000 characters", + }, + active: { + type: 'boolean', + errorMessage: "The rule's 'active' field must be a boolean", + }, + match: { + type: 'string', + errorMessage: "The rule's 'match' field must be a string containing a valid regex pattern", + }, + variable: { + anyOf: [ + { + type: 'string', + pattern: '^\\$\\{(' + [...new Set(FIREWALL_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + enum: [...FIREWALL_VARIABLES], + errorMessage: "The 'variable' field must be a valid firewall variable", + }, + ], + errorMessage: "The 'variable' field must be a valid variable (with or without ${})", + }, + behaviors: { + type: 'array', + items: firewallBehaviorSchema, + minItems: 1, + maxItems: 10, + errorMessage: 'The behaviors must be an array with 1-10 items.', + }, + criteria: { + type: 'array', + minItems: 1, + maxItems: 10, + items: { + type: 'object', + properties: { + conditional: { + type: 'string', + enum: FIREWALL_RULE_CONDITIONAL, + errorMessage: `The 'conditional' field must be one of: ${FIREWALL_RULE_CONDITIONAL.join(', ')}`, + }, + variable: { + anyOf: [ + { + type: 'string', + pattern: '^\\$\\{(' + [...new Set(FIREWALL_VARIABLES)].join('|') + ')\\}$', + errorMessage: "The 'variable' field must be a valid variable wrapped in ${}", + }, + { + type: 'string', + enum: [...FIREWALL_VARIABLES], + errorMessage: "The 'variable' field must be a valid firewall variable", + }, + ], + errorMessage: "The 'variable' field must be a valid variable (with or without ${})", + }, + operator: { + type: 'string', + enum: FIREWALL_RULE_OPERATORS, + errorMessage: `The 'operator' field must be one of: ${FIREWALL_RULE_OPERATORS.join(', ')}`, + }, + argument: { + type: ['string', 'number', 'null'], + errorMessage: 'The argument must be a string, a number or null', + }, + }, + required: ['conditional', 'variable', 'operator'], + additionalProperties: false, + // only `exists` and `does_not_exist` do not compare with a value + if: { properties: { operator: { enum: ['exists', 'does_not_exist'] } }, required: ['operator'] }, + else: { + required: ['argument'], + properties: { argument: { type: ['string', 'number'] } }, + errorMessage: { + required: "The 'argument' field is required unless the operator is 'exists' or 'does_not_exist'", + properties: { argument: 'The argument must be a string or a number for this operator' }, + }, + }, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the criteria object', + required: "The 'variable', 'operator' and 'conditional' fields are required in each criteria object", + }, + }, + errorMessage: { + type: 'The criteria field must be an array with at least one criteria item', + }, + }, + }, + required: ['name', 'behaviors'], + oneOf: [ + { + required: ['match', 'variable'], + not: { required: ['criteria'] }, + errorMessage: + "When using 'match' or 'variable', both fields are required and cannot be used with 'criteria'.", + }, + { + required: ['criteria'], + not: { + anyOf: [{ required: ['match'] }, { required: ['variable'] }], + }, + errorMessage: "Cannot use 'criteria' together with 'match' or 'variable'.", + }, + ], + errorMessage: { + oneOf: "You must use either 'match' AND 'variable' together OR 'criteria', but not both at the same time", + }, + }, + }, + functionsInstances: { + type: 'array', + items: firewallFunctionsInstances, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + type: 'Each firewall item must be an object', + additionalProperties: 'No additional properties are allowed in the firewall object', + required: "The 'name' field is required in each firewall object", + }, + }, + errorMessage: { + type: "The 'firewall' field must be an array of firewall objects", + }, +}; + +export default firewall; diff --git a/packages/config/src/versions/v6/schemas/networkList/index.ts b/packages/config/src/versions/v6/schemas/networkList/index.ts new file mode 100644 index 00000000..c242eba0 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/networkList/index.ts @@ -0,0 +1,85 @@ +import { NETWORK_LIST_TYPES } from '../../constants'; + +/** + * Schema of the v6 network lists, from `NetworkListRequest` of the v6 API: each item has 1 to 250 characters. + * The items follow the formats the API documents for the types `asn` (digits only) and `countries` (two uppercase + * alphanumeric characters, ISO 3166-1 alpha-2). The items of `ip_cidr` can be an IP with or without CIDR and with or + * without an expiration date, so they are not checked. + */ +const networkListSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 250 characters.", + }, + type: { + type: 'string', + enum: NETWORK_LIST_TYPES, + errorMessage: "The 'type' field must be a string. Accepted values are 'ip_cidr', 'asn' or 'countries'.", + }, + items: { + type: 'array', + minItems: 1, + maxItems: 20000, + items: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "Each item in 'items' must be a string between 1 and 250 characters.", + }, + errorMessage: "The 'items' field must be an array of strings with 1-20000 items.", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean.", + }, + }, + required: ['name', 'type', 'items'], + additionalProperties: false, + allOf: [ + { + if: { properties: { type: { const: 'asn' } }, required: ['type'] }, + then: { + properties: { + items: { + type: 'array', + items: { + pattern: '^[0-9]+$', + errorMessage: 'Each ASN item must be a number composed of digits only.', + }, + }, + }, + }, + }, + { + if: { properties: { type: { const: 'countries' } }, required: ['type'] }, + then: { + properties: { + items: { + type: 'array', + items: { + pattern: '^[A-Z0-9]{2}$', + errorMessage: + 'Each country item must be a two-character uppercase alphanumeric code (ISO 3166-1 alpha-2).', + }, + }, + }, + }, + }, + ], + errorMessage: { + additionalProperties: 'No additional properties are allowed in network list items.', + required: "The 'name', 'type' and 'items' fields are required in each network list item.", + }, + }, +}; + +export default networkListSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index eb2ebee4..6501a57b 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -1,15 +1,19 @@ import applicationsSchema from './applications'; import buildSchema from './build'; import connectorsSchema from './connectors'; +import customPagesSchema from './customPages'; import deploymentsSchema from './deployments'; import environmentsSchema from './environments'; +import firewallSchema from './firewall'; import functionsSchema from './functions'; +import networkListSchema from './networkList'; import storageSchema from './storage'; +import wafSchema from './waf'; import workloadsSchema from './workloads'; /** * JSON Schema of the v6 config. - * TODO: only `version`, `build`, `functions`, `storage`, `connectors`, `applications`, `workloads`, `environments` and `deployments` are accepted until the schemas of the other v6 resources are defined. + * TODO: only `version`, `build`, `functions`, `storage`, `connectors`, `customPages`, `networkList`, `waf`, `firewall`, `applications`, `workloads`, `environments` and `deployments` are accepted until the schemas of the other v6 resources are defined. */ const azionConfigSchema = { $id: 'azionConfig', @@ -22,6 +26,10 @@ const azionConfigSchema = { functions: functionsSchema, storage: storageSchema, connectors: connectorsSchema, + customPages: customPagesSchema, + networkList: networkListSchema, + waf: wafSchema, + firewall: firewallSchema, applications: applicationsSchema, workloads: workloadsSchema, environments: environmentsSchema, @@ -30,7 +38,7 @@ const azionConfigSchema = { additionalProperties: false, errorMessage: { additionalProperties: - 'Config can only contain the following properties: version, build, functions, storage, connectors, applications, workloads, environments, deployments', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/schemas/waf/index.ts b/packages/config/src/versions/v6/schemas/waf/index.ts new file mode 100644 index 00000000..f23dcce9 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/waf/index.ts @@ -0,0 +1,110 @@ +import { + WAF_ENGINE_TYPES, + WAF_ENGINE_VERSIONS, + WAF_RULESETS, + WAF_SENSITIVITY, + WAF_THREAT_TYPES, +} from '../../constants'; + +/** + * Schema of the v6 wafs, from `WAFRequest` of the v6 API. The request has no `id` nor `productVersion`, only the name + * is required, and a threshold only requires the threat. + */ +const wafSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The WAF configuration must have a 'name' field of type string (1-250 characters)", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + engineSettings: { + type: 'object', + properties: { + engineVersion: { + type: 'string', + enum: WAF_ENGINE_VERSIONS, + default: '2021-Q3', + errorMessage: "The 'engineVersion' field must be '2021-Q3'", + }, + type: { + type: 'string', + enum: WAF_ENGINE_TYPES, + default: 'score', + errorMessage: "The 'type' field must be 'score'", + }, + attributes: { + type: 'object', + properties: { + rulesets: { + type: 'array', + items: { + type: 'integer', + enum: WAF_RULESETS, + errorMessage: "The 'rulesets' field must be an array containing [1]", + }, + default: [1], + errorMessage: "The 'rulesets' field must be an array containing [1]", + }, + thresholds: { + type: 'array', + items: { + type: 'object', + properties: { + threat: { + type: 'string', + enum: WAF_THREAT_TYPES, + errorMessage: `The 'threat' field must be one of: ${WAF_THREAT_TYPES.join(', ')}`, + }, + sensitivity: { + type: 'string', + enum: WAF_SENSITIVITY, + errorMessage: `The 'sensitivity' field must be one of: ${WAF_SENSITIVITY.join(', ')}`, + }, + }, + required: ['threat'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in a threshold', + required: "The 'threat' field is required in each threshold", + }, + }, + maxItems: 8, + errorMessage: "The 'thresholds' field must be an array of threat configurations (max 8 items)", + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the attributes object', + }, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in the engineSettings object', + }, + }, + }, + required: ['name'], + additionalProperties: false, + errorMessage: { + type: "The 'waf' field must be an object", + additionalProperties: 'No additional properties are allowed in the WAF object', + required: "The 'name' field is required in the WAF object", + }, + }, + errorMessage: { + type: "The 'waf' field must be an array", + }, +}; + +export default wafSchema; diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 442e1383..46e846cc 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -18,11 +18,25 @@ import type { CONNECTOR_LOAD_BALANCE_METHOD, CONNECTOR_SERVER_ROLES, CONNECTOR_TRANSPORT_POLICY, + CUSTOM_PAGE_ERROR_CODES, + CUSTOM_PAGE_TYPES, DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES, ENVIRONMENT_BRANCH_TRACKING_MODES, ENVIRONMENT_LOG_VERBOSITY, ENVIRONMENT_ROBOTS_POLICIES, + FIREWALL_NO_ARGS_BEHAVIORS, + FIREWALL_RATE_LIMIT_BY, + FIREWALL_RATE_LIMIT_TYPES, + FIREWALL_RULE_CONDITIONAL, + FIREWALL_RULE_OPERATORS, + FIREWALL_WAF_MODES, + NETWORK_LIST_TYPES, + WAF_ENGINE_TYPES, + WAF_ENGINE_VERSIONS, + WAF_RULESETS, + WAF_SENSITIVITY, + WAF_THREAT_TYPES, WORKLOADS_ACCESS_TYPES, } from './constants'; @@ -238,6 +252,134 @@ export type AzionConnectorV6 = attributes: { region: (typeof CONNECTOR_LIVE_INGEST_REGIONS)[number] }; }); +/** + * Page of a custom page, served for an error code. + */ +export type AzionCustomPageEntryV6 = { + /** Error code the page is served for (or `default`) */ + code: (typeof CUSTOM_PAGE_ERROR_CODES)[number]; + page: { + type?: (typeof CUSTOM_PAGE_TYPES)[number]; + attributes: { + /** Name of a connector declared in `connectors`, or its id */ + connector: string | number; + /** Time to live in seconds */ + ttl?: number; + /** Path the connector is requested with */ + uri?: string | null; + customStatusCode?: number | null; + }; + }; +}; + +/** + * Custom pages of the Azion API v6. + */ +export type AzionCustomPageV6 = { + /** Custom page name */ + name: string; + /** Active status */ + active?: boolean; + /** Pages, one for each error code */ + pages: AzionCustomPageEntryV6[]; +}; + +/** + * Network list of the Azion API v6. + */ +export type AzionNetworkListV6 = { + /** Network list name */ + name: string; + /** Type of the items: IP addresses (with or without CIDR), ASNs or country codes */ + type: (typeof NETWORK_LIST_TYPES)[number]; + /** Items of the list */ + items: string[]; + /** Active status */ + active?: boolean; +}; + +/** + * Criterion of a firewall rule. The argument is optional (the operators `exists` and `does_not_exist` do not take one). + */ +export type AzionFirewallCriterionV6 = { + /** Variable, with or without `${}` */ + variable: string; + conditional: (typeof FIREWALL_RULE_CONDITIONAL)[number]; + operator: (typeof FIREWALL_RULE_OPERATORS)[number]; + argument?: string | number | null; +}; + +/** + * Behavior of a firewall rule. `run_function` and `set_waf` reference a function and a waf by name or by id. + */ +export type AzionFirewallBehaviorV6 = + | { type: 'run_function'; attributes: { value: string | number } } + | { type: 'set_waf'; attributes: { mode: (typeof FIREWALL_WAF_MODES)[number]; wafId: string | number } } + | { + type: 'set_rate_limit'; + attributes: { + type?: (typeof FIREWALL_RATE_LIMIT_TYPES)[number]; + limitBy: (typeof FIREWALL_RATE_LIMIT_BY)[number]; + averageRateLimit: number; + maximumBurstSize?: number | null; + }; + } + | { type: (typeof FIREWALL_NO_ARGS_BEHAVIORS)[number] } + | { + type: 'set_custom_response'; + attributes: { statusCode: number; contentType?: string; contentBody?: string }; + }; + +/** + * Rule of a firewall: either `criteria`, or `match` and `variable` together (a `matches` criterion). + */ +export type AzionFirewallRuleV6 = { + name: string; + description?: string; + active?: boolean; + /** Regex the variable must match */ + match?: string; + variable?: string; + criteria?: AzionFirewallCriterionV6[]; + behaviors: AzionFirewallBehaviorV6[]; +}; + +/** + * Firewall of the Azion API v6. + */ +export type AzionFirewallV6 = { + name: string; + active?: boolean; + debugRules?: boolean; + /** Enable the functions module */ + functions?: boolean; + /** Enable the network protection module */ + networkProtection?: boolean; + /** Enable the waf module */ + waf?: boolean; + rules?: AzionFirewallRuleV6[]; + functionsInstances?: AzionFunctionInstance[]; +}; + +/** + * WAF of the Azion API v6. + */ +export type AzionWafV6 = { + name: string; + active?: boolean; + engineSettings?: { + engineVersion?: (typeof WAF_ENGINE_VERSIONS)[number]; + type?: (typeof WAF_ENGINE_TYPES)[number]; + attributes?: { + rulesets?: (typeof WAF_RULESETS)[number][]; + thresholds?: { + threat: (typeof WAF_THREAT_TYPES)[number]; + sensitivity?: (typeof WAF_SENSITIVITY)[number]; + }[]; + }; + }; +}; + /** * Config of the Azion API v6. * TODO: structure placeholder. Add the remaining v6 resources once their schemas are defined. @@ -251,6 +393,14 @@ export type AzionConfigV6 = { functions?: AzionFunctionV6[]; /** Storage buckets */ storage?: AzionStorageV6[]; + /** Custom pages */ + customPages?: AzionCustomPageV6[]; + /** Network lists */ + networkList?: AzionNetworkListV6[]; + /** WAFs */ + waf?: AzionWafV6[]; + /** Firewalls */ + firewall?: AzionFirewallV6[]; /** Connectors */ connectors?: AzionConnectorV6[]; /** Applications */ diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index e52c4ddb..9f83a63e 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -107,8 +107,8 @@ describe('validateConfig (v6)', () => { }); it('rejects properties the v6 schema does not know yet', () => { - expect(() => validateConfig({ version: 6, firewall: [] })).toThrow( - 'Config can only contain the following properties: version, build, functions, storage, connectors, applications, workloads, environments, deployments', + expect(() => validateConfig({ version: 6, purge: [] })).toThrow( + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments', ); }); @@ -784,3 +784,493 @@ describe('validateConfig (v6) application cache', () => { ); }); }); + +describe('validateConfig (v6) waf and firewall', () => { + const waf = (extra: Record = {}) => ({ version: 6, waf: [{ name: 'my-waf', ...extra }] }); + const firewall = (extra: Record = {}) => ({ + version: 6, + firewall: [{ name: 'my-firewall', ...extra }], + }); + const rule = (extra: Record = {}) => + firewall({ + rules: [ + { + name: 'rule', + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'deny' }], + ...extra, + }, + ], + }); + const behavior = (value: Record) => rule({ behaviors: [value] }); + + describe('waf', () => { + it('accepts a waf with only the name, and a complete one', () => { + expect(() => validateConfig(waf())).not.toThrow(); + expect(() => + validateConfig( + waf({ + active: false, + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [{ threat: 'sql_injection', sensitivity: 'highest' }, { threat: 'file_upload' }], + }, + }, + }), + ), + ).not.toThrow(); + }); + + it('requires the name and limits it to 250 characters', () => { + expect(() => validateConfig({ version: 6, waf: [{ active: true }] })).toThrow( + "The 'name' field is required in the WAF object", + ); + expect(() => validateConfig({ version: 6, waf: [{ name: 'a'.repeat(251) }] })).toThrow(); + }); + + it('does not accept id nor productVersion (they are not in the v6 request)', () => { + expect(() => validateConfig(waf({ id: 1 }))).toThrow('No additional properties are allowed in the WAF object'); + expect(() => validateConfig(waf({ productVersion: '1.0' }))).toThrow( + 'No additional properties are allowed in the WAF object', + ); + }); + + it('validates the engine settings and the thresholds', () => { + const engine = (attributes: Record) => waf({ engineSettings: { attributes } }); + + expect(() => validateConfig(waf({ engineSettings: { engineVersion: '2022-Q1' } }))).toThrow( + "The 'engineVersion' field must be '2021-Q3'", + ); + expect(() => validateConfig(waf({ engineSettings: { type: 'rules' } }))).toThrow( + "The 'type' field must be 'score'", + ); + expect(() => validateConfig(engine({ rulesets: [2] }))).toThrow( + "The 'rulesets' field must be an array containing [1]", + ); + expect(() => validateConfig(engine({ thresholds: [{ sensitivity: 'low' }] }))).toThrow( + "The 'threat' field is required in each threshold", + ); + expect(() => validateConfig(engine({ thresholds: [{ threat: 'xss' }] }))).toThrow( + "The 'threat' field must be one of:", + ); + expect(() => validateConfig(engine({ thresholds: [{ threat: 'file_upload', sensitivity: 'max' }] }))).toThrow( + "The 'sensitivity' field must be one of: highest, high, medium, low, lowest", + ); + expect(() => + validateConfig(engine({ thresholds: Array.from({ length: 9 }, () => ({ threat: 'file_upload' })) })), + ).toThrow("The 'thresholds' field must be an array of threat configurations (max 8 items)"); + }); + }); + + describe('firewall', () => { + it('accepts a firewall with only the name, and a complete one', () => { + expect(() => validateConfig(firewall())).not.toThrow(); + expect(() => + validateConfig( + firewall({ + active: true, + debugRules: false, + functions: true, + networkProtection: true, + waf: true, + rules: [ + { + name: 'rule', + description: 'Block admin', + active: true, + criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], + behaviors: [{ type: 'bypass' }], + }, + ], + functionsInstances: [{ name: 'instance', ref: 'fn', args: {}, active: false }], + }), + ), + ).not.toThrow(); + }); + + it('limits the firewall name to 250 characters and the rule name to 100 (v6 API limits)', () => { + expect(() => validateConfig({ version: 6, firewall: [{ name: 'a'.repeat(250) }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, firewall: [{ name: 'a'.repeat(251) }] })).toThrow( + "The firewall configuration must have a 'name' field of type string (1-250 characters)", + ); + expect(() => validateConfig(rule({ name: 'a'.repeat(100) }))).not.toThrow(); + expect(() => validateConfig(rule({ name: 'a'.repeat(101) }))).toThrow( + "Each firewall rule must have a 'name' field of type string (1-100 characters)", + ); + expect(() => validateConfig(rule({ description: 'a'.repeat(1001) }))).toThrow( + "The rule's 'description' field must be a string of at most 1000 characters", + ); + }); + + it('requires the argument unless the operator is exists or does_not_exist', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', ...value }] }); + const message = "The 'argument' field is required unless the operator is 'exists' or 'does_not_exist'"; + + expect(() => validateConfig(criterion({ operator: 'is_equal', argument: 'example.com' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'exists' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'does_not_exist' }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'is_equal' }))).toThrow(message); + expect(() => validateConfig(criterion({ operator: 'is_in_list' }))).toThrow(message); + expect(() => validateConfig(criterion({ operator: 'matches', argument: null }))).toThrow(); + }); + + it('does not require the argument of a criterion and accepts null', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', operator: 'exists', ...value }] }); + + expect(() => validateConfig(criterion({}))).not.toThrow(); + expect(() => validateConfig(criterion({ argument: null }))).not.toThrow(); + expect(() => validateConfig(criterion({ operator: 'is_in_list', argument: 12 }))).not.toThrow(); + expect(() => validateConfig(criterion({ argument: true }))).toThrow( + 'The argument must be a string, a number or null', + ); + }); + + it('allows up to 10 criteria in a rule (the group limit of the v6 API)', () => { + const criteria = (n: number) => + rule({ + criteria: Array.from({ length: n }, () => ({ variable: 'host', conditional: 'and', operator: 'exists' })), + }); + + expect(() => validateConfig(criteria(10))).not.toThrow(); + expect(() => validateConfig(criteria(11))).toThrow(); + }); + + it('requires either criteria or match and variable together', () => { + expect(() => + validateConfig( + firewall({ rules: [{ name: 'rule', match: '^/', variable: 'request_uri', behaviors: [{ type: 'drop' }] }] }), + ), + ).not.toThrow(); + expect(() => + validateConfig(firewall({ rules: [{ name: 'rule', match: '^/', behaviors: [{ type: 'drop' }] }] })), + ).toThrow(); + expect(() => validateConfig(rule({ match: '^/', variable: 'request_uri' }))).toThrow(); + }); + + it('accepts only the variables, operators and conditionals of the firewall', () => { + const criterion = (value: Record) => + rule({ criteria: [{ variable: 'host', conditional: 'if', operator: 'exists', ...value }] }); + + expect(() => validateConfig(criterion({ variable: '${uri}' }))).toThrow(); + expect(() => validateConfig(criterion({ operator: 'contains' }))).toThrow("The 'operator' field must be one of:"); + expect(() => validateConfig(criterion({ conditional: 'not' }))).toThrow( + "The 'conditional' field must be one of: if, and, or", + ); + }); + + describe('behaviors', () => { + it('accepts deny, drop and bypass (new in v6)', () => { + ['deny', 'drop', 'bypass'].forEach((type) => expect(() => validateConfig(behavior({ type }))).not.toThrow()); + expect(() => validateConfig(behavior({ type: 'allow' }))).toThrow(); + }); + + it('validates set_waf: the mode is logging or blocking in v6 (learning in v4)', () => { + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'logging', wafId: 'my-waf' } })), + ).not.toThrow(); + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'blocking', wafId: 1 } })), + ).not.toThrow(); + expect(() => + validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'learning', wafId: 'my-waf' } })), + ).toThrow('The mode must be one of: logging, blocking'); + expect(() => validateConfig(behavior({ type: 'set_waf', attributes: { mode: 'logging' } }))).toThrow( + "Both 'mode' and 'wafId' fields are required in set_waf attributes", + ); + }); + + it('validates set_rate_limit: integers, and only limitBy and averageRateLimit are required', () => { + const rateLimit = (attributes: Record) => behavior({ type: 'set_rate_limit', attributes }); + + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 10 }))).not.toThrow(); + expect(() => + validateConfig( + rateLimit({ type: 'minute', limitBy: 'client_ip', averageRateLimit: 10, maximumBurstSize: null }), + ), + ).not.toThrow(); + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: '10' }))).toThrow( + 'The averageRateLimit must be an integer between 1 and 2147483647', + ); + expect(() => validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 0 }))).toThrow(); + expect(() => + validateConfig(rateLimit({ limitBy: 'global', averageRateLimit: 5, maximumBurstSize: '1' })), + ).toThrow('The maximumBurstSize must be an integer between 1 and 2147483647 or null'); + expect(() => validateConfig(rateLimit({ limitBy: 'global' }))).toThrow( + "The 'limitBy' and 'averageRateLimit' fields are required in set_rate_limit behavior attributes.", + ); + expect(() => validateConfig(rateLimit({ type: 'hour', limitBy: 'global', averageRateLimit: 5 }))).toThrow( + 'The rate limit type must be one of: second, minute', + ); + }); + + it('validates set_custom_response: an integer status code and the limits of the content', () => { + const custom = (attributes: Record) => behavior({ type: 'set_custom_response', attributes }); + + expect(() => validateConfig(custom({ statusCode: 403 }))).not.toThrow(); + expect(() => + validateConfig(custom({ statusCode: 200, contentType: 'text/plain', contentBody: 'a'.repeat(500) })), + ).not.toThrow(); + expect(() => validateConfig(custom({ statusCode: '403' }))).toThrow( + 'The statusCode must be an integer between 200 and 499', + ); + expect(() => validateConfig(custom({ statusCode: 500 }))).toThrow(); + expect(() => validateConfig(custom({ statusCode: 403, contentBody: 'a'.repeat(501) }))).toThrow( + 'The contentBody must be a string of at most 500 characters', + ); + expect(() => validateConfig(custom({ statusCode: 403, contentType: 'a'.repeat(256) }))).toThrow( + 'The contentType must be a string of at most 255 characters', + ); + expect(() => validateConfig(custom({}))).toThrow("The 'statusCode' field is required in setCustomResponse"); + }); + + it('validates run_function', () => { + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 'fn' } }))).not.toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 7 } }))).not.toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: { value: 0 } }))).toThrow(); + expect(() => validateConfig(behavior({ type: 'run_function', attributes: {} }))).toThrow( + "The 'value' field is required in run_function behavior attributes.", + ); + }); + + it('requires between 1 and 10 behaviors', () => { + expect(() => validateConfig(rule({ behaviors: [] }))).toThrow( + 'The behaviors must be an array with 1-10 items.', + ); + expect(() => + validateConfig(rule({ behaviors: Array.from({ length: 11 }, () => ({ type: 'bypass' })) })), + ).toThrow('The behaviors must be an array with 1-10 items.'); + }); + }); + + describe('functionsInstances', () => { + const instance = (value: Record) => firewall({ functionsInstances: [value] }); + + it('accepts active (the v6 request has it) and limits the name to 100 characters', () => { + expect(() => validateConfig(instance({ name: 'i', ref: 'fn', active: false }))).not.toThrow(); + expect(() => validateConfig(instance({ name: 'a'.repeat(100), ref: 10 }))).not.toThrow(); + expect(() => validateConfig(instance({ name: 'a'.repeat(101), ref: 'fn' }))).toThrow( + 'The name must be a string between 1 and 100 characters long', + ); + }); + + it('requires name and ref and rejects unknown properties', () => { + expect(() => validateConfig(instance({ name: 'i' }))).toThrow(); + expect(() => validateConfig(instance({ name: 'i', ref: 'fn', unknown: true }))).toThrow( + 'No additional properties are allowed in the firewallFunctionsInstance object', + ); + }); + }); + }); +}); + +describe('validateConfig (v6) networkList', () => { + const list = (extra: Record = {}) => ({ + version: 6, + networkList: [{ name: 'my-list', type: 'ip_cidr', items: ['10.0.0.0/8'], ...extra }], + }); + + it('accepts every type of list, with and without active', () => { + expect(() => validateConfig(list())).not.toThrow(); + expect(() => validateConfig(list({ type: 'asn', items: ['13335'], active: false }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['BR', 'US'] }))).not.toThrow(); + }); + + it('requires name, type and items', () => { + const message = "The 'name', 'type' and 'items' fields are required in each network list item."; + + expect(() => validateConfig({ version: 6, networkList: [{ type: 'asn', items: ['1'] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, networkList: [{ name: 'my-list', items: ['1'] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, networkList: [{ name: 'my-list', type: 'asn' }] })).toThrow(message); + }); + + it('rejects an unknown type and limits the name to 250 characters', () => { + expect(() => validateConfig(list({ type: 'domain' }))).toThrow( + "The 'type' field must be a string. Accepted values are 'ip_cidr', 'asn' or 'countries'.", + ); + expect(() => validateConfig(list({ name: 'a'.repeat(250) }))).not.toThrow(); + expect(() => validateConfig(list({ name: 'a'.repeat(251) }))).toThrow( + "The 'name' field must be a string between 1 and 250 characters.", + ); + }); + + it('requires 1 to 20000 items of 1 to 250 characters each (v6 API)', () => { + expect(() => validateConfig(list({ items: [] }))).toThrow( + "The 'items' field must be an array of strings with 1-20000 items.", + ); + expect(() => validateConfig(list({ items: Array.from({ length: 20000 }, (_, i) => `10.0.${i}.1`) }))).not.toThrow(); + expect(() => validateConfig(list({ items: Array.from({ length: 20001 }, (_, i) => `10.0.${i}.1`) }))).toThrow(); + expect(() => validateConfig(list({ items: [''] }))).toThrow( + "Each item in 'items' must be a string between 1 and 250 characters.", + ); + expect(() => validateConfig(list({ items: ['a'.repeat(251)] }))).toThrow(); + expect(() => validateConfig(list({ items: [13335] }))).toThrow(); + }); + + it('requires the ASN items to be digits only', () => { + expect(() => validateConfig(list({ type: 'asn', items: ['13335', '1'] }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'asn', items: ['AS13335'] }))).toThrow( + 'Each ASN item must be a number composed of digits only.', + ); + expect(() => validateConfig(list({ type: 'asn', items: ['13335', '12.5'] }))).toThrow(); + }); + + it('requires the country items to be two uppercase alphanumeric characters', () => { + expect(() => validateConfig(list({ type: 'countries', items: ['BR', 'US', 'D3'] }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['br'] }))).toThrow( + 'Each country item must be a two-character uppercase alphanumeric code (ISO 3166-1 alpha-2).', + ); + expect(() => validateConfig(list({ type: 'countries', items: ['BRA'] }))).toThrow(); + expect(() => validateConfig(list({ type: 'countries', items: ['B'] }))).toThrow(); + }); + + it('does not check the format of the ip_cidr items (IPs, CIDRs and expiration dates)', () => { + expect(() => + validateConfig( + list({ + items: ['192.168.0.1', '192.168.0.1/24', '2001:db8::/32', '192.168.0.1 --LT2025-05-29T12:25:23Z'], + }), + ), + ).not.toThrow(); + }); + + it('rejects unknown properties', () => { + expect(() => validateConfig(list({ unknown: true }))).toThrow( + 'No additional properties are allowed in network list items.', + ); + }); +}); + +describe('validateConfig (v6) customPages', () => { + const entry = (extra: Record = {}, attributes: Record = {}) => ({ + code: '404', + page: { attributes: { connector: 'my-connector', ...attributes }, ...extra }, + }); + const customPages = (pages: unknown[], extra: Record = {}) => ({ + version: 6, + customPages: [{ name: 'errors', pages, ...extra }], + }); + + it('accepts a minimal and a complete custom page', () => { + expect(() => validateConfig(customPages([entry()]))).not.toThrow(); + expect(() => + validateConfig( + customPages( + [ + entry({ type: 'page_connector' }, { connector: 10, ttl: 300, uri: '/error.html', customStatusCode: 200 }), + { code: 'default', page: { attributes: { connector: 'my-connector', uri: null, customStatusCode: null } } }, + ], + { active: false }, + ), + ), + ).not.toThrow(); + }); + + it('requires name and pages, and at least one page', () => { + const message = "The 'name' and 'pages' fields are required in each custom page"; + + expect(() => validateConfig({ version: 6, customPages: [{ pages: [entry()] }] })).toThrow(message); + expect(() => validateConfig({ version: 6, customPages: [{ name: 'errors' }] })).toThrow(message); + expect(() => validateConfig(customPages([]))).toThrow( + "The 'pages' field must be an array of 1 to 23 page configurations", + ); + }); + + it('allows up to 23 pages, one for each error code (v6 API limit)', () => { + const codes = [ + 'default', + '400', + '401', + '403', + '404', + '405', + '406', + '408', + '409', + '410', + '411', + '414', + '415', + '416', + '426', + '429', + '431', + '500', + '501', + '502', + '503', + '504', + '505', + ]; + const pages = codes.map((code) => ({ ...entry(), code })); + + expect(() => validateConfig(customPages(pages))).not.toThrow(); + expect(() => validateConfig(customPages([...pages, entry()]))).toThrow( + "The 'pages' field must be an array of 1 to 23 page configurations", + ); + }); + + it('accepts only the error codes of the API', () => { + expect(() => validateConfig(customPages([{ ...entry(), code: '418' }]))).toThrow( + "The 'code' field must be a valid error code", + ); + expect(() => validateConfig(customPages([{ ...entry(), code: 404 }]))).toThrow(); + }); + + it('requires the connector, as a name or an id between 1 and 2147483647', () => { + expect(() => validateConfig(customPages([entry({}, { connector: 1 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 2147483647 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 0 })]))).toThrow(); + expect(() => validateConfig(customPages([entry({}, { connector: 2147483648 })]))).toThrow(); + expect(() => validateConfig(customPages([{ code: '404', page: { attributes: { ttl: 1 } } }]))).toThrow( + "The 'connector' field is required in page attributes", + ); + }); + + it('validates the ttl and the custom status code', () => { + expect(() => validateConfig(customPages([entry({}, { ttl: 31536000 })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { ttl: 31536001 })]))).toThrow( + "The 'ttl' field must be an integer between 0 and 31536000", + ); + expect(() => validateConfig(customPages([entry({}, { ttl: -1 })]))).toThrow(); + expect(() => validateConfig(customPages([entry({}, { customStatusCode: 600 })]))).toThrow( + "The 'customStatusCode' field must be an integer between 100 and 599 or null", + ); + expect(() => validateConfig(customPages([entry({}, { customStatusCode: 99 })]))).toThrow(); + }); + + it('validates the uri: 1 to 250 characters or null, with no pattern (v6 API)', () => { + expect(() => validateConfig(customPages([entry({}, { uri: '/errors/404.html' })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'errors/404 page.html' })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'a'.repeat(250) })]))).not.toThrow(); + expect(() => validateConfig(customPages([entry({}, { uri: 'a'.repeat(251) })]))).toThrow( + "The 'uri' field must be a string between 1 and 250 characters or null", + ); + expect(() => validateConfig(customPages([entry({}, { uri: '' })]))).toThrow(); + }); + + it('accepts only the page_connector type', () => { + expect(() => validateConfig(customPages([entry({ type: 'page_static' })]))).toThrow( + "The 'type' field must be a valid page type", + ); + }); + + it('limits the name to 255 characters and rejects unknown properties', () => { + expect(() => + validateConfig({ version: 6, customPages: [{ name: 'a'.repeat(255), pages: [entry()] }] }), + ).not.toThrow(); + expect(() => validateConfig({ version: 6, customPages: [{ name: 'a'.repeat(256), pages: [entry()] }] })).toThrow( + "The 'name' field must be a string between 1 and 255 characters", + ); + expect(() => validateConfig(customPages([entry()], { unknown: true }))).toThrow( + 'No additional properties are allowed in custom page objects', + ); + expect(() => validateConfig(customPages([{ ...entry(), unknown: true }]))).toThrow( + 'No additional properties are allowed in page entry', + ); + }); +}); From 405b814019385d18e731b89d393b745694e08e92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 10:18:29 -0300 Subject: [PATCH 14/29] feat(presets): add the v6 config to the eleventy preset Add the build, the storage of the _site folder, the storage connector, the application with the cache and the MPA rules, an environment, a deployment and the workload bound to them, as the v4 config has. A test checks that the storage, the connectors and the application of the v6 manifest are the same as the ones of the v4 manifest. --- packages/presets/src/presets/configs.test.ts | 20 ++++- .../presets/src/presets/eleventy/config.v6.ts | 76 +++++++++++++++++++ .../presets/src/presets/eleventy/index.ts | 9 ++- 3 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 packages/presets/src/presets/eleventy/config.v6.ts diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 1292fbc0..42780d1a 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -40,12 +40,13 @@ describe('preset configs by API version', () => { }); describe('v6', () => { - it('is declared by javascript, opennextjs and react only for now', () => { + it('is declared by eleventy, javascript, opennextjs and react only for now', () => { const withV6 = presets .filter((preset) => preset.configs?.[6]) .map((preset) => preset.metadata.name) .sort(); - expect(withV6).toEqual(['javascript', 'opennextjs', 'react']); + expect(withV6).toEqual(['eleventy', 'javascript', 'opennextjs', 'react']); + expect(getPresetApiVersions(byName('eleventy'))).toEqual([3, 4, 6]); expect(getPresetApiVersions(byName('opennextjs'))).toEqual([3, 4, 6]); expect(getPresetApiVersions(byName('javascript'))).toEqual([3, 4, 6]); expect(getPresetApiVersions(byName('react'))).toEqual([3, 4, 6]); @@ -88,6 +89,21 @@ describe('preset configs by API version', () => { expect(v6.connectors.map((connector: { name: string }) => connector.name)).toEqual(['$CONNECTOR_NAME']); }); + it('eleventy: validates and has the same storage, connectors and application in the manifest as the v4 config', () => { + const config = resolvePresetConfig(byName('eleventy'), 6); + expect(() => validateConfig(config)).not.toThrow(); + + const v4 = processConfig(resolvePresetConfig(byName('eleventy'), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(v4.connectors); + expect(v6.applications).toEqual(v4.applications); + expect(v6.applications[0].cache_settings).toHaveLength(1); + expect(v6.storage[0].dir).toBe('./_site'); + }); + it('opennextjs: validates and has the same storage, connectors, functions and application in the manifest as the v4 config', () => { const config = resolvePresetConfig(byName('opennextjs'), 6); expect(() => validateConfig(config)).not.toThrow(); diff --git a/packages/presets/src/presets/eleventy/config.v6.ts b/packages/presets/src/presets/eleventy/config.v6.ts new file mode 100644 index 00000000..2adab860 --- /dev/null +++ b/packages/presets/src/presets/eleventy/config.v6.ts @@ -0,0 +1,76 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './_site', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/eleventy/index.ts b/packages/presets/src/presets/eleventy/index.ts index db34c542..3ef5016d 100644 --- a/packages/presets/src/presets/eleventy/index.ts +++ b/packages/presets/src/presets/eleventy/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const eleventy: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const eleventy: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; From d01376c26f3c22a90113775ee8c7cf801ff1d613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 3 Nov 2026 10:24:06 -0300 Subject: [PATCH 15/29] feat(config): define the firewall replaced keys of API v6 A firewall-only project must not inherit the keys of a preset that only serve an application. v6 has the ones of v4 (applications, workloads, connectors and functions) plus the environments and the deployments, which only exist to bind a workload to an application. Tests check the keys of v3, v4 and v6 and that the keys of v4 and v6 exist in the config schema of their version. --- .../config/src/versions/accessors.test.ts | 19 +++++++++++++++++++ packages/config/src/versions/v6/index.ts | 5 +++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index f7420440..aa196c50 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from '@jest/globals'; import { getApplicationName, getFirewallReplacedKeys, getStorage } from './accessors'; +import v4Schema from './v4/schemas/schema'; +import v6Schema from './v6/schemas/schema'; const v4 = { applications: [{ name: 'app-1' }, { name: 'app-2' }], @@ -74,5 +76,22 @@ describe('version accessors', () => { it('lists the preset keys a firewall-only project must not inherit', () => { expect(getFirewallReplacedKeys(4)).toEqual(['applications', 'workloads', 'connectors', 'functions']); expect(getFirewallReplacedKeys(3)).toEqual(['origin', 'cache', 'rules', 'functions']); + expect(getFirewallReplacedKeys(6)).toEqual([ + 'applications', + 'workloads', + 'connectors', + 'functions', + 'environments', + 'deployments', + ]); + }); + + it('lists only keys that exist in the config schema of each version', () => { + const properties = (schema: { definitions: { mainConfig: { properties: object } } }) => + Object.keys(schema.definitions.mainConfig.properties); + const schemas = { 4: properties(v4Schema), 6: properties(v6Schema) }; + + getFirewallReplacedKeys(4).forEach((key) => expect(schemas[4]).toContain(key)); + getFirewallReplacedKeys(6).forEach((key) => expect(schemas[6]).toContain(key)); }); }); diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts index 8a896568..68d458ef 100644 --- a/packages/config/src/versions/v6/index.ts +++ b/packages/config/src/versions/v6/index.ts @@ -12,8 +12,9 @@ const accessors: ConfigVersionAccessors = { const storage = (config as AzionConfigV6).storage?.[0]; return storage ? { bucket: storage.name, prefix: storage.prefix ?? '' } : undefined; }, - // TODO: define the keys a firewall-only project must not inherit once the v6 config has firewall - firewallReplacedKeys: [], + // the keys of a preset that only serve an application, which a firewall-only project does not have. The environments + // and the deployments only exist to bind a workload to an application, so they go along with the workloads + firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments', 'deployments'], }; // v6 has its own AzionConfig type, which is not assignable to the default (v4) one used by the shared contract From 34168ac162cdcd73421ec4b2385d8e264622dbac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 10:21:20 -0300 Subject: [PATCH 16/29] fix(config): declare the item types of the v6 network list schema Ajv strict mode warned about the items of the asn and countries lists on every validation of a v6 config, since the whole schema is compiled. Add a test that compiles every config and manifest schema and fails on any strict mode warning. --- .../src/versions/schemaStrictMode.test.ts | 50 +++++++++++++++++++ .../versions/v6/schemas/networkList/index.ts | 2 + 2 files changed, 52 insertions(+) create mode 100644 packages/config/src/versions/schemaStrictMode.test.ts diff --git a/packages/config/src/versions/schemaStrictMode.test.ts b/packages/config/src/versions/schemaStrictMode.test.ts new file mode 100644 index 00000000..3a790da8 --- /dev/null +++ b/packages/config/src/versions/schemaStrictMode.test.ts @@ -0,0 +1,50 @@ +import Ajv from 'ajv'; +import ajvErrors from 'ajv-errors'; +import addKeywords from 'ajv-keywords'; + +import v3Schema from './v3/schemas/schema'; +import { schemaManifest as v3Manifest } from './v3/schemas/schemaManifest'; +import v4Schema from './v4/schemas/schema'; +import { schemaManifest as v4Manifest } from './v4/schemas/schemaManifest'; +import v6Schema from './v6/schemas/schema'; +import { schemaManifest as v6Manifest } from './v6/schemas/schemaManifest'; + +// The validators compile the whole schema of a version on every call, even if the config does not use a resource, so a +// schema that breaks the strict mode of ajv (e.g. `pattern` without `type: 'string'`) warns for every config. +// Jest only prints the console of a failing suite, so the warnings are captured here and checked. +function compileWarnings(schema: Record) { + const warnings: string[] = []; + const ajv = new Ajv({ + allErrors: true, + $data: true, + allowUnionTypes: true, + logger: { + log: () => undefined, + warn: (message: unknown) => warnings.push(String(message)), + error: (message: unknown) => warnings.push(String(message)), + }, + }); + ajvErrors(ajv); + addKeywords(ajv, ['instanceof']); + ajv.compile(schema); + return warnings; +} + +describe('schemas compile in the strict mode of ajv', () => { + it.each([ + ['v3 config', v3Schema], + ['v3 manifest', v3Manifest], + ['v4 config', v4Schema], + ['v4 manifest', v4Manifest], + ['v6 config', v6Schema], + ['v6 manifest', v6Manifest], + ])('%s has no warnings', (_name, schema) => { + expect(compileWarnings(schema as Record)).toEqual([]); + }); + + it('catches a schema that breaks the strict mode', () => { + const warnings = compileWarnings({ type: 'object', properties: { items: { pattern: '^[0-9]+$' } } }); + + expect(warnings.join('\n')).toContain('missing type "string" for keyword "pattern"'); + }); +}); diff --git a/packages/config/src/versions/v6/schemas/networkList/index.ts b/packages/config/src/versions/v6/schemas/networkList/index.ts index c242eba0..b838b774 100644 --- a/packages/config/src/versions/v6/schemas/networkList/index.ts +++ b/packages/config/src/versions/v6/schemas/networkList/index.ts @@ -52,6 +52,7 @@ const networkListSchema = { items: { type: 'array', items: { + type: 'string', pattern: '^[0-9]+$', errorMessage: 'Each ASN item must be a number composed of digits only.', }, @@ -66,6 +67,7 @@ const networkListSchema = { items: { type: 'array', items: { + type: 'string', pattern: '^[A-Z0-9]{2}$', errorMessage: 'Each country item must be a two-character uppercase alphanumeric code (ISO 3166-1 alpha-2).', From 01e43b87162841083bbd1f771373279d13645814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 10:21:33 -0300 Subject: [PATCH 17/29] feat(config): name the environment and deployment of a workload binding in API v6 The config only knows names, and the CLI resolves them to the ids of the resources it creates, so the manifest binding carries environment_name and deployment_name instead of environment_id and deployment_id. --- .../workloadProcessConfigStrategy.test.ts | 27 ++++++++++++++++--- .../workloadProcessConfigStrategy.ts | 11 ++++---- packages/presets/src/presets/configs.test.ts | 2 +- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts index 9d0af6e7..59324002 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts @@ -88,8 +88,8 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { ); expect(workload.bindings).toEqual([ { - environment_id: 'production', - deployment_id: 'default-deployment', + environment_name: 'production', + deployment_name: 'default-deployment', domains: [ { domain: 'example.com', certificate: 7 }, { domain: 'www.example.com', certificate: null }, @@ -98,6 +98,15 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { ]); }); + it('should name the environment and the deployment of a binding as names, not as ids (the CLI resolves the ids)', () => { + const [workload] = strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], + }); + + expect(Object.keys(workload.bindings[0])).toEqual(['environment_name', 'deployment_name', 'domains']); + }); + it('should throw when a binding references an environment that is not declared', () => { expect(() => strategy.transformToManifest({ @@ -145,7 +154,11 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { tls: { ciphers: 3, minimum_version: 'tls_1_2' }, protocols: { http: { versions: ['http1'], http_ports: [80], https_ports: [443], quic_ports: null } }, bindings: [ - { environment_id: 'ENV01', deployment_id: 'DEP01', domains: [{ domain: 'a.com', certificate: 1 }] }, + { + environment_name: 'production', + deployment_name: 'default-deployment', + domains: [{ domain: 'a.com', certificate: 1 }], + }, ], }, ], @@ -162,7 +175,13 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, protocols: { http: { versions: ['http1'], httpPorts: [80], httpsPorts: [443], quicPorts: null } }, mtls: undefined, - bindings: [{ environment: 'ENV01', deployment: 'DEP01', domains: [{ domain: 'a.com', certificate: 1 }] }], + bindings: [ + { + environment: 'production', + deployment: 'default-deployment', + domains: [{ domain: 'a.com', certificate: 1 }], + }, + ], }, ]); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts index dd1a1450..742a07e9 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts @@ -6,7 +6,8 @@ import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; * @class WorkloadProcessConfigStrategy * @description Converts the v6 workloads between the config and the manifest. * A binding references an environment and a deployment by the name it has in the config. The manifest keeps that name - * in `environment_id` and `deployment_id`, which the Azion CLI resolves to the ids of the API. + * in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, so it is the + * one that knows their ids and sends them to the API. */ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy { /** @@ -62,8 +63,8 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy } : undefined, bindings: (workload.bindings ?? []).map((binding) => ({ - environment_id: binding.environment, - deployment_id: binding.deployment, + environment_name: binding.environment, + deployment_name: binding.deployment, domains: (binding.domains ?? []).map((item) => ({ domain: item.domain, certificate: item.certificate ?? null, @@ -109,8 +110,8 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy bindings: workload.bindings?.map( // eslint-disable-next-line @typescript-eslint/no-explicit-any (binding: any) => ({ - environment: binding.environment_id, - deployment: binding.deployment_id, + environment: binding.environment_name, + deployment: binding.deployment_name, domains: binding.domains, }), ), diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 42780d1a..3015f515 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -138,7 +138,7 @@ describe('preset configs by API version', () => { expect.objectContaining({ name: '$WORKLOAD_NAME', active: true, infrastructure: 1 }), ); expect(manifest.workloads[0].bindings).toEqual([ - { environment_id: '$ENVIRONMENT_NAME', deployment_id: '$DEPLOYMENT_NAME', domains: [] }, + { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, ]); }); }); From 81b9a9463f57da4211253554d465848214dc27de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 10:32:37 -0300 Subject: [PATCH 18/29] feat(config): add the device groups of an application to API v6 DeviceGroupRequest has the same constraints as v4, so the schema and the strategy are separate copies of the v4 ones. --- .../applicationProcessConfigStrategy.test.ts | 21 ++++++++++ .../applicationProcessConfigStrategy.ts | 8 +++- .../deviceGroupsProcessConfigStrategy.test.ts | 37 ++++++++++++++++++ .../deviceGroupsProcessConfigStrategy.ts | 39 +++++++++++++++++++ .../versions/v6/schemas/applications/index.ts | 31 ++++++++++++++- packages/config/src/versions/v6/types.ts | 13 ++++++- .../versions/v6/validateConfig/index.test.ts | 26 +++++++++++++ 7 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts index e074ddcc..9151536d 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts @@ -123,6 +123,27 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(application.modules.functions.enabled).toBe(true); }); + it('should round trip the device groups through the manifest', () => { + const deviceGroups = [{ name: 'mobile', userAgent: 'Android|iPhone' }]; + const [application] = strategy.transformToManifest({ + version: 6, + applications: [{ name: 'my-app', deviceGroups }], + }); + + expect(application.device_groups).toEqual([{ name: 'mobile', user_agent: 'Android|iPhone' }]); + + const transformedPayload: AzionConfigV6 = { version: 6 }; + strategy.transformToConfig({ applications: [application] }, transformedPayload); + + expect(transformedPayload.applications?.[0].deviceGroups).toEqual(deviceGroups); + }); + + it('should not write device_groups when the application has none', () => { + const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); + + expect(application).not.toHaveProperty('device_groups'); + }); + it('should not write rules and function instances when the application has none', () => { const [application] = strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app' }] }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts index 2ea5b476..d393f776 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -1,6 +1,7 @@ import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; import type { AzionApplicationV6, AzionConfigV6 } from '../../../types'; import CacheProcessConfigStrategy from './cacheProcessConfigStrategy'; +import DeviceGroupsProcessConfigStrategy from './deviceGroupsProcessConfigStrategy'; import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; @@ -8,12 +9,12 @@ import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; * ApplicationProcessConfigStrategy * @class ApplicationProcessConfigStrategy * @description Converts the v6 applications between the config and the manifest. - * TODO: convert the remaining resources of an application (device groups). */ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { private cacheStrategy = new CacheProcessConfigStrategy(); private rulesStrategy = new RulesProcessConfigStrategy(); private functionInstancesStrategy = new FunctionInstancesProcessConfigStrategy(); + private deviceGroupsStrategy = new DeviceGroupsProcessConfigStrategy(); transformToManifest(config: AzionConfigV6) { if (!config.applications || !Array.isArray(config.applications)) { @@ -58,6 +59,10 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { + const strategy = new DeviceGroupsProcessConfigStrategy(); + + describe('transformToManifest', () => { + it('should map each device group to the manifest', () => { + expect( + strategy.transformToManifest([ + { name: 'mobile', userAgent: 'Android|iPhone' }, + { name: 'desktop', userAgent: 'Windows|Macintosh' }, + ]), + ).toEqual([ + { name: 'mobile', user_agent: 'Android|iPhone' }, + { name: 'desktop', user_agent: 'Windows|Macintosh' }, + ]); + }); + + it('should return undefined when there are no device groups', () => { + expect(strategy.transformToManifest([])).toBeUndefined(); + expect(strategy.transformToManifest(undefined as never)).toBeUndefined(); + }); + }); + + describe('transformToConfig', () => { + it('should map the manifest device groups back to the config', () => { + expect(strategy.transformToConfig([{ name: 'mobile', user_agent: 'Android|iPhone' }])).toEqual([ + { name: 'mobile', userAgent: 'Android|iPhone' }, + ]); + }); + + it('should return an empty array when there are no device groups', () => { + expect(strategy.transformToConfig([])).toEqual([]); + expect(strategy.transformToConfig(undefined as never)).toEqual([]); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts new file mode 100644 index 00000000..9f0e6ef3 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/deviceGroupsProcessConfigStrategy.ts @@ -0,0 +1,39 @@ +import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionDeviceGroupV6 } from '../../../types'; + +/** + * DeviceGroupsProcessConfigStrategy V6 + * @class DeviceGroupsProcessConfigStrategy + * @description Converts the device groups of a v6 application between the config and the manifest. + */ +class DeviceGroupsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Transform azion.config device groups to the v6 manifest format + */ + transformToManifest(deviceGroups: AzionDeviceGroupV6[]) { + if (!Array.isArray(deviceGroups) || deviceGroups.length === 0) { + return; + } + + return deviceGroups.map((deviceGroup) => ({ + name: deviceGroup.name, + user_agent: deviceGroup.userAgent, + })); + } + + /** + * Transform the v6 manifest format back to azion.config device groups + */ + transformToConfig(payload: Array<{ name: string; user_agent: string }>): AzionDeviceGroupV6[] { + if (!Array.isArray(payload) || payload.length === 0) { + return []; + } + + return payload.map((deviceGroup) => ({ + name: deviceGroup.name, + userAgent: deviceGroup.user_agent, + })); + } +} + +export default DeviceGroupsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/schemas/applications/index.ts b/packages/config/src/versions/v6/schemas/applications/index.ts index 5043d090..0517585b 100644 --- a/packages/config/src/versions/v6/schemas/applications/index.ts +++ b/packages/config/src/versions/v6/schemas/applications/index.ts @@ -137,7 +137,7 @@ const createRuleSchema = (isRequestPhase = false) => ({ * Based on v4, checked against the requests of the v6 API: `name` has at most 100 characters in an application * (`ApplicationRequest`) and in a rule (`RequestPhaseRuleRequest`, `ResponsePhaseRuleRequest`). * Cache: `maxAgeSeconds` is between 0 and 31536000 (1 year) and `tieredCache.topology` is not nullable, as in `CacheSettingRequest`. - * TODO: add the remaining resources of an application (device groups). + * Device groups: same constraints as v4 (`DeviceGroupRequest`). */ const applicationsSchema = { type: 'array', @@ -398,6 +398,35 @@ const applicationsSchema = { }, additionalProperties: false, }, + deviceGroups: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 250, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 250 characters", + }, + userAgent: { + type: 'string', + minLength: 1, + maxLength: 512, + pattern: '.*', + errorMessage: "The 'userAgent' field must be a valid regex pattern between 1 and 512 characters", + }, + }, + required: ['name', 'userAgent'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in device group objects', + required: "The 'name' and 'userAgent' fields are required in each device group", + }, + }, + errorMessage: "The 'deviceGroups' field must be an array of device group objects", + }, functionsInstances: { type: 'array', items: { diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 46e846cc..831ef252 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -45,9 +45,18 @@ import type { */ export type AzionFunctionV6 = AzionFunction; +/** + * Device group of an application of the Azion API v6. + */ +export type AzionDeviceGroupV6 = { + /** Device group name */ + name: string; + /** User agent regex pattern */ + userAgent: string; +}; + /** * Application of the Azion API v6. - * TODO: add the remaining resources of an application (device groups). */ export type AzionApplicationV6 = { /** Application name */ @@ -70,6 +79,8 @@ export type AzionApplicationV6 = { rules?: AzionRules; /** Function instances */ functionsInstances?: AzionFunctionInstance[]; + /** Device groups */ + deviceGroups?: AzionDeviceGroupV6[]; }; /** diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 9f83a63e..2a5ef45a 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -281,6 +281,32 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { ).toThrow(); }); }); + + describe('deviceGroups', () => { + it('accepts a device group and requires name and userAgent', () => { + expect(() => + validateConfig(app({ deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'mobile' }] }))).toThrow( + "The 'name' and 'userAgent' fields are required in each device group", + ); + }); + + it('limits the name to 250 characters and the user agent to 512 (DeviceGroupRequest)', () => { + expect(() => + validateConfig(app({ deviceGroups: [{ name: 'a'.repeat(250), userAgent: 'u'.repeat(512) }] })), + ).not.toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a'.repeat(251), userAgent: 'u' }] }))).toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a', userAgent: 'u'.repeat(513) }] }))).toThrow(); + expect(() => validateConfig(app({ deviceGroups: [{ name: '', userAgent: 'u' }] }))).toThrow(); + }); + + it('rejects unknown properties in a device group', () => { + expect(() => validateConfig(app({ deviceGroups: [{ name: 'a', userAgent: 'u', id: 1 }] }))).toThrow( + 'No additional properties are allowed in device group objects', + ); + }); + }); }); describe('validateConfig (v6) workloads, environments and deployments', () => { From 8fb31379b0dd405d48c49f36a72cc7e6b34651c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 10:32:53 -0300 Subject: [PATCH 19/29] feat(config): add the purge to API v6 PurgeRequest only differs from v4 in that each item has at least one character. The wildcard error message now says the asterisk is required. --- packages/config/src/versions/registry.test.ts | 2 +- .../purgeProcessConfigStrategy.test.ts | 88 +++++++++++++++++++ .../purgeProcessConfigStrategy.ts | 62 +++++++++++++ .../src/versions/v6/processStrategy/index.ts | 3 +- .../src/versions/v6/schemas/purge/index.ts | 49 +++++++++++ .../config/src/versions/v6/schemas/schema.ts | 5 +- packages/config/src/versions/v6/types.ts | 15 +++- .../versions/v6/validateConfig/index.test.ts | 60 ++++++++++++- 8 files changed, 277 insertions(+), 7 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/purge/index.ts diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 081384f5..7e870ea8 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -139,7 +139,7 @@ describe('v6 support', () => { it('validates a v6 config and rejects fields the v6 schema does not know yet', () => { expect(() => validateConfig(v6Config)).not.toThrow(); - expect(() => validateConfig({ version: 6, purge: [] })).toThrow(); + expect(() => validateConfig({ version: 6, kv: [] })).toThrow(); }); it('does not accept v6 on the v4 schema nor the other way around', () => { diff --git a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts new file mode 100644 index 00000000..3a4c0286 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts @@ -0,0 +1,88 @@ +import type { AzionConfigV6 } from '../../types'; +import PurgeProcessConfigStrategy from './purgeProcessConfigStrategy'; + +describe('PurgeProcessConfigStrategy (v6)', () => { + let strategy: PurgeProcessConfigStrategy; + + beforeEach(() => { + strategy = new PurgeProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return undefined when there is no purge', () => { + expect(strategy.transformToManifest({ version: 6 })).toBeUndefined(); + expect(strategy.transformToManifest({ version: 6, purge: [] })).toBeUndefined(); + }); + + it('should map a purge to the manifest and default the layer to cache', () => { + const config: AzionConfigV6 = { + version: 6, + purge: [ + { type: 'url', items: ['https://example.com/path'] }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'tiered_cache' }, + { type: 'cachekey', items: ['example.com/path'] }, + ], + }; + + expect(strategy.transformToManifest(config)).toEqual([ + { type: 'url', items: ['https://example.com/path'], layer: 'cache' }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'tiered_cache' }, + { type: 'cachekey', items: ['example.com/path'], layer: 'cache' }, + ]); + }); + + it('should throw when a url item has no protocol', () => { + expect(() => + strategy.transformToManifest({ version: 6, purge: [{ type: 'url', items: ['example.com/path'] }] }), + ).toThrow('The URL must contain the protocol (http:// or https://).'); + }); + + it('should throw when a wildcard item has no asterisk', () => { + expect(() => + strategy.transformToManifest({ + version: 6, + purge: [{ type: 'wildcard', items: ['https://example.com/path'] }], + }), + ).toThrow('The wildcard purge must contain the wildcard character (*).'); + }); + }); + + describe('transformToConfig', () => { + it('should return undefined when the manifest has no purge', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ purge: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.purge).toBeUndefined(); + }); + + it('should map the manifest back to the config and replace an existing purge', () => { + const transformedPayload: AzionConfigV6 = { + version: 6, + purge: [{ type: 'url', items: ['https://example.com/old'] }], + }; + + const result = strategy.transformToConfig( + { purge: [{ type: 'url', items: ['https://example.com/new'] }] }, + transformedPayload, + ); + + expect(result).toEqual([{ type: 'url', items: ['https://example.com/new'], layer: 'cache' }]); + expect(transformedPayload.purge).toEqual(result); + }); + + it('should apply the same item checks as the config', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(() => + strategy.transformToConfig({ purge: [{ type: 'url', items: ['example.com'] }] }, transformedPayload), + ).toThrow('The URL must contain the protocol (http:// or https://).'); + expect(() => + strategy.transformToConfig( + { purge: [{ type: 'wildcard', items: ['https://example.com'] }] }, + transformedPayload, + ), + ).toThrow('The wildcard purge must contain the wildcard character (*).'); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts new file mode 100644 index 00000000..56aedf76 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.ts @@ -0,0 +1,62 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionPurgeV6 } from '../../types'; + +/** + * Checks the items of a purge as the Azion CLI needs them: a `url` carries the protocol and a `wildcard` the asterisk. + */ +function validatePurgeItems(purge: Pick) { + purge.items.forEach((value) => { + if (purge.type === 'url' && !value.includes('http://') && !value.includes('https://')) { + throw new Error('The URL must contain the protocol (http:// or https://).'); + } + + if (purge.type === 'wildcard' && !value.includes('*')) { + throw new Error('The wildcard purge must contain the wildcard character (*).'); + } + }); +} + +/** + * PurgeProcessConfigStrategy V6 + * @class PurgeProcessConfigStrategy + * @description Converts the v6 purge between the config and the manifest. + */ +class PurgeProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.purge) || config.purge.length === 0) { + return; + } + + return config.purge.map((purge) => { + validatePurgeItems(purge); + + return { + type: purge.type, + items: purge.items, + layer: purge.layer ?? 'cache', + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: any, transformedPayload: AzionConfigV6) { + const purgeConfig = payload.purge; + if (!Array.isArray(purgeConfig) || purgeConfig.length === 0) { + return; + } + + transformedPayload.purge = purgeConfig.map((purge: AzionPurgeV6) => { + validatePurgeItems(purge); + + return { + type: purge.type, + items: purge.items, + layer: purge.layer ?? 'cache', + }; + }); + + return transformedPayload.purge; + } +} + +export default PurgeProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index 87666b7a..895580dc 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -7,6 +7,7 @@ import CustomPagesProcessConfigStrategy from './implementations/customPagesProce import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; +import PurgeProcessConfigStrategy from './implementations/purgeProcessConfigStrategy'; import FirewallProcessConfigStrategy from './implementations/secure/firewallProcessConfigStrategy'; import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; @@ -29,7 +30,7 @@ function factoryProcessContext() { processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); processConfigContext.setStrategy('workloads', new WorkloadProcessConfigStrategy()); - // TODO: register the other v6 strategies (setStrategy) as the v6 resources are defined + processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/purge/index.ts b/packages/config/src/versions/v6/schemas/purge/index.ts new file mode 100644 index 00000000..ded034dd --- /dev/null +++ b/packages/config/src/versions/v6/schemas/purge/index.ts @@ -0,0 +1,49 @@ +/** + * Schema of the v6 purge. + * Based on v4, checked against `PurgeRequest` (`POST /workspace/purge/{purge_type}`): each item has at least 1 character + * and `layer` is `cache` or `tiered_cache`. The `uri` format of the items is not enforced here: a `cachekey` item is not a URI, + * and the strategy already checks the protocol of a `url` and the asterisk of a `wildcard`. + */ +const purgeSchema = { + type: 'array', + items: { + type: 'object', + properties: { + type: { + type: 'string', + enum: ['url', 'cachekey', 'wildcard'], + errorMessage: "The 'type' field must be either 'url', 'cachekey' or 'wildcard'.", + }, + items: { + type: 'array', + minItems: 1, + items: { + type: 'string', + minLength: 1, + errorMessage: { + type: "Each item in 'items' must be a string.", + minLength: "Each item in 'items' must have at least 1 character.", + }, + }, + errorMessage: { + type: "The 'items' field must be an array of strings.", + minItems: 'The purge items array cannot be empty. At least one item must be specified.', + }, + }, + layer: { + type: 'string', + enum: ['cache', 'tiered_cache'], + errorMessage: "The 'layer' field must be either 'cache' or 'tiered_cache'.", + }, + }, + required: ['type', 'items'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in purge items.', + required: "The 'type and items' fields are required in each purge item.", + }, + }, + errorMessage: "The 'purge' field must be an array of purge items.", +}; + +export default purgeSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index 6501a57b..3138a26f 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -7,13 +7,13 @@ import environmentsSchema from './environments'; import firewallSchema from './firewall'; import functionsSchema from './functions'; import networkListSchema from './networkList'; +import purgeSchema from './purge'; import storageSchema from './storage'; import wafSchema from './waf'; import workloadsSchema from './workloads'; /** * JSON Schema of the v6 config. - * TODO: only `version`, `build`, `functions`, `storage`, `connectors`, `customPages`, `networkList`, `waf`, `firewall`, `applications`, `workloads`, `environments` and `deployments` are accepted until the schemas of the other v6 resources are defined. */ const azionConfigSchema = { $id: 'azionConfig', @@ -34,11 +34,12 @@ const azionConfigSchema = { workloads: workloadsSchema, environments: environmentsSchema, deployments: deploymentsSchema, + purge: purgeSchema, }, additionalProperties: false, errorMessage: { additionalProperties: - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 831ef252..285300fb 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -391,9 +391,20 @@ export type AzionWafV6 = { }; }; +/** + * Purge of the Azion API v6. + */ +export type AzionPurgeV6 = { + /** Items to be purged */ + items: string[]; + /** Cache layer to be purged */ + layer?: 'cache' | 'tiered_cache'; + /** Purge type */ + type: 'url' | 'cachekey' | 'wildcard'; +}; + /** * Config of the Azion API v6. - * TODO: structure placeholder. Add the remaining v6 resources once their schemas are defined. */ export type AzionConfigV6 = { /** Azion API version this config targets. */ @@ -422,4 +433,6 @@ export type AzionConfigV6 = { environments?: AzionEnvironmentV6[]; /** Deployments */ deployments?: AzionDeploymentV6[]; + /** Purge configurations */ + purge?: AzionPurgeV6[]; }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 2a5ef45a..cae8ec3e 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -107,8 +107,8 @@ describe('validateConfig (v6)', () => { }); it('rejects properties the v6 schema does not know yet', () => { - expect(() => validateConfig({ version: 6, purge: [] })).toThrow( - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments', + expect(() => validateConfig({ version: 6, kv: [] })).toThrow( + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', ); }); @@ -1300,3 +1300,59 @@ describe('validateConfig (v6) customPages', () => { ); }); }); + +describe('validateConfig (v6) purge', () => { + describe('purge', () => { + it('accepts the three purge types and both layers', () => { + expect(() => + validateConfig({ + version: 6, + purge: [ + { type: 'url', items: ['https://example.com/a'], layer: 'cache' }, + { type: 'cachekey', items: ['example.com/a'], layer: 'tiered_cache' }, + { type: 'wildcard', items: ['https://example.com/*'] }, + ], + }), + ).not.toThrow(); + }); + + it('requires type and items', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url' }] })).toThrow( + "The 'type and items' fields are required in each purge item.", + ); + expect(() => validateConfig({ version: 6, purge: [{ items: ['a'] }] })).toThrow( + "The 'type and items' fields are required in each purge item.", + ); + }); + + it('rejects an unknown type or layer', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'tag', items: ['a'] }] })).toThrow( + "The 'type' field must be either 'url', 'cachekey' or 'wildcard'.", + ); + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: ['a'], layer: 'edge' }] })).toThrow( + "The 'layer' field must be either 'cache' or 'tiered_cache'.", + ); + }); + + it('requires at least one item and rejects empty items (PurgeRequest)', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: [] }] })).toThrow( + 'The purge items array cannot be empty. At least one item must be specified.', + ); + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: [''] }] })).toThrow( + "Each item in 'items' must have at least 1 character.", + ); + }); + + it('rejects unknown properties in a purge item', () => { + expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: ['a'], name: 'x' }] })).toThrow( + 'No additional properties are allowed in purge items.', + ); + }); + + it('rejects a purge that is not an array', () => { + expect(() => validateConfig({ version: 6, purge: {} })).toThrow( + "The 'purge' field must be an array of purge items.", + ); + }); + }); +}); From 72dabdbe862ccd8e285ad28ca08de0c4d2a928d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 14:35:24 -0300 Subject: [PATCH 20/29] chore: add the changeset for the API v6 config Bump @aziontech/config and @aziontech/presets as minor for the v6 config support. --- .changeset/config-api-v6.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .changeset/config-api-v6.md diff --git a/.changeset/config-api-v6.md b/.changeset/config-api-v6.md new file mode 100644 index 00000000..6d52826f --- /dev/null +++ b/.changeset/config-api-v6.md @@ -0,0 +1,9 @@ +--- +'@aziontech/config': minor +'@aziontech/presets': minor +--- + +Support the Azion API v6 config in the same packages. + +- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments`, `deployments` and workloads with `bindings` (the environment and deployment policies are required, and a binding references them by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. +- `@aziontech/presets`: the `javascript`, `react`, `opennextjs` and `eleventy` presets now provide their v6 config in `configs[6]`. `config` remains the default (v4) config. From f6ea66f372ee8e0127205046432f870722b97854 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 4 Nov 2026 14:48:13 -0300 Subject: [PATCH 21/29] security(deps): remediate pnpm audit vulnerabilities Override handlebars, fast-uri, qs, minimatch and glob to their patched versions and bump vite to 7.3.7 (kept on v7 with an override). deepmerge has no patched version (GHSA-gcqx-w48m-w2h4, low) and is only reached through jest-config, so the advisory is ignored until upstream releases a fix. --- package.json | 17 +- packages/vite-config/package.json | 2 +- pnpm-lock.yaml | 411 ++++++++++++++---------------- 3 files changed, 212 insertions(+), 218 deletions(-) diff --git a/package.json b/package.json index 9da3131d..3b32e649 100644 --- a/package.json +++ b/package.json @@ -58,15 +58,20 @@ "prettier": "^3.9.6", "typescript": "^5.9.3", "typescript-eslint": "^8.69.0", - "vite": "^7.3.6", + "vite": "^7.3.7", "vite-plugin-dts": "^4.5.4" }, "pnpm": { + "auditConfig": { + "ignoreGhsas": [ + "GHSA-gcqx-w48m-w2h4" + ] + }, "overrides": { "lodash": ">=4.18.0", "postcss": ">=8.5.18", - "fast-uri": ">=4.1.5", - "qs": ">=6.15.2", + "fast-uri": ">=4.2.3", + "qs": ">=6.16.1", "esbuild": ">=0.28.1", "source-map-js": ">=1.2.2", "brace-expansion@1": "^1.1.17", @@ -77,7 +82,11 @@ "js-yaml@3>argparse": "^2.0.1", "@rushstack/ts-command-line>argparse": "^2.0.1", "@babel/core": ">=7.29.6", - "@babel/plugin-transform-modules-systemjs": ">=7.29.4" + "@babel/plugin-transform-modules-systemjs": ">=7.29.4", + "handlebars": ">=4.7.10", + "vite@7": "^7.3.7", + "minimatch@<11.0.1": ">=11.0.1", + "glob@<14.0.2": ">=14.0.2" } }, "workspaces": [ diff --git a/packages/vite-config/package.json b/packages/vite-config/package.json index aa9c735d..c122fd40 100644 --- a/packages/vite-config/package.json +++ b/packages/vite-config/package.json @@ -19,7 +19,7 @@ "src" ], "peerDependencies": { - "vite": "^7.3.6", + "vite": "^7.3.7", "vite-plugin-dts": "^4.5.4" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0ab510da..7c213884 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,8 +7,8 @@ settings: overrides: lodash: '>=4.18.0' postcss: '>=8.5.18' - fast-uri: '>=4.1.5' - qs: '>=6.15.2' + fast-uri: '>=4.2.3' + qs: '>=6.16.1' esbuild: '>=0.28.1' source-map-js: '>=1.2.2' brace-expansion@1: ^1.1.17 @@ -20,6 +20,10 @@ overrides: '@rushstack/ts-command-line>argparse': ^2.0.1 '@babel/core': '>=7.29.6' '@babel/plugin-transform-modules-systemjs': '>=7.29.4' + handlebars: '>=4.7.10' + vite@7: ^7.3.7 + minimatch@<11.0.1: '>=11.0.1' + glob@<14.0.2: '>=14.0.2' importers: @@ -65,11 +69,11 @@ importers: specifier: ^8.69.0 version: 8.69.0(eslint@10.10.0(jiti@2.6.1))(typescript@5.9.3) vite: - specifier: ^7.3.6 - version: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + specifier: ^7.3.7 + version: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) vite-plugin-dts: specifier: ^4.5.4 - version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)) + version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)) packages/ai: devDependencies: @@ -138,7 +142,7 @@ importers: version: 1.3.8 babel-loader: specifier: ^10.1.1 - version: 10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)) + version: 10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) browserify-zlib: specifier: ^0.2.0 version: 0.2.0 @@ -183,7 +187,7 @@ importers: version: 2.0.12 ts-loader: specifier: ^9.6.2 - version: 9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)) + version: 9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) unenv: specifier: 2.0.0-rc.24 version: 2.0.0-rc.24 @@ -198,7 +202,7 @@ importers: version: 1.1.2 webpack: specifier: ^5.110.3 - version: 5.110.3(esbuild@0.28.2) + version: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) devDependencies: '@aziontech/vite-config': specifier: workspace:* @@ -348,7 +352,7 @@ importers: version: 10.9.2(@types/node@22.20.1)(typescript@5.9.3) webpack: specifier: ^5.110.3 - version: 5.110.3(esbuild@0.28.2) + version: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) packages/cookies: devDependencies: @@ -456,7 +460,7 @@ importers: version: 0.2.17 webpack: specifier: ^5.110.3 - version: 5.110.3 + version: 5.110.3(lightningcss@1.33.0) devDependencies: '@aziontech/vite-config': specifier: workspace:* @@ -631,11 +635,11 @@ importers: packages/vite-config: dependencies: vite: - specifier: ^7.3.6 - version: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + specifier: ^7.3.7 + version: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) vite-plugin-dts: specifier: ^4.5.4 - version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)) + version: 4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)) packages/wasm-image-processor: devDependencies: @@ -1658,9 +1662,8 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} - '@isaacs/cliui@8.0.2': - resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} - engines: {node: '>=12'} + '@isaacs/nonrecursive-glob-match@1.0.3': + resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==} '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} @@ -1918,10 +1921,6 @@ packages: resolution: {integrity: sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==} engines: {node: '>=14.18.0'} - '@pkgjs/parseargs@0.11.0': - resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} - engines: {node: '>=14'} - '@pkgr/core@0.3.6': resolution: {integrity: sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==} engines: {node: ^14.18.0 || >=16.0.0} @@ -2515,10 +2514,6 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} - ansi-regex@6.3.0: - resolution: {integrity: sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==} - engines: {node: '>=12'} - ansi-styles@3.2.1: resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} engines: {node: '>=4'} @@ -2531,10 +2526,6 @@ packages: resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} engines: {node: '>=10'} - ansi-styles@6.2.3: - resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} - engines: {node: '>=12'} - anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -2612,9 +2603,6 @@ packages: peerDependencies: '@babel/core': '>=7.29.6' - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -2627,9 +2615,6 @@ packages: engines: {node: '>=6.0.0'} hasBin: true - brace-expansion@2.1.7: - resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} - brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -2883,9 +2868,6 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} - eastasianwidth@0.2.0: - resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - electron-to-chromium@1.5.422: resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==} @@ -2896,9 +2878,6 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} - emoji-regex@9.2.2: - resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} - enhanced-resolve@5.24.5: resolution: {integrity: sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==} engines: {node: '>=10.13.0'} @@ -3044,8 +3023,8 @@ packages: fast-string-width@3.0.2: resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} - fast-uri@4.2.1: - resolution: {integrity: sha512-TmHQgewjHtMq1E5QKA0tOE0yeYGQs25KZC/ziJpubRtWI15W92e6vPFydWOeZBVROSHBYw/QhD9d5OefdD6LDg==} + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} fast-wrap-ansi@0.2.2: resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} @@ -3098,10 +3077,6 @@ packages: resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} engines: {node: '>= 0.4'} - foreground-child@3.3.1: - resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} - engines: {node: '>=14'} - fraction.js@5.3.4: resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} @@ -3155,13 +3130,8 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob@10.5.0: - resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me - hasBin: true - - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + glob@14.0.3: + resolution: {integrity: sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==} engines: {node: 18 || 20 || >=22} global-directory@4.0.1: @@ -3179,8 +3149,8 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -3358,9 +3328,6 @@ packages: resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} engines: {node: '>=8'} - jackspeak@3.4.3: - resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} - javascript-natural-sort@0.7.1: resolution: {integrity: sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==} @@ -3569,6 +3536,76 @@ packages: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} @@ -3632,9 +3669,6 @@ packages: lodash.upperfirst@4.3.1: resolution: {integrity: sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==} - lru-cache@10.4.3: - resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} - lru-cache@11.5.2: resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} engines: {node: 20 || >=22} @@ -3693,17 +3727,9 @@ packages: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} - minimatch@10.2.3: - resolution: {integrity: sha512-Rwi3pnapEqirPSbWbrZaa6N3nmqq4Xer/2XooiOKyV3q12ML06f7MOuc5DVH8ONZIFhwIYQ3yzPH4nt7iWHaTg==} - engines: {node: 18 || 20 || >=22} - - minimatch@10.2.6: - resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} - engines: {node: 18 || 20 || >=22} - - minimatch@9.0.9: - resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} - engines: {node: '>=16 || 14 >=14.17'} + minimatch@11.0.4: + resolution: {integrity: sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==} + engines: {node: 20 || >=22} minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -3887,9 +3913,6 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} - package-json-from-dist@1.0.1: - resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} - package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} @@ -3930,12 +3953,8 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - path-scurry@1.11.1: - resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} - engines: {node: '>=16 || 14 >=14.18'} - - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} engines: {node: 18 || 20 || >=22} pathe@2.0.3: @@ -4023,8 +4042,8 @@ packages: resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} engines: {node: '>=20'} - qs@6.16.0: - resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} quansync@0.2.11: @@ -4210,10 +4229,6 @@ packages: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} - string-width@5.1.2: - resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} - engines: {node: '>=12'} - string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} @@ -4221,10 +4236,6 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} - strip-ansi@7.2.0: - resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} - engines: {node: '>=12'} - strip-bom@3.0.0: resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} engines: {node: '>=4'} @@ -4467,13 +4478,13 @@ packages: resolution: {integrity: sha512-d4sOM8M/8z7vRXHHq/ebbblfaxENjogAAekcfcDCCwAyvGqnPrc7f4NZbvItS+g4WTgerW0xDwSz5qz11JT3vg==} peerDependencies: typescript: '*' - vite: '*' + vite: ^7.3.7 peerDependenciesMeta: vite: optional: true - vite@7.3.6: - resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==} + vite@7.3.7: + resolution: {integrity: sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -4565,10 +4576,6 @@ packages: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} - wrap-ansi@8.1.0: - resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} - engines: {node: '>=12'} - write-file-atomic@5.0.1: resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -5760,7 +5767,7 @@ snapshots: dependencies: '@eslint/object-schema': 3.0.5 debug: 4.4.3 - minimatch: 10.2.6 + minimatch: 11.0.4 transitivePeerDependencies: - supports-color @@ -5799,14 +5806,7 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} - '@isaacs/cliui@8.0.2': - dependencies: - string-width: 5.1.2 - string-width-cjs: string-width@4.2.3 - strip-ansi: 7.2.0 - strip-ansi-cjs: strip-ansi@6.0.1 - wrap-ansi: 8.1.0 - wrap-ansi-cjs: wrap-ansi@7.0.0 + '@isaacs/nonrecursive-glob-match@1.0.3': {} '@istanbuljs/load-nyc-config@1.1.0': dependencies: @@ -5924,7 +5924,7 @@ snapshots: chalk: 4.1.2 collect-v8-coverage: 1.0.3 exit-x: 0.2.2 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 istanbul-lib-coverage: 3.2.2 istanbul-lib-instrument: 6.0.3 @@ -6071,7 +6071,7 @@ snapshots: '@rushstack/terminal': 0.24.3(@types/node@22.20.1) '@rushstack/ts-command-line': 5.3.13(@types/node@22.20.1) diff: 8.0.4 - minimatch: 10.2.3 + minimatch: 11.0.4 resolve: 1.22.12 semver: 7.7.4 source-map: 0.6.1 @@ -6176,9 +6176,6 @@ snapshots: tslib: 2.8.1 webcrypto-core: 1.9.2 - '@pkgjs/parseargs@0.11.0': - optional: true - '@pkgr/core@0.3.6': {} '@pnpm/deps.graph-sequencer@1100.0.1': {} @@ -6471,7 +6468,7 @@ snapshots: '@typescript-eslint/types': 8.69.0 '@typescript-eslint/visitor-keys': 8.69.0 debug: 4.4.3 - minimatch: 10.2.6 + minimatch: 11.0.4 semver: 7.8.5 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -6604,7 +6601,7 @@ snapshots: '@vue/compiler-vue2': 2.7.16 '@vue/shared': 3.5.42 alien-signals: 0.4.14 - minimatch: 9.0.9 + minimatch: 11.0.4 muggle-string: 0.4.1 path-browserify: 1.0.1 optionalDependencies: @@ -6743,14 +6740,14 @@ snapshots: ajv@8.18.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 4.2.1 + fast-uri: 4.2.3 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 4.2.1 + fast-uri: 4.2.3 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -6762,8 +6759,6 @@ snapshots: ansi-regex@5.0.1: {} - ansi-regex@6.3.0: {} - ansi-styles@3.2.1: dependencies: color-convert: 1.9.3 @@ -6774,8 +6769,6 @@ snapshots: ansi-styles@5.2.0: {} - ansi-styles@6.2.3: {} - anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -6817,12 +6810,12 @@ snapshots: transitivePeerDependencies: - supports-color - babel-loader@10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)): + babel-loader@10.1.1(@babel/core@7.29.7)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: '@babel/core': 7.29.7 find-up: 5.0.0 optionalDependencies: - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) babel-plugin-istanbul@8.0.0: dependencies: @@ -6887,18 +6880,12 @@ snapshots: babel-plugin-jest-hoist: 30.5.0 babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) - balanced-match@1.0.2: {} - balanced-match@4.0.4: {} base64-js@1.5.1: {} baseline-browser-mapping@2.11.21: {} - brace-expansion@2.1.7: - dependencies: - balanced-match: 1.0.2 - brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -7119,16 +7106,12 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 - eastasianwidth@0.2.0: {} - electron-to-chromium@1.5.422: {} emittery@0.13.1: {} emoji-regex@8.0.0: {} - emoji-regex@9.2.2: {} - enhanced-resolve@5.24.5: dependencies: graceful-fs: 4.2.11 @@ -7233,7 +7216,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 10.2.6 + minimatch: 11.0.4 natural-compare: 1.4.0 optionator: 0.9.4 optionalDependencies: @@ -7311,7 +7294,7 @@ snapshots: dependencies: fast-string-truncated-width: 3.0.3 - fast-uri@4.2.1: {} + fast-uri@4.2.3: {} fast-wrap-ansi@0.2.2: dependencies: @@ -7367,11 +7350,6 @@ snapshots: dependencies: is-callable: 1.2.7 - foreground-child@3.3.1: - dependencies: - cross-spawn: 7.0.6 - signal-exit: 4.1.0 - fraction.js@5.3.4: {} fs-extra@11.3.6: @@ -7423,20 +7401,11 @@ snapshots: dependencies: is-glob: 4.0.3 - glob@10.5.0: - dependencies: - foreground-child: 3.3.1 - jackspeak: 3.4.3 - minimatch: 9.0.9 - minipass: 7.1.3 - package-json-from-dist: 1.0.1 - path-scurry: 1.11.1 - - glob@13.0.6: + glob@14.0.3: dependencies: - minimatch: 10.2.6 + minimatch: 11.0.4 minipass: 7.1.3 - path-scurry: 2.0.2 + path-scurry: 3.0.0 global-directory@4.0.1: dependencies: @@ -7448,7 +7417,7 @@ snapshots: graceful-fs@4.2.11: {} - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -7607,12 +7576,6 @@ snapshots: html-escaper: 2.0.2 istanbul-lib-report: 3.0.1 - jackspeak@3.4.3: - dependencies: - '@isaacs/cliui': 8.0.2 - optionalDependencies: - '@pkgjs/parseargs': 0.11.0 - javascript-natural-sort@0.7.1: {} jest-changed-files@30.5.1: @@ -7677,7 +7640,7 @@ snapshots: chalk: 4.1.2 ci-info: 4.4.0 deepmerge: 4.3.1 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 jest-circus: 30.5.1 jest-docblock: 30.5.0 @@ -7854,7 +7817,7 @@ snapshots: cjs-module-lexer: 2.2.1 collect-v8-coverage: 1.0.3 es-module-lexer: 2.3.2 - glob: 13.0.6 + glob: 14.0.3 graceful-fs: 4.2.11 jest-haste-map: 30.5.1 jest-message-util: 30.5.1 @@ -8007,6 +7970,56 @@ snapshots: prelude-ls: 1.2.1 type-check: 0.4.0 + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + optional: true + lines-and-columns@1.2.4: {} load-json-file@4.0.0: @@ -8063,8 +8076,6 @@ snapshots: lodash.upperfirst@4.3.1: {} - lru-cache@10.4.3: {} - lru-cache@11.5.2: {} lru-cache@5.1.1: @@ -8115,37 +8126,33 @@ snapshots: mimic-fn@2.1.0: {} - minimatch@10.2.3: - dependencies: - brace-expansion: 5.0.12 - - minimatch@10.2.6: + minimatch@11.0.4: dependencies: + '@isaacs/nonrecursive-glob-match': 1.0.3 brace-expansion: 5.0.12 - minimatch@9.0.9: - dependencies: - brace-expansion: 2.1.7 - minimist@1.2.8: {} - minimizer-webpack-plugin@5.10.0(esbuild@0.28.2)(webpack@5.110.3(esbuild@0.28.2)): + minimizer-webpack-plugin@5.10.0(esbuild@0.28.2)(lightningcss@1.33.0)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 terser: 5.51.2 - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) optionalDependencies: esbuild: 0.28.2 + lightningcss: 1.33.0 - minimizer-webpack-plugin@5.10.0(webpack@5.110.3): + minimizer-webpack-plugin@5.10.0(lightningcss@1.33.0)(webpack@5.110.3(lightningcss@1.33.0)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 terser: 5.51.2 - webpack: 5.110.3 + webpack: 5.110.3(lightningcss@1.33.0) + optionalDependencies: + lightningcss: 1.33.0 minipass@7.1.3: {} @@ -8246,8 +8253,6 @@ snapshots: p-try@2.2.0: {} - package-json-from-dist@1.0.1: {} - package-manager-detector@1.9.0: {} pako@1.0.11: {} @@ -8280,12 +8285,7 @@ snapshots: path-parse@1.0.7: {} - path-scurry@1.11.1: - dependencies: - lru-cache: 10.4.3 - minipass: 7.1.3 - - path-scurry@2.0.2: + path-scurry@3.0.0: dependencies: lru-cache: 11.5.2 minipass: 7.1.3 @@ -8362,7 +8362,7 @@ snapshots: dependencies: hookified: 2.2.0 - qs@6.16.0: + qs@6.17.1: dependencies: es-define-property: 1.0.1 side-channel: 1.1.1 @@ -8577,12 +8577,6 @@ snapshots: is-fullwidth-code-point: 3.0.0 strip-ansi: 6.0.1 - string-width@5.1.2: - dependencies: - eastasianwidth: 0.2.0 - emoji-regex: 9.2.2 - strip-ansi: 7.2.0 - string_decoder@1.3.0: dependencies: safe-buffer: 5.2.1 @@ -8591,10 +8585,6 @@ snapshots: dependencies: ansi-regex: 5.0.1 - strip-ansi@7.2.0: - dependencies: - ansi-regex: 6.3.0 - strip-bom@3.0.0: {} strip-bom@4.0.0: {} @@ -8633,8 +8623,8 @@ snapshots: test-exclude@7.0.2: dependencies: '@istanbuljs/schema': 0.1.6 - glob: 10.5.0 - minimatch: 10.2.6 + glob: 14.0.3 + minimatch: 11.0.4 text-extensions@2.4.0: {} @@ -8665,7 +8655,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 jest: 30.5.1(@types/node@22.20.1)(ts-node@10.9.2(@types/node@22.20.1)(typescript@5.9.3)) json5: 2.2.3 lodash.memoize: 4.1.2 @@ -8682,13 +8672,13 @@ snapshots: esbuild: 0.28.2 jest-util: 30.5.1 - ts-loader@9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)): + ts-loader@9.6.2(typescript@5.9.3)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)): dependencies: chalk: 4.1.2 picomatch: 4.0.7 source-map: 0.7.6 typescript: 5.9.3 - webpack: 5.110.3(esbuild@0.28.2) + webpack: 5.110.3(esbuild@0.28.2)(lightningcss@1.33.0) ts-node@10.9.2(@types/node@22.20.1)(typescript@5.9.3): dependencies: @@ -8801,7 +8791,7 @@ snapshots: url@0.11.4: dependencies: punycode: 1.4.1 - qs: 6.16.0 + qs: 6.17.1 util-deprecate@1.0.2: {} @@ -8821,7 +8811,7 @@ snapshots: '@types/istanbul-lib-coverage': 2.0.6 convert-source-map: 2.0.0 - vite-plugin-dts@4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1)): + vite-plugin-dts@4.5.4(@types/node@22.20.1)(rollup@4.63.1)(typescript@5.9.3)(vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1)): dependencies: '@microsoft/api-extractor': 7.59.0(@types/node@22.20.1) '@rollup/pluginutils': 5.4.0(rollup@4.63.1) @@ -8834,13 +8824,13 @@ snapshots: magic-string: 0.30.21 typescript: 5.9.3 optionalDependencies: - vite: 7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1) + vite: 7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1) transitivePeerDependencies: - '@types/node' - rollup - supports-color - vite@7.3.6(@types/node@22.20.1)(jiti@2.6.1)(terser@5.51.2)(yaml@2.9.1): + vite@7.3.7(@types/node@22.20.1)(jiti@2.6.1)(lightningcss@1.33.0)(terser@5.51.2)(yaml@2.9.1): dependencies: esbuild: 0.28.2 fdir: 6.5.0(picomatch@4.0.7) @@ -8852,6 +8842,7 @@ snapshots: '@types/node': 22.20.1 fsevents: 2.3.3 jiti: 2.6.1 + lightningcss: 1.33.0 terser: 5.51.2 yaml: 2.9.1 @@ -8875,7 +8866,7 @@ snapshots: webpack-sources@3.5.1: {} - webpack@5.110.3: + webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0): dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 @@ -8890,7 +8881,7 @@ snapshots: events: 3.3.0 graceful-fs: 4.2.11 mime-db: 1.54.0 - minimizer-webpack-plugin: 5.10.0(webpack@5.110.3) + minimizer-webpack-plugin: 5.10.0(esbuild@0.28.2)(lightningcss@1.33.0)(webpack@5.110.3(esbuild@0.28.2)(lightningcss@1.33.0)) neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.3 @@ -8914,7 +8905,7 @@ snapshots: - svgo - uglify-js - webpack@5.110.3(esbuild@0.28.2): + webpack@5.110.3(lightningcss@1.33.0): dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 @@ -8929,7 +8920,7 @@ snapshots: events: 3.3.0 graceful-fs: 4.2.11 mime-db: 1.54.0 - minimizer-webpack-plugin: 5.10.0(esbuild@0.28.2)(webpack@5.110.3(esbuild@0.28.2)) + minimizer-webpack-plugin: 5.10.0(lightningcss@1.33.0)(webpack@5.110.3(lightningcss@1.33.0)) neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.3 @@ -8982,12 +8973,6 @@ snapshots: string-width: 4.2.3 strip-ansi: 6.0.1 - wrap-ansi@8.1.0: - dependencies: - ansi-styles: 6.2.3 - string-width: 5.1.2 - strip-ansi: 7.2.0 - write-file-atomic@5.0.1: dependencies: imurmurhash: 0.1.4 From 954437b9ac0431996d8e20da1657edcce4ce9ef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Thu, 5 Nov 2026 17:39:37 -0300 Subject: [PATCH 22/29] feat(config): use the workload deployments in API v6 The production OpenAPI has no top-level Deployments API, so the deployments are the ones of the workload again: workloads[].deployments with the strategy (application, firewall and custom page by name or id) and a workload_name in each manifest workload_deployments item. A binding references an environment and a deployment of its own workload. Removes the deployments key, its bindingPolicy and strategyDefaults, and updates the v6 presets. --- .../config/src/versions/accessors.test.ts | 1 - packages/config/src/versions/registry.test.ts | 2 +- packages/config/src/versions/v6/constants.ts | 2 +- packages/config/src/versions/v6/index.ts | 6 +- .../deploymentProcessConfigStrategy.test.ts | 96 --------- .../deploymentProcessConfigStrategy.ts | 68 ------ ...adDeploymentsProcessConfigStrategy.test.ts | 195 ++++++++++++++++++ ...orkloadDeploymentsProcessConfigStrategy.ts | 90 ++++++++ .../workloadProcessConfigStrategy.test.ts | 39 +++- .../workloadProcessConfigStrategy.ts | 10 +- .../src/versions/v6/processStrategy/index.ts | 4 +- .../versions/v6/schemas/deployments/index.ts | 68 ------ .../config/src/versions/v6/schemas/schema.ts | 4 +- .../versions/v6/schemas/workloads/index.ts | 86 +++++++- packages/config/src/versions/v6/types.ts | 49 +++-- .../versions/v6/validateConfig/index.test.ts | 87 +++++--- packages/presets/src/presets/configs.test.ts | 19 +- .../presets/src/presets/eleventy/config.v6.ts | 20 +- .../src/presets/javascript/config.v6.ts | 20 +- .../src/presets/opennextjs/config.v6.ts | 20 +- .../presets/src/presets/react/config.v6.ts | 20 +- 21 files changed, 565 insertions(+), 341 deletions(-) delete mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts delete mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts delete mode 100644 packages/config/src/versions/v6/schemas/deployments/index.ts diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index aa196c50..bd3a6166 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -82,7 +82,6 @@ describe('version accessors', () => { 'connectors', 'functions', 'environments', - 'deployments', ]); }); diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 7e870ea8..1d5acd7d 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -156,8 +156,8 @@ describe('v6 support', () => { firewall: [], custom_pages: [], environments: [], - deployments: [], workloads: [], + workload_deployments: [], }); }); diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts index 7c25f8f7..c38e8c5f 100644 --- a/packages/config/src/versions/v6/constants.ts +++ b/packages/config/src/versions/v6/constants.ts @@ -110,7 +110,7 @@ export const ENVIRONMENT_BRANCH_TRACKING_MODES = ['branch_is', 'branch_starts_wi export const DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls'] as const; -export const DEPLOYMENT_BINDING_POLICIES = ['STRICT', 'FLEXIBLE'] as const; +export const WORKLOAD_DEPLOYMENT_STRATEGY_TYPES = ['default'] as const; export const WORKLOADS_ACCESS_TYPES = ['read_only', 'read_write', 'restricted'] as const; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts index 68d458ef..ccc0f1c3 100644 --- a/packages/config/src/versions/v6/index.ts +++ b/packages/config/src/versions/v6/index.ts @@ -12,9 +12,9 @@ const accessors: ConfigVersionAccessors = { const storage = (config as AzionConfigV6).storage?.[0]; return storage ? { bucket: storage.name, prefix: storage.prefix ?? '' } : undefined; }, - // the keys of a preset that only serve an application, which a firewall-only project does not have. The environments - // and the deployments only exist to bind a workload to an application, so they go along with the workloads - firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments', 'deployments'], + // the keys of a preset that only serve an application, which a firewall-only project does not have. The + // environments only exist to bind a workload to an application, so they go along with the workloads + firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments'], }; // v6 has its own AzionConfig type, which is not assignable to the default (v4) one used by the shared contract diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts deleted file mode 100644 index a2f53993..00000000 --- a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { AzionConfigV6 } from '../../types'; -import DeploymentProcessConfigStrategy from './deploymentProcessConfigStrategy'; - -describe('DeploymentProcessConfigStrategy (v6)', () => { - let strategy: DeploymentProcessConfigStrategy; - - beforeEach(() => { - strategy = new DeploymentProcessConfigStrategy(); - }); - - describe('transformToManifest', () => { - it('should return an empty array when there are no deployments', () => { - expect(strategy.transformToManifest({ version: 6 })).toEqual([]); - }); - - it('should write the binding policy and apply the defaults the API requires to the other fields', () => { - expect( - strategy.transformToManifest({ - version: 6, - deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], - }), - ).toEqual([ - { - name: 'default-deployment', - description: null, - binding_policy: 'FLEXIBLE', - strategy_defaults: {}, - }, - ]); - }); - - it('should write the binding policy that the config declares', () => { - const policies = (['STRICT', 'FLEXIBLE'] as const).map( - (bindingPolicy) => - strategy.transformToManifest({ - version: 6, - deployments: [{ name: 'default-deployment', bindingPolicy }], - })?.[0].binding_policy, - ); - - expect(policies).toEqual(['STRICT', 'FLEXIBLE']); - }); - - it('should map every field of the deployment to the manifest', () => { - const [deployment] = strategy.transformToManifest({ - version: 6, - deployments: [ - { - name: 'default-deployment', - description: 'Default', - bindingPolicy: 'STRICT', - deploymentPolicy: 'single_version', - strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, - }, - ], - }); - - expect(deployment).toEqual({ - name: 'default-deployment', - description: 'Default', - binding_policy: 'STRICT', - strategy_defaults: { skew_protection: { enabled: true, default_ttl_seconds: 3600 } }, - deployment_policy: 'single_version', - }); - }); - }); - - describe('transformToConfig', () => { - it('should not set deployments when the manifest has none', () => { - const transformedPayload: AzionConfigV6 = { version: 6 }; - - expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); - expect(transformedPayload.deployments).toBeUndefined(); - }); - - it('should round trip a deployment through the manifest', () => { - const config: AzionConfigV6 = { - version: 6, - deployments: [ - { - name: 'default-deployment', - description: 'Default', - bindingPolicy: 'STRICT', - deploymentPolicy: 'single_version', - strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, - }, - ], - }; - const transformedPayload: AzionConfigV6 = { version: 6 }; - - strategy.transformToConfig({ deployments: strategy.transformToManifest(config) }, transformedPayload); - - expect(transformedPayload.deployments).toEqual(config.deployments); - }); - }); -}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts deleted file mode 100644 index 9670622c..00000000 --- a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts +++ /dev/null @@ -1,68 +0,0 @@ -import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; -import type { AzionConfigV6, AzionDeploymentV6 } from '../../types'; - -/** - * DeploymentProcessConfigStrategy - * @class DeploymentProcessConfigStrategy - * @description Converts the v6 deployments between the config and the manifest. - * The creation of a deployment requires `binding_policy`, which the config must declare. The replacement of a - * deployment also requires `description` and `strategy_defaults`, so the manifest defaults them to no description and - * no skew protection. - * The application a deployment serves is not part of it: the Azion CLI sets it when it creates a release. - */ -class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { - transformToManifest(config: AzionConfigV6) { - if (!Array.isArray(config?.deployments) || config.deployments.length === 0) { - return []; - } - - return config.deployments.map((deployment: AzionDeploymentV6) => { - const skewProtection = deployment.strategyDefaults?.skewProtection; - - return { - name: deployment.name, - description: deployment.description ?? null, - binding_policy: deployment.bindingPolicy, - strategy_defaults: skewProtection - ? { - skew_protection: { - enabled: skewProtection.enabled, - default_ttl_seconds: skewProtection.defaultTtlSeconds, - }, - } - : {}, - ...(deployment.deploymentPolicy && { deployment_policy: deployment.deploymentPolicy }), - }; - }); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToConfig(payload: { deployments?: any[] }, transformedPayload: AzionConfigV6) { - if (!Array.isArray(payload?.deployments) || payload.deployments.length === 0) { - return; - } - - transformedPayload.deployments = payload.deployments.map((deployment) => { - const skewProtection = deployment.strategy_defaults?.skew_protection; - - return { - name: deployment.name, - description: deployment.description, - bindingPolicy: deployment.binding_policy, - deploymentPolicy: deployment.deployment_policy, - strategyDefaults: skewProtection - ? { - skewProtection: { - enabled: skewProtection.enabled, - defaultTtlSeconds: skewProtection.default_ttl_seconds, - }, - } - : undefined, - }; - }); - - return transformedPayload.deployments; - } -} - -export default DeploymentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts new file mode 100644 index 00000000..da6753aa --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts @@ -0,0 +1,195 @@ +import type { AzionConfigV6, AzionWorkloadDeploymentV6 } from '../../types'; +import WorkloadDeploymentsProcessConfigStrategy from './workloadDeploymentsProcessConfigStrategy'; + +describe('WorkloadDeploymentsProcessConfigStrategy (v6)', () => { + let strategy: WorkloadDeploymentsProcessConfigStrategy; + + const deployment = ( + attributes: AzionWorkloadDeploymentV6['strategy']['attributes'] = { application: 'my-app' }, + extra: Partial = {}, + ): AzionWorkloadDeploymentV6 => ({ + name: 'my-deployment', + strategy: { type: 'default', attributes }, + ...extra, + }); + + const declared: AzionConfigV6 = { + version: 6, + applications: [{ name: 'my-app' }], + firewall: [{ name: 'my-firewall' }], + customPages: [{ name: 'my-page', pages: [] }], + }; + + beforeEach(() => { + strategy = new WorkloadDeploymentsProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no workloads or deployments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + expect(strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] })).toEqual([]); + }); + + it('should apply the defaults and name the workload each deployment belongs to', () => { + const result = strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'my-workload', deployments: [deployment()] }], + }); + + expect(result).toEqual([ + { + workload_name: 'my-workload', + name: 'my-deployment', + current: true, + active: true, + strategy: { type: 'default', attributes: { application: 'my-app', firewall: null, custom_page: null } }, + }, + ]); + }); + + it('should list the deployments of every workload', () => { + const result = strategy.transformToManifest({ + ...declared, + workloads: [ + { name: 'a', deployments: [deployment(), deployment({ application: 'my-app' }, { name: 'second' })] }, + { name: 'b', deployments: [deployment({ application: 'my-app' }, { name: 'third' })] }, + ], + }); + + expect(result.map((item) => [item.workload_name, item.name])).toEqual([ + ['a', 'my-deployment'], + ['a', 'second'], + ['b', 'third'], + ]); + }); + + it('should keep names as names and IDs as numbers (the CLI resolves the names)', () => { + const [named] = strategy.transformToManifest({ + ...declared, + workloads: [ + { + name: 'w', + deployments: [ + deployment( + { application: 'my-app', firewall: 'my-firewall', customPage: 'my-page' }, + { current: false, active: false }, + ), + ], + }, + ], + }); + const [withIds] = strategy.transformToManifest({ + version: 6, + workloads: [{ name: 'w', deployments: [deployment({ application: 10, firewall: 20, customPage: 30 })] }], + }); + + expect(named).toEqual(expect.objectContaining({ current: false, active: false })); + expect(named.strategy.attributes).toEqual({ + application: 'my-app', + firewall: 'my-firewall', + custom_page: 'my-page', + }); + expect(withIds.strategy.attributes).toEqual({ application: 10, firewall: 20, custom_page: 30 }); + }); + + it('should throw when the application, firewall or custom page is not declared', () => { + const run = (attributes: AzionWorkloadDeploymentV6['strategy']['attributes'], config = declared) => + strategy.transformToManifest({ ...config, workloads: [{ name: 'w', deployments: [deployment(attributes)] }] }); + + expect(() => run({ application: 'other' })).toThrow( + 'Workload deployment "my-deployment" references non-existent Application "other".', + ); + expect(() => run({ application: 'my-app', firewall: 'other' })).toThrow( + 'Workload deployment "my-deployment" references non-existent Firewall "other".', + ); + expect(() => run({ application: 'my-app', customPage: 'other' })).toThrow( + 'Workload deployment "my-deployment" references non-existent Custom Page "other".', + ); + expect(() => run({ application: 'my-app' }, { version: 6 })).toThrow('non-existent Application "my-app"'); + }); + }); + + describe('transformToConfig', () => { + it('should not change the workloads when the manifest has no deployments', () => { + const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'w' }] }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(strategy.transformToConfig({ workload_deployments: [] }, transformedPayload)).toBeUndefined(); + expect(transformedPayload.workloads).toEqual([{ name: 'w' }]); + }); + + it('should give each workload the deployments that name it', () => { + const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'a' }, { name: 'b' }] }; + + strategy.transformToConfig( + { + workload_deployments: [ + { + workload_name: 'b', + name: 'second', + current: true, + active: false, + strategy: { type: 'default', attributes: { application: 'my-app', firewall: 'f', custom_page: null } }, + }, + { + workload_name: 'a', + name: 'first', + current: true, + active: true, + strategy: { type: 'default', attributes: { application: 10 } }, + }, + ], + }, + transformedPayload, + ); + + expect(transformedPayload.workloads).toEqual([ + { + name: 'a', + deployments: [ + { + name: 'first', + current: true, + active: true, + strategy: { type: 'default', attributes: { application: 10, firewall: null, customPage: null } }, + }, + ], + }, + { + name: 'b', + deployments: [ + { + name: 'second', + current: true, + active: false, + strategy: { type: 'default', attributes: { application: 'my-app', firewall: 'f', customPage: null } }, + }, + ], + }, + ]); + }); + + it('should round trip through the manifest', () => { + const config: AzionConfigV6 = { + ...declared, + workloads: [ + { + name: 'w', + deployments: [ + deployment( + { application: 'my-app', firewall: 'my-firewall', customPage: null }, + { current: true, active: true }, + ), + ], + }, + ], + }; + const manifest = { workload_deployments: strategy.transformToManifest(config) }; + const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'w' }] }; + + strategy.transformToConfig(manifest, transformedPayload); + + expect(transformedPayload.workloads?.[0].deployments).toEqual(config.workloads?.[0].deployments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts new file mode 100644 index 00000000..1bdc961d --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts @@ -0,0 +1,90 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionWorkloadDeploymentV6 } from '../../types'; + +/** + * WorkloadDeploymentsProcessConfigStrategy V6 + * @class WorkloadDeploymentsProcessConfigStrategy + * @description Converts the deployments of the v6 workloads between the config and the manifest. + * The manifest lists the deployments of every workload under `workload_deployments`, as v4 does, and each one carries the + * `workload_name` it belongs to, because the API creates a deployment under a workload + * (`/workspace/workloads/{workload_id}/deployments`) and the Azion CLI is the one that knows the workload ID. + * The application, firewall and custom page of the strategy are IDs in the API: a name is validated against the config + * and kept in the manifest for the CLI to resolve, and an ID goes through as the number it is. + */ +class WorkloadDeploymentsProcessConfigStrategy extends ProcessConfigStrategy { + /** + * Validate that a referenced resource is declared. A number is an ID, which is not validated. + */ + private validateReference( + resources: { name: string }[] | undefined, + nameOrId: string | number, + label: string, + deploymentName: string, + ) { + if (typeof nameOrId === 'string' && !resources?.some((resource) => resource.name === nameOrId)) { + throw new Error(`Workload deployment "${deploymentName}" references non-existent ${label} "${nameOrId}".`); + } + } + + transformToManifest(config: AzionConfigV6) { + const workloads = config?.workloads; + if (!workloads || workloads.length === 0) { + return []; + } + + return workloads.flatMap((workload) => + (workload.deployments ?? []).map((deployment: AzionWorkloadDeploymentV6) => { + const { application, firewall, customPage } = deployment.strategy.attributes; + + this.validateReference(config.applications, application, 'Application', deployment.name); + if (firewall) this.validateReference(config.firewall, firewall, 'Firewall', deployment.name); + if (customPage) this.validateReference(config.customPages, customPage, 'Custom Page', deployment.name); + + return { + workload_name: workload.name, + name: deployment.name, + current: deployment.current ?? true, + active: deployment.active ?? true, + strategy: { + type: deployment.strategy.type, + attributes: { + application, + firewall: firewall ?? null, + custom_page: customPage ?? null, + }, + }, + }; + }), + ); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { workload_deployments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.workload_deployments) || payload.workload_deployments.length === 0) { + return; + } + + transformedPayload.workloads = (transformedPayload.workloads ?? []).map((workload) => ({ + ...workload, + deployments: payload + .workload_deployments!.filter((deployment) => deployment.workload_name === workload.name) + .map((deployment) => ({ + name: deployment.name, + current: deployment.current, + active: deployment.active, + strategy: { + type: deployment.strategy.type, + attributes: { + application: deployment.strategy.attributes.application, + firewall: deployment.strategy.attributes.firewall ?? null, + customPage: deployment.strategy.attributes.custom_page ?? null, + }, + }, + })), + })); + + return transformedPayload.workloads; + } +} + +export default WorkloadDeploymentsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts index 59324002..15d99aaa 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts @@ -1,4 +1,4 @@ -import type { AzionConfigV6 } from '../../types'; +import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; import WorkloadProcessConfigStrategy from './workloadProcessConfigStrategy'; describe('WorkloadProcessConfigStrategy (v6)', () => { @@ -7,8 +7,10 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { const declared: AzionConfigV6 = { version: 6, environments: [{ name: 'production', deploymentPolicy: 'single_version' }], - deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], }; + const deployments: AzionWorkloadV6['deployments'] = [ + { name: 'default-deployment', strategy: { type: 'default', attributes: { application: 'my-app' } } }, + ]; beforeEach(() => { strategy = new WorkloadProcessConfigStrategy(); @@ -61,6 +63,7 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { workloads: [ { name: 'my-workload', + deployments, active: false, infrastructure: 2, workloadDomainAllowAccess: false, @@ -101,7 +104,9 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { it('should name the environment and the deployment of a binding as names, not as ids (the CLI resolves the ids)', () => { const [workload] = strategy.transformToManifest({ ...declared, - workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], + workloads: [ + { name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'default-deployment' }] }, + ], }); expect(Object.keys(workload.bindings[0])).toEqual(['environment_name', 'deployment_name', 'domains']); @@ -111,25 +116,45 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { expect(() => strategy.transformToManifest({ ...declared, - workloads: [{ name: 'w', bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }], + workloads: [ + { name: 'w', deployments, bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }, + ], }), ).toThrow('Workload "w" binding references non-existent Environment "staging".'); }); - it('should throw when a binding references a deployment that is not declared', () => { + it('should throw when a binding references a deployment that the workload does not declare', () => { expect(() => strategy.transformToManifest({ ...declared, - workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'other' }] }], + workloads: [{ name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'other' }] }], }), ).toThrow('Workload "w" binding references non-existent Deployment "other".'); + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], + }), + ).toThrow('Workload "w" binding references non-existent Deployment "default-deployment".'); expect(() => strategy.transformToManifest({ version: 6, - workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'd' }] }], + workloads: [{ name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'd' }] }], }), ).toThrow('non-existent Environment "production"'); }); + + it('should not accept a deployment of another workload in a binding', () => { + expect(() => + strategy.transformToManifest({ + ...declared, + workloads: [ + { name: 'a', deployments }, + { name: 'b', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }, + ], + }), + ).toThrow('Workload "b" binding references non-existent Deployment "default-deployment".'); + }); }); describe('transformToConfig', () => { diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts index 742a07e9..4fe30ceb 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts @@ -5,13 +5,13 @@ import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; * WorkloadProcessConfigStrategy V6 * @class WorkloadProcessConfigStrategy * @description Converts the v6 workloads between the config and the manifest. - * A binding references an environment and a deployment by the name it has in the config. The manifest keeps that name - * in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, so it is the - * one that knows their ids and sends them to the API. + * A binding references an environment and a deployment of the workload by the name it has in the config. The manifest + * keeps that name in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, + * so it is the one that knows their ids and sends them to the API. */ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy { /** - * Validate that the environment and the deployment of the bindings are declared + * Validate that the environment of the bindings is declared and that the deployment is one of the workload */ private validateBindingReferences(config: AzionConfigV6, workload: AzionWorkloadV6) { workload.bindings?.forEach((binding) => { @@ -20,7 +20,7 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy `Workload "${workload.name}" binding references non-existent Environment "${binding.environment}".`, ); } - if (!config.deployments?.some((deployment) => deployment.name === binding.deployment)) { + if (!workload.deployments?.some((deployment) => deployment.name === binding.deployment)) { throw new Error( `Workload "${workload.name}" binding references non-existent Deployment "${binding.deployment}".`, ); diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index 895580dc..7e1a616c 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -4,7 +4,6 @@ import ApplicationProcessConfigStrategy from './implementations/application/appl import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; import ConnectorProcessConfigStrategy from './implementations/connectorProcessConfigStrategy'; import CustomPagesProcessConfigStrategy from './implementations/customPagesProcessConfigStrategy'; -import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; import PurgeProcessConfigStrategy from './implementations/purgeProcessConfigStrategy'; @@ -12,6 +11,7 @@ import FirewallProcessConfigStrategy from './implementations/secure/firewallProc import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; +import WorkloadDeploymentsProcessConfigStrategy from './implementations/workloadDeploymentsProcessConfigStrategy'; import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; @@ -28,8 +28,8 @@ function factoryProcessContext() { processConfigContext.setStrategy('custom_pages', new CustomPagesProcessConfigStrategy()); processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); - processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); processConfigContext.setStrategy('workloads', new WorkloadProcessConfigStrategy()); + processConfigContext.setStrategy('workload_deployments', new WorkloadDeploymentsProcessConfigStrategy()); processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/deployments/index.ts b/packages/config/src/versions/v6/schemas/deployments/index.ts deleted file mode 100644 index 555530f0..00000000 --- a/packages/config/src/versions/v6/schemas/deployments/index.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES } from '../../constants'; - -/** - * Schema of the v6 deployments, from `DeploymentCreateRequest` and `DeploymentRequest` of the v6 API. - * `bindingPolicy` is required, as in the creation of a deployment. - */ -const deploymentsSchema = { - type: 'array', - items: { - type: 'object', - properties: { - name: { - type: 'string', - minLength: 3, - maxLength: 255, - errorMessage: "The 'name' field must be a string between 3 and 255 characters", - }, - description: { - type: ['string', 'null'], - errorMessage: "The 'description' field must be a string or null", - }, - bindingPolicy: { - type: 'string', - enum: DEPLOYMENT_BINDING_POLICIES, - errorMessage: `The 'bindingPolicy' field must be one of: ${DEPLOYMENT_BINDING_POLICIES.join(', ')}`, - }, - deploymentPolicy: { - type: 'string', - enum: DEPLOYMENT_POLICIES, - errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, - }, - strategyDefaults: { - type: 'object', - properties: { - skewProtection: { - type: 'object', - properties: { - enabled: { type: 'boolean' }, - defaultTtlSeconds: { type: 'integer', minimum: 1, maximum: 2147483647 }, - }, - required: ['enabled', 'defaultTtlSeconds'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in skewProtection', - required: "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", - }, - }, - }, - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in strategyDefaults', - }, - }, - }, - required: ['name', 'bindingPolicy'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in deployment objects', - required: { - name: "The 'name' field is required in each deployment", - bindingPolicy: "The 'bindingPolicy' field is required in each deployment", - }, - }, - }, - errorMessage: "The 'deployments' field must be an array of deployment objects", -}; - -export default deploymentsSchema; diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index 3138a26f..e4351504 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -2,7 +2,6 @@ import applicationsSchema from './applications'; import buildSchema from './build'; import connectorsSchema from './connectors'; import customPagesSchema from './customPages'; -import deploymentsSchema from './deployments'; import environmentsSchema from './environments'; import firewallSchema from './firewall'; import functionsSchema from './functions'; @@ -33,13 +32,12 @@ const azionConfigSchema = { applications: applicationsSchema, workloads: workloadsSchema, environments: environmentsSchema, - deployments: deploymentsSchema, purge: purgeSchema, }, additionalProperties: false, errorMessage: { additionalProperties: - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, purge', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/schemas/workloads/index.ts b/packages/config/src/versions/v6/schemas/workloads/index.ts index 6d560b2e..9b9fe9db 100644 --- a/packages/config/src/versions/v6/schemas/workloads/index.ts +++ b/packages/config/src/versions/v6/schemas/workloads/index.ts @@ -1,4 +1,5 @@ import { + WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, WORKLOAD_HTTP_VERSIONS, WORKLOAD_INFRASTRUCTURE, WORKLOAD_MTLS_VERIFICATION, @@ -10,6 +11,8 @@ import { * Schema of the v6 workloads. * Based on v4, checked against `WorkloadRequest` of the v6 API: the domains and the certificate moved to the * `bindings`, `tls.ciphers` is not nullable and the ports and versions of the http protocol have limits. + * `deployments` are the workload deployments (`WorkloadDeploymentRequest`): the strategy type can only be `default` and + * its application, firewall and custom page are IDs in the API, so the config accepts a name or an ID for each of them. */ const workloadsSchema = { type: 'array', @@ -139,6 +142,86 @@ const workloadsSchema = { }, additionalProperties: false, }, + deployments: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 1, + maxLength: 254, + pattern: '.*', + errorMessage: "The 'name' field must be a string between 1 and 254 characters", + }, + current: { + type: 'boolean', + default: true, + errorMessage: "The 'current' field must be a boolean", + }, + active: { + type: 'boolean', + default: true, + errorMessage: "The 'active' field must be a boolean", + }, + strategy: { + type: 'object', + properties: { + type: { + type: 'string', + enum: WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, + errorMessage: `The 'type' field must be one of: ${WORKLOAD_DEPLOYMENT_STRATEGY_TYPES.join(', ')}`, + }, + attributes: { + type: 'object', + properties: { + application: { + type: ['string', 'integer'], + minimum: 1, + minLength: 1, + errorMessage: + "The 'application' field must be the name of an application declared in 'applications' or an application ID", + }, + firewall: { + type: ['string', 'integer', 'null'], + minimum: 1, + minLength: 1, + errorMessage: + "The 'firewall' field must be the name of a firewall declared in 'firewall', a firewall ID or null", + }, + customPage: { + type: ['string', 'integer', 'null'], + minimum: 1, + minLength: 1, + errorMessage: + "The 'customPage' field must be the name of a custom page declared in 'customPages', a custom page ID or null", + }, + }, + required: ['application'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in strategy attributes', + required: "The 'application' field is required in strategy attributes", + }, + }, + }, + required: ['type', 'attributes'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in strategy', + required: "The 'type' and 'attributes' fields are required in strategy", + }, + }, + }, + required: ['name', 'strategy'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in deployment items', + required: "The 'name' and 'strategy' fields are required in each deployment", + }, + }, + errorMessage: "The 'deployments' field must be an array of deployment objects", + }, bindings: { type: 'array', items: { @@ -152,7 +235,8 @@ const workloadsSchema = { deployment: { type: 'string', minLength: 1, - errorMessage: "The 'deployment' field must be the name of a deployment declared in 'deployments'", + errorMessage: + "The 'deployment' field must be the name of a deployment declared in the 'deployments' of the workload", }, domains: { type: 'array', diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index 285300fb..a8abc7a2 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -20,7 +20,6 @@ import type { CONNECTOR_TRANSPORT_POLICY, CUSTOM_PAGE_ERROR_CODES, CUSTOM_PAGE_TYPES, - DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES, ENVIRONMENT_BRANCH_TRACKING_MODES, ENVIRONMENT_LOG_VERBOSITY, @@ -37,6 +36,7 @@ import type { WAF_RULESETS, WAF_SENSITIVITY, WAF_THREAT_TYPES, + WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, WORKLOADS_ACCESS_TYPES, } from './constants'; @@ -102,17 +102,41 @@ export type AzionWorkloadBindingDomainV6 = { }; /** - * Binding of a workload to an environment and a deployment. + * Binding of a workload to an environment and one of its deployments. */ export type AzionWorkloadBindingV6 = { /** Name of an environment declared in `environments` */ environment: string; - /** Name of a deployment declared in `deployments` */ + /** Name of a deployment declared in the `deployments` of the same workload */ deployment: string; /** Domains served by the binding */ domains?: AzionWorkloadBindingDomainV6[]; }; +/** + * Deployment of a workload of the Azion API v6. + */ +export type AzionWorkloadDeploymentV6 = { + /** Deployment name */ + name: string; + /** Whether it is the current deployment of the workload */ + current?: boolean; + /** Whether the deployment is active */ + active?: boolean; + /** What the deployment serves */ + strategy: { + type: (typeof WORKLOAD_DEPLOYMENT_STRATEGY_TYPES)[number]; + attributes: { + /** Name or ID of the application */ + application: string | number; + /** Name or ID of the firewall */ + firewall?: string | number | null; + /** Name or ID of the custom page */ + customPage?: string | number | null; + }; + }; +}; + /** * Workload of the Azion API v6. */ @@ -124,6 +148,8 @@ export type AzionWorkloadV6 = { protocols?: AzionWorkloadProtocols; mtls?: AzionWorkloadMTLS; workloadDomainAllowAccess?: boolean; + /** Deployments of the workload: the application, firewall and custom page each one serves */ + deployments?: AzionWorkloadDeploymentV6[]; /** Environments and deployments the workload is bound to, with the domains of each binding */ bindings?: AzionWorkloadBindingV6[]; }; @@ -152,21 +178,6 @@ export type AzionEnvironmentV6 = { deploymentPolicy: (typeof DEPLOYMENT_POLICIES)[number]; }; -/** - * Deployment of the Azion API v6. - */ -export type AzionDeploymentV6 = { - /** Deployment name */ - name: string; - description?: string | null; - /** Whether a release can swap the resources of the deployment. Required by the API */ - bindingPolicy: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; - deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; - strategyDefaults?: { - skewProtection?: { enabled: boolean; defaultTtlSeconds: number }; - }; -}; - /** * Storage (bucket) of the Azion API v6. */ @@ -431,8 +442,6 @@ export type AzionConfigV6 = { workloads?: AzionWorkloadV6[]; /** Environments */ environments?: AzionEnvironmentV6[]; - /** Deployments */ - deployments?: AzionDeploymentV6[]; /** Purge configurations */ purge?: AzionPurgeV6[]; }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index cae8ec3e..0fcccacc 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -108,7 +108,7 @@ describe('validateConfig (v6)', () => { it('rejects properties the v6 schema does not know yet', () => { expect(() => validateConfig({ version: 6, kv: [] })).toThrow( - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, purge', ); }); @@ -309,7 +309,7 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { }); }); -describe('validateConfig (v6) workloads, environments and deployments', () => { +describe('validateConfig (v6) workloads, workload deployments and environments', () => { const workload = (extra: Record = {}) => ({ version: 6, workloads: [{ name: 'my-workload', ...extra }], @@ -318,10 +318,12 @@ describe('validateConfig (v6) workloads, environments and deployments', () => { version: 6, environments: [{ name: 'production', deploymentPolicy: 'single_version', ...extra }], }); - const deployment = (extra: Record = {}) => ({ - version: 6, - deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE', ...extra }], - }); + const workloadDeployment = (extra: Record = {}) => + workload({ + deployments: [ + { name: 'default-deployment', strategy: { type: 'default', attributes: { application: 'my-app' } }, ...extra }, + ], + }); describe('workloads', () => { it('accepts a complete workload', () => { @@ -479,49 +481,70 @@ describe('validateConfig (v6) workloads, environments and deployments', () => { }); describe('deployments', () => { - it('accepts a complete deployment', () => { + it('accepts a complete deployment, with the references as names or as IDs', () => { + expect(() => + validateConfig( + workloadDeployment({ + current: true, + active: false, + strategy: { + type: 'default', + attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-page' }, + }, + }), + ), + ).not.toThrow(); expect(() => validateConfig( - deployment({ - description: 'Default', - bindingPolicy: 'STRICT', - deploymentPolicy: 'single_version', - strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + workloadDeployment({ + strategy: { type: 'default', attributes: { application: 10, firewall: 20, customPage: null } }, }), ), ).not.toThrow(); }); - it('limits the name to 3-255 characters and requires it', () => { - expect(() => validateConfig({ version: 6, deployments: [{ bindingPolicy: 'STRICT' }] })).toThrow( - "The 'name' field is required in each deployment", + it('requires name and strategy and limits the name to 254 characters', () => { + expect(() => validateConfig(workload({ deployments: [{ name: 'd' }] }))).toThrow( + "The 'name' and 'strategy' fields are required in each deployment", ); - expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab', bindingPolicy: 'FLEXIBLE' }] })).toThrow( - "The 'name' field must be a string between 3 and 255 characters", + expect(() => validateConfig(workloadDeployment({ name: 'd'.repeat(254) }))).not.toThrow(); + expect(() => validateConfig(workloadDeployment({ name: 'd'.repeat(255) }))).toThrow( + "The 'name' field must be a string between 1 and 254 characters", ); + expect(() => validateConfig(workloadDeployment({ name: '' }))).toThrow(); }); - it('requires the bindingPolicy (the creation of a deployment requires it)', () => { - expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( - "The 'bindingPolicy' field is required in each deployment", + it('requires the type and the application of the strategy, and the type can only be default', () => { + expect(() => validateConfig(workloadDeployment({ strategy: { attributes: { application: 'a' } } }))).toThrow( + "The 'type' and 'attributes' fields are required in strategy", + ); + expect(() => validateConfig(workloadDeployment({ strategy: { type: 'default', attributes: {} } }))).toThrow( + "The 'application' field is required in strategy attributes", ); - expect(() => validateConfig(deployment({ bindingPolicy: 'STRICT' }))).not.toThrow(); - expect(() => validateConfig(deployment({ bindingPolicy: 'FLEXIBLE' }))).not.toThrow(); + expect(() => + validateConfig(workloadDeployment({ strategy: { type: 'canary', attributes: { application: 'a' } } })), + ).toThrow("The 'type' field must be one of: default"); }); - it('rejects values out of the enums and invalid skew protection', () => { - expect(() => validateConfig(deployment({ bindingPolicy: 'strict' }))).toThrow( - "The 'bindingPolicy' field must be one of: STRICT, FLEXIBLE", + it('rejects an ID below 1, an empty name and unknown properties', () => { + const attributes = (extra: Record) => + workloadDeployment({ strategy: { type: 'default', attributes: { application: 'a', ...extra } } }); + + expect(() => validateConfig(attributes({ application: 0 }))).toThrow(); + expect(() => validateConfig(attributes({ application: '' }))).toThrow(); + expect(() => validateConfig(attributes({ customPage: 0 }))).toThrow(); + expect(() => validateConfig(attributes({ unknown: 1 }))).toThrow( + 'No additional properties are allowed in strategy attributes', ); - expect(() => validateConfig(deployment({ deploymentPolicy: 'rolling' }))).toThrow( - "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", + expect(() => validateConfig(workloadDeployment({ unknown: 1 }))).toThrow( + 'No additional properties are allowed in deployment items', ); - expect(() => validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true } } }))).toThrow( - "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + }); + + it('does not accept the top-level deployments of the dev spec (the production API has no Deployments API)', () => { + expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( + 'Config can only contain the following properties', ); - expect(() => - validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 0 } } })), - ).toThrow(); }); }); }); diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 3015f515..6223325f 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -120,7 +120,7 @@ describe('preset configs by API version', () => { expect(v6.applications).toEqual(v4.applications); }); - it('javascript: binds the workload to an environment and a deployment declared in the config', () => { + it('javascript: binds the workload to an environment and to its own deployment', () => { const manifest = processConfig(resolvePresetConfig(byName('javascript'), 6)); expect(manifest.environments.map((environment: { name: string }) => environment.name)).toEqual([ @@ -129,10 +129,7 @@ describe('preset configs by API version', () => { expect( manifest.environments.map((environment: { deployment_policy: string }) => environment.deployment_policy), ).toEqual(['single_version']); - expect(manifest.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); - expect(manifest.deployments.map((deployment: { binding_policy: string }) => deployment.binding_policy)).toEqual([ - 'FLEXIBLE', - ]); + expect(manifest).not.toHaveProperty('deployments'); expect(manifest.workloads).toHaveLength(1); expect(manifest.workloads[0]).toEqual( expect.objectContaining({ name: '$WORKLOAD_NAME', active: true, infrastructure: 1 }), @@ -141,6 +138,18 @@ describe('preset configs by API version', () => { { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, ]); }); + + it.each(['javascript', 'react', 'opennextjs', 'eleventy'])( + '%s: the workload deployment of the v6 manifest is the one of the v4 manifest, with the workload it belongs to', + (name) => { + const v4 = processConfig(resolvePresetConfig(byName(name), 4)); + const v6 = processConfig(resolvePresetConfig(byName(name), 6)); + + expect(v6.workload_deployments).toEqual( + v4.workload_deployments.map((deployment: object) => ({ workload_name: '$WORKLOAD_NAME', ...deployment })), + ); + }, + ); }); describe.each(goldenPresets)('%s (v3)', (name) => { diff --git a/packages/presets/src/presets/eleventy/config.v6.ts b/packages/presets/src/presets/eleventy/config.v6.ts index 2adab860..c1a6e1ff 100644 --- a/packages/presets/src/presets/eleventy/config.v6.ts +++ b/packages/presets/src/presets/eleventy/config.v6.ts @@ -51,18 +51,24 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], - // the application a deployment serves is set by the Azion CLI when it creates the release - deployments: [ - { - name: '$DEPLOYMENT_NAME', - bindingPolicy: 'FLEXIBLE', - }, - ], workloads: [ { name: '$WORKLOAD_NAME', active: true, infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts index 87fbc714..033c3bdb 100644 --- a/packages/presets/src/presets/javascript/config.v6.ts +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -56,18 +56,24 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], - // the application a deployment serves is set by the Azion CLI when it creates the release - deployments: [ - { - name: '$DEPLOYMENT_NAME', - bindingPolicy: 'FLEXIBLE', - }, - ], workloads: [ { name: '$WORKLOAD_NAME', active: true, infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/opennextjs/config.v6.ts b/packages/presets/src/presets/opennextjs/config.v6.ts index e7e60d94..843b43e7 100644 --- a/packages/presets/src/presets/opennextjs/config.v6.ts +++ b/packages/presets/src/presets/opennextjs/config.v6.ts @@ -161,18 +161,24 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], - // the application a deployment serves is set by the Azion CLI when it creates the release - deployments: [ - { - name: '$DEPLOYMENT_NAME', - bindingPolicy: 'FLEXIBLE', - }, - ], workloads: [ { name: '$WORKLOAD_NAME', active: true, infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts index 041bdbd9..f1cdebf5 100644 --- a/packages/presets/src/presets/react/config.v6.ts +++ b/packages/presets/src/presets/react/config.v6.ts @@ -51,18 +51,24 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], - // the application a deployment serves is set by the Azion CLI when it creates the release - deployments: [ - { - name: '$DEPLOYMENT_NAME', - bindingPolicy: 'FLEXIBLE', - }, - ], workloads: [ { name: '$WORKLOAD_NAME', active: true, infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], bindings: [ { environment: '$ENVIRONMENT_NAME', From 0883fdff268d120c257c86d8185e7fe9c89a84e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Thu, 5 Nov 2026 17:39:54 -0300 Subject: [PATCH 23/29] chore: describe the workload deployments in the v6 changeset --- .changeset/config-api-v6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/config-api-v6.md b/.changeset/config-api-v6.md index 6d52826f..d9c2c8b2 100644 --- a/.changeset/config-api-v6.md +++ b/.changeset/config-api-v6.md @@ -5,5 +5,5 @@ Support the Azion API v6 config in the same packages. -- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments`, `deployments` and workloads with `bindings` (the environment and deployment policies are required, and a binding references them by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. +- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments` (the deployment policy is required) and workloads with their `deployments` and `bindings` (a binding references an environment and one of the deployments of the workload by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. - `@aziontech/presets`: the `javascript`, `react`, `opennextjs` and `eleventy` presets now provide their v6 config in `configs[6]`. `config` remains the default (v4) config. From e3fffe6609b1138fff7c0be90fd34af5257a6946 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 6 Nov 2026 10:26:55 -0300 Subject: [PATCH 24/29] feat(presets): add the v6 config to every preset Each config.v6.ts is the v4 config of the preset with version 6, an environment and the binding of its workload deployment. nitro has no v3 config, so it declares the versions 4 and 6. The preset tests now run for every preset. --- .changeset/config-api-v6.md | 2 +- .../presets/src/presets/angular/config.v6.ts | 82 +++++ packages/presets/src/presets/angular/index.ts | 9 +- .../presets/src/presets/astro/config.v6.ts | 82 +++++ packages/presets/src/presets/astro/index.ts | 9 +- packages/presets/src/presets/configs.test.ts | 61 ++-- .../src/presets/docusaurus/config.v6.ts | 82 +++++ .../presets/src/presets/docusaurus/index.ts | 3 +- .../src/presets/emscripten/config.v6.ts | 115 ++++++++ .../presets/src/presets/emscripten/index.ts | 3 +- .../presets/src/presets/gatsby/config.v6.ts | 82 +++++ packages/presets/src/presets/gatsby/index.ts | 9 +- .../presets/src/presets/hexo/config.v6.ts | 82 +++++ packages/presets/src/presets/hexo/index.ts | 9 +- .../presets/src/presets/html/config.v6.ts | 82 +++++ packages/presets/src/presets/html/index.ts | 3 +- .../presets/src/presets/hugo/config.v6.ts | 82 +++++ packages/presets/src/presets/hugo/index.ts | 9 +- .../presets/src/presets/jekyll/config.v6.ts | 82 +++++ packages/presets/src/presets/jekyll/index.ts | 9 +- .../presets/src/presets/next/config.v6.ts | 189 ++++++++++++ packages/presets/src/presets/next/index.ts | 3 +- .../presets/src/presets/nitro/config.v6.ts | 219 ++++++++++++++ packages/presets/src/presets/nitro/index.ts | 3 +- .../presets/src/presets/nuxt/config.v6.ts | 279 ++++++++++++++++++ packages/presets/src/presets/nuxt/index.ts | 9 +- .../presets/src/presets/preact/config.v6.ts | 82 +++++ packages/presets/src/presets/preact/index.ts | 9 +- .../presets/src/presets/qwik/config.v6.ts | 82 +++++ packages/presets/src/presets/qwik/index.ts | 9 +- .../presets/src/presets/rustwasm/config.v6.ts | 112 +++++++ .../presets/src/presets/rustwasm/index.ts | 9 +- .../presets/src/presets/stencil/config.v6.ts | 82 +++++ packages/presets/src/presets/stencil/index.ts | 9 +- .../presets/src/presets/svelte/config.v6.ts | 249 ++++++++++++++++ packages/presets/src/presets/svelte/index.ts | 9 +- .../src/presets/typescript/config.v6.ts | 86 ++++++ .../presets/src/presets/typescript/index.ts | 3 +- .../src/presets/vitepress/config.v6.ts | 82 +++++ .../presets/src/presets/vitepress/index.ts | 9 +- packages/presets/src/presets/vue/config.v6.ts | 82 +++++ packages/presets/src/presets/vue/index.ts | 9 +- .../presets/src/presets/vuepress/config.v6.ts | 82 +++++ .../presets/src/presets/vuepress/index.ts | 9 +- 44 files changed, 2566 insertions(+), 47 deletions(-) create mode 100644 packages/presets/src/presets/angular/config.v6.ts create mode 100644 packages/presets/src/presets/astro/config.v6.ts create mode 100644 packages/presets/src/presets/docusaurus/config.v6.ts create mode 100644 packages/presets/src/presets/emscripten/config.v6.ts create mode 100644 packages/presets/src/presets/gatsby/config.v6.ts create mode 100644 packages/presets/src/presets/hexo/config.v6.ts create mode 100644 packages/presets/src/presets/html/config.v6.ts create mode 100644 packages/presets/src/presets/hugo/config.v6.ts create mode 100644 packages/presets/src/presets/jekyll/config.v6.ts create mode 100644 packages/presets/src/presets/next/config.v6.ts create mode 100644 packages/presets/src/presets/nitro/config.v6.ts create mode 100644 packages/presets/src/presets/nuxt/config.v6.ts create mode 100644 packages/presets/src/presets/preact/config.v6.ts create mode 100644 packages/presets/src/presets/qwik/config.v6.ts create mode 100644 packages/presets/src/presets/rustwasm/config.v6.ts create mode 100644 packages/presets/src/presets/stencil/config.v6.ts create mode 100644 packages/presets/src/presets/svelte/config.v6.ts create mode 100644 packages/presets/src/presets/typescript/config.v6.ts create mode 100644 packages/presets/src/presets/vitepress/config.v6.ts create mode 100644 packages/presets/src/presets/vue/config.v6.ts create mode 100644 packages/presets/src/presets/vuepress/config.v6.ts diff --git a/.changeset/config-api-v6.md b/.changeset/config-api-v6.md index d9c2c8b2..0fe792ed 100644 --- a/.changeset/config-api-v6.md +++ b/.changeset/config-api-v6.md @@ -6,4 +6,4 @@ Support the Azion API v6 config in the same packages. - `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments` (the deployment policy is required) and workloads with their `deployments` and `bindings` (a binding references an environment and one of the deployments of the workload by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. -- `@aziontech/presets`: the `javascript`, `react`, `opennextjs` and `eleventy` presets now provide their v6 config in `configs[6]`. `config` remains the default (v4) config. +- `@aziontech/presets`: every preset now provides its v6 config in `configs[6]` (`nitro` has no v3 config, as it did not exist on v3). `config` remains the default (v4) config. diff --git a/packages/presets/src/presets/angular/config.v6.ts b/packages/presets/src/presets/angular/config.v6.ts new file mode 100644 index 00000000..3ea2fcb7 --- /dev/null +++ b/packages/presets/src/presets/angular/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/angular/index.ts b/packages/presets/src/presets/angular/index.ts index eb551e1f..c3cdefa3 100644 --- a/packages/presets/src/presets/angular/index.ts +++ b/packages/presets/src/presets/angular/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const angular: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const angular: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/astro/config.v6.ts b/packages/presets/src/presets/astro/config.v6.ts new file mode 100644 index 00000000..a8b2b837 --- /dev/null +++ b/packages/presets/src/presets/astro/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/astro/index.ts b/packages/presets/src/presets/astro/index.ts index 03336589..009cd330 100644 --- a/packages/presets/src/presets/astro/index.ts +++ b/packages/presets/src/presets/astro/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const astro: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const astro: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 6223325f..3cdc5bd9 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -29,8 +29,8 @@ describe('preset configs by API version', () => { }, ); - it('keeps nitro v4 only, as it did not exist on v3', () => { - expect(getPresetApiVersions(byName('nitro'))).toEqual([4]); + it('keeps nitro without a v3 config, as it did not exist on v3', () => { + expect(getPresetApiVersions(byName('nitro'))).toEqual([4, 6]); expect(() => resolvePresetConfig(byName('nitro'), 3)).toThrow('does not support config version 3'); }); @@ -40,19 +40,42 @@ describe('preset configs by API version', () => { }); describe('v6', () => { - it('is declared by eleventy, javascript, opennextjs and react only for now', () => { - const withV6 = presets - .filter((preset) => preset.configs?.[6]) - .map((preset) => preset.metadata.name) - .sort(); - expect(withV6).toEqual(['eleventy', 'javascript', 'opennextjs', 'react']); - expect(getPresetApiVersions(byName('eleventy'))).toEqual([3, 4, 6]); - expect(getPresetApiVersions(byName('opennextjs'))).toEqual([3, 4, 6]); - expect(getPresetApiVersions(byName('javascript'))).toEqual([3, 4, 6]); - expect(getPresetApiVersions(byName('react'))).toEqual([3, 4, 6]); - expect(() => resolvePresetConfig(byName('vue'), 6)).toThrow('does not support config version 6'); + it('is declared by every preset, nitro without a v3 config as it did not exist on v3', () => { + const withoutV6 = presets.filter((preset) => !preset.configs?.[6]).map((preset) => preset.metadata.name); + expect(withoutV6).toEqual([]); + presets.forEach((preset) => + expect(getPresetApiVersions(preset)).toEqual(preset.metadata.name === 'nitro' ? [4, 6] : [3, 4, 6]), + ); }); + it.each(presets.map((preset) => [preset.metadata.name, preset] as const))( + '%s: validates and produces the manifest of the v4 config, with the environment and the binding of the v6', + (name) => { + const config = resolvePresetConfig(byName(name), 6); + expect(config.version).toBe(6); + expect(() => validateConfig(config)).not.toThrow(); + + // functions (e.g. build.extend) are different instances in each config, so compare through JSON + const plain = (value: unknown) => JSON.parse(JSON.stringify(value)); + const v4 = processConfig(resolvePresetConfig(byName(name), 4)); + const v6 = processConfig(config); + + expect(v6.version).toBe(6); + expect(plain(v6.build)).toEqual(plain(v4.build)); + expect(v6.storage).toEqual(v4.storage); + expect(v6.connectors).toEqual(v4.connectors); + expect(plain(v6.functions)).toEqual(plain(v4.functions)); + expect(v6.applications).toEqual(v4.applications); + expect(v6.workload_deployments).toEqual( + v4.workload_deployments.map((deployment: object) => ({ workload_name: '$WORKLOAD_NAME', ...deployment })), + ); + expect(v6.environments.map((environment: { name: string }) => environment.name)).toEqual(['$ENVIRONMENT_NAME']); + expect(v6.workloads[0].bindings).toEqual([ + { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, + ]); + }, + ); + it('javascript: validates and keeps the build of the v4 config', () => { const config = resolvePresetConfig(byName('javascript'), 6); expect(config.version).toBe(6); @@ -138,18 +161,6 @@ describe('preset configs by API version', () => { { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, ]); }); - - it.each(['javascript', 'react', 'opennextjs', 'eleventy'])( - '%s: the workload deployment of the v6 manifest is the one of the v4 manifest, with the workload it belongs to', - (name) => { - const v4 = processConfig(resolvePresetConfig(byName(name), 4)); - const v6 = processConfig(resolvePresetConfig(byName(name), 6)); - - expect(v6.workload_deployments).toEqual( - v4.workload_deployments.map((deployment: object) => ({ workload_name: '$WORKLOAD_NAME', ...deployment })), - ); - }, - ); }); describe.each(goldenPresets)('%s (v3)', (name) => { diff --git a/packages/presets/src/presets/docusaurus/config.v6.ts b/packages/presets/src/presets/docusaurus/config.v6.ts new file mode 100644 index 00000000..53d84147 --- /dev/null +++ b/packages/presets/src/presets/docusaurus/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './build', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/docusaurus/index.ts b/packages/presets/src/presets/docusaurus/index.ts index fa5722f7..0852636b 100644 --- a/packages/presets/src/presets/docusaurus/index.ts +++ b/packages/presets/src/presets/docusaurus/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; @@ -8,7 +9,7 @@ import prebuild from './prebuild'; export const docusaurus: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/emscripten/config.v6.ts b/packages/presets/src/presets/emscripten/config.v6.ts new file mode 100644 index 00000000..b60a0de6 --- /dev/null +++ b/packages/presets/src/presets/emscripten/config.v6.ts @@ -0,0 +1,115 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; +import webpack, { Configuration } from 'webpack'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + bundler: 'webpack', + polyfills: false, + extend: (context: Configuration) => { + context = { + ...context, + optimization: { + minimize: false, + }, + performance: { + maxEntrypointSize: 2097152, + maxAssetSize: 2097152, + }, + module: { + rules: [ + { + test: /\.wasm$/, + type: 'asset/inline', + }, + ], + }, + plugins: [ + new webpack.optimize.LimitChunkCountPlugin({ + maxChunks: 1, + }), + ], + }; + return context; + }, + } as AzionBuild, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/emscripten/index.ts b/packages/presets/src/presets/emscripten/index.ts index 04d5405e..35d77548 100644 --- a/packages/presets/src/presets/emscripten/index.ts +++ b/packages/presets/src/presets/emscripten/index.ts @@ -1,13 +1,14 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; export const emscripten: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/gatsby/config.v6.ts b/packages/presets/src/presets/gatsby/config.v6.ts new file mode 100644 index 00000000..5ff287f9 --- /dev/null +++ b/packages/presets/src/presets/gatsby/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/gatsby/index.ts b/packages/presets/src/presets/gatsby/index.ts index 12b0a936..54dc9e1f 100644 --- a/packages/presets/src/presets/gatsby/index.ts +++ b/packages/presets/src/presets/gatsby/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const gatsby: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const gatsby: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/hexo/config.v6.ts b/packages/presets/src/presets/hexo/config.v6.ts new file mode 100644 index 00000000..5ff287f9 --- /dev/null +++ b/packages/presets/src/presets/hexo/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/hexo/index.ts b/packages/presets/src/presets/hexo/index.ts index 0f8f6f1a..0084ed4c 100644 --- a/packages/presets/src/presets/hexo/index.ts +++ b/packages/presets/src/presets/hexo/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const hexo: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const hexo: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/html/config.v6.ts b/packages/presets/src/presets/html/config.v6.ts new file mode 100644 index 00000000..5fbaaa14 --- /dev/null +++ b/packages/presets/src/presets/html/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './www', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/html/index.ts b/packages/presets/src/presets/html/index.ts index ddd4decb..5243a690 100644 --- a/packages/presets/src/presets/html/index.ts +++ b/packages/presets/src/presets/html/index.ts @@ -1,7 +1,8 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; -export const html: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler }; +export const html: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler }; diff --git a/packages/presets/src/presets/hugo/config.v6.ts b/packages/presets/src/presets/hugo/config.v6.ts new file mode 100644 index 00000000..5ff287f9 --- /dev/null +++ b/packages/presets/src/presets/hugo/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/hugo/index.ts b/packages/presets/src/presets/hugo/index.ts index 6d35d685..c5e5c3f5 100644 --- a/packages/presets/src/presets/hugo/index.ts +++ b/packages/presets/src/presets/hugo/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const hugo: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const hugo: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/jekyll/config.v6.ts b/packages/presets/src/presets/jekyll/config.v6.ts new file mode 100644 index 00000000..c1a6e1ff --- /dev/null +++ b/packages/presets/src/presets/jekyll/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './_site', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/jekyll/index.ts b/packages/presets/src/presets/jekyll/index.ts index abb44bed..af287d76 100644 --- a/packages/presets/src/presets/jekyll/index.ts +++ b/packages/presets/src/presets/jekyll/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const jekyll: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const jekyll: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/next/config.v6.ts b/packages/presets/src/presets/next/config.v6.ts new file mode 100644 index 00000000..1e5b74d0 --- /dev/null +++ b/packages/presets/src/presets/next/config.v6.ts @@ -0,0 +1,189 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + polyfills: true, + }, + storage: [ + { + name: '$BUCKET_NAME', + dir: '.edge/next-build-assets', + workloadsAccess: 'read_only', + prefix: '$BUCKET_PREFIX', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Next.js Static Assets and set cache policy', + description: 'Serve Next.js static assets through edge connector and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_next/static/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Serve static assets through edge connector and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json|xml|html)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Next.js Function', + description: 'Execute Next.js edge function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/next/index.ts b/packages/presets/src/presets/next/index.ts index c05255ac..2f374486 100644 --- a/packages/presets/src/presets/next/index.ts +++ b/packages/presets/src/presets/next/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import postbuild from './postbuild'; @@ -8,7 +9,7 @@ import prebuild from './prebuild'; export const next: AzionBuildPreset = { config, - configs: { 3: configV3, 4: config }, + configs: { 3: configV3, 4: config, 6: configV6 }, metadata, handler, prebuild, diff --git a/packages/presets/src/presets/nitro/config.v6.ts b/packages/presets/src/presets/nitro/config.v6.ts new file mode 100644 index 00000000..a14caace --- /dev/null +++ b/packages/presets/src/presets/nitro/config.v6.ts @@ -0,0 +1,219 @@ +import type { AzionBuild, AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: '.output/server/index.mjs', + polyfills: true, + bundler: 'esbuild', + preset: 'nitro', + } as AzionBuild, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.output/public', + workloadsAccess: 'read_write', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Deliver static assets directly from storage and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|json|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Nitro Function', + description: 'Execute Nitro function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/nitro/index.ts b/packages/presets/src/presets/nitro/index.ts index a1ea67c9..0b64bda5 100644 --- a/packages/presets/src/presets/nitro/index.ts +++ b/packages/presets/src/presets/nitro/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; +import configV6 from './config.v6'; import metadata from './metadata'; import prebuild from './prebuild'; -export const nitro: AzionBuildPreset = { config, configs: { 4: config }, metadata, prebuild }; +export const nitro: AzionBuildPreset = { config, configs: { 4: config, 6: configV6 }, metadata, prebuild }; diff --git a/packages/presets/src/presets/nuxt/config.v6.ts b/packages/presets/src/presets/nuxt/config.v6.ts new file mode 100644 index 00000000..e86a8035 --- /dev/null +++ b/packages/presets/src/presets/nuxt/config.v6.ts @@ -0,0 +1,279 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + preset: 'nuxt', + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: '.output/public', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Nuxt Static Assets and set cache policy', + description: 'Serve Nuxt static assets through edge connector and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/_nuxt/', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Execute Nuxt Function when starts with /api/_content', + description: + 'Handle @nuxt/content API requests - executes Nuxt function for content management endpoints. Remove this rule if your project does not use the @nuxt/content library.', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'starts_with', + argument: '/api/_content', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Deliver Static Assets and set cache policy', + description: 'Deliver static assets directly from storage and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|json|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Nuxt Function', + description: 'Execute Nuxt function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/nuxt/index.ts b/packages/presets/src/presets/nuxt/index.ts index 3c63bcb7..62063bf0 100644 --- a/packages/presets/src/presets/nuxt/index.ts +++ b/packages/presets/src/presets/nuxt/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const nuxt: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const nuxt: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/preact/config.v6.ts b/packages/presets/src/presets/preact/config.v6.ts new file mode 100644 index 00000000..f1cdebf5 --- /dev/null +++ b/packages/presets/src/presets/preact/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/preact/index.ts b/packages/presets/src/presets/preact/index.ts index c3a89af3..3d3b01af 100644 --- a/packages/presets/src/presets/preact/index.ts +++ b/packages/presets/src/presets/preact/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const preact: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const preact: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/qwik/config.v6.ts b/packages/presets/src/presets/qwik/config.v6.ts new file mode 100644 index 00000000..f1cdebf5 --- /dev/null +++ b/packages/presets/src/presets/qwik/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/qwik/index.ts b/packages/presets/src/presets/qwik/index.ts index 47204a05..79dc8424 100644 --- a/packages/presets/src/presets/qwik/index.ts +++ b/packages/presets/src/presets/qwik/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const qwik: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const qwik: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/rustwasm/config.v6.ts b/packages/presets/src/presets/rustwasm/config.v6.ts new file mode 100644 index 00000000..296d3895 --- /dev/null +++ b/packages/presets/src/presets/rustwasm/config.v6.ts @@ -0,0 +1,112 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.js', + polyfills: false, + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: '.wasm-bindgen', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/rustwasm/index.ts b/packages/presets/src/presets/rustwasm/index.ts index c0d2359b..f6229d31 100644 --- a/packages/presets/src/presets/rustwasm/index.ts +++ b/packages/presets/src/presets/rustwasm/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; // import postbuild from './postbuild'; import prebuild from './prebuild'; -export const rustwasm: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const rustwasm: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/stencil/config.v6.ts b/packages/presets/src/presets/stencil/config.v6.ts new file mode 100644 index 00000000..5fbaaa14 --- /dev/null +++ b/packages/presets/src/presets/stencil/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './www', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/stencil/index.ts b/packages/presets/src/presets/stencil/index.ts index 6fd83ad2..3207ee48 100644 --- a/packages/presets/src/presets/stencil/index.ts +++ b/packages/presets/src/presets/stencil/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const stencil: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const stencil: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/svelte/config.v6.ts b/packages/presets/src/presets/svelte/config.v6.ts new file mode 100644 index 00000000..f9175d11 --- /dev/null +++ b/packages/presets/src/presets/svelte/config.v6.ts @@ -0,0 +1,249 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + preset: 'svelte', + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './build', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/handler.js', + bindings: { + storage: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: { + request: [ + { + name: 'Deliver Immutable Assets and Set Cache Policy', + description: 'Delivers immutable assets and set cache policy.', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'starts_with', + argument: '/_app/immutable', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Redirect to index.html for Subpaths', + description: 'Handle subpath requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}/index.html', + }, + }, + ], + }, + { + name: 'Redirect to index.html', + description: 'Handle directory requests by rewriting to index.html', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '.*/$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'rewrite_request', + attributes: { + value: '${uri}index.html', + }, + }, + ], + }, + { + name: 'Deliver Static Assets and Set Cache Policy', + description: 'Deliver static assets directly from storage and set cache policy', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: + '.(jpg|jpeg|png|gif|bmp|webp|svg|ico|ttf|otf|woff|woff2|eot|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|webm|mp3|wav|ogg|css|js|xml|html|txt|csv|zip|rar|7z|tar|gz|webmanifest|map|md|yaml|yml)$', + }, + ], + ], + behaviors: [ + { + type: 'set_connector', + attributes: { + value: '$CONNECTOR_NAME', + }, + }, + { + type: 'set_cache_policy', + attributes: { + value: '$APPLICATION_NAME', + }, + }, + { + type: 'deliver', + }, + ], + }, + { + name: 'Execute Svelte Function', + description: 'Execute Svelte function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + { + type: 'forward_cookies', + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/svelte/index.ts b/packages/presets/src/presets/svelte/index.ts index a56b2147..7ca768b4 100644 --- a/packages/presets/src/presets/svelte/index.ts +++ b/packages/presets/src/presets/svelte/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const svelte: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const svelte: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/typescript/config.v6.ts b/packages/presets/src/presets/typescript/config.v6.ts new file mode 100644 index 00000000..93717c73 --- /dev/null +++ b/packages/presets/src/presets/typescript/config.v6.ts @@ -0,0 +1,86 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +const config: AzionConfigV6 = { + version: 6, + build: { + entry: 'index.ts', + }, + functions: [ + { + name: '$FUNCTION_NAME', + path: './functions/index.js', // path to the edge function. This path is relative to the .edge folder. + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + rules: { + request: [ + { + name: 'Execute Function', + description: 'Execute function for all requests', + active: true, + criteria: [ + [ + { + variable: '${uri}', + conditional: 'if', + operator: 'matches', + argument: '^/', + }, + ], + ], + behaviors: [ + { + type: 'run_function', + attributes: { + value: '$FUNCTION_NAME', + }, + }, + ], + }, + ], + }, + functionsInstances: [ + { + name: '$FUNCTION_INSTANCE_NAME', + ref: '$FUNCTION_NAME', + }, + ], + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/typescript/index.ts b/packages/presets/src/presets/typescript/index.ts index 820c1e05..d1006eb7 100644 --- a/packages/presets/src/presets/typescript/index.ts +++ b/packages/presets/src/presets/typescript/index.ts @@ -1,6 +1,7 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import metadata from './metadata'; -export const typescript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata }; +export const typescript: AzionBuildPreset = { config, configs: { 3: configV3, 4: config, 6: configV6 }, metadata }; diff --git a/packages/presets/src/presets/vitepress/config.v6.ts b/packages/presets/src/presets/vitepress/config.v6.ts new file mode 100644 index 00000000..5852b6e6 --- /dev/null +++ b/packages/presets/src/presets/vitepress/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vitepress/index.ts b/packages/presets/src/presets/vitepress/index.ts index 4a49c6ff..07f0aca1 100644 --- a/packages/presets/src/presets/vitepress/index.ts +++ b/packages/presets/src/presets/vitepress/index.ts @@ -1,9 +1,16 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; // import postbuild from './postbuild'; -export const vitepress: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const vitepress: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; diff --git a/packages/presets/src/presets/vue/config.v6.ts b/packages/presets/src/presets/vue/config.v6.ts new file mode 100644 index 00000000..f1cdebf5 --- /dev/null +++ b/packages/presets/src/presets/vue/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createSPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createSPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vue/index.ts b/packages/presets/src/presets/vue/index.ts index 8c1e91c5..d32a6817 100644 --- a/packages/presets/src/presets/vue/index.ts +++ b/packages/presets/src/presets/vue/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const vue: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, handler, metadata, prebuild }; +export const vue: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + handler, + metadata, + prebuild, +}; diff --git a/packages/presets/src/presets/vuepress/config.v6.ts b/packages/presets/src/presets/vuepress/config.v6.ts new file mode 100644 index 00000000..5852b6e6 --- /dev/null +++ b/packages/presets/src/presets/vuepress/config.v6.ts @@ -0,0 +1,82 @@ +import type { AzionConfigV6 } from '@aziontech/config'; +import { createMPARules } from '@aziontech/config/rules'; + +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + }, + storage: [ + { + name: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + dir: './.edge/assets', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: '$CONNECTOR_NAME', + active: true, + type: 'storage', + attributes: { + bucket: '$BUCKET_NAME', + prefix: '$BUCKET_PREFIX', + }, + }, + ], + applications: [ + { + name: '$APPLICATION_NAME', + cache: [ + { + name: '$APPLICATION_NAME', + browser: { + maxAgeSeconds: 7200, + }, + edge: { + maxAgeSeconds: 7200, + }, + }, + ], + rules: createMPARules({ + connector: '$CONNECTOR_NAME', + application: '$APPLICATION_NAME', + }), + }, + ], + environments: [ + { + name: '$ENVIRONMENT_NAME', + deploymentPolicy: 'single_version', + }, + ], + workloads: [ + { + name: '$WORKLOAD_NAME', + active: true, + infrastructure: 1, + deployments: [ + { + name: '$DEPLOYMENT_NAME', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { + application: '$APPLICATION_NAME', + }, + }, + }, + ], + bindings: [ + { + environment: '$ENVIRONMENT_NAME', + deployment: '$DEPLOYMENT_NAME', + }, + ], + }, + ], +}; + +export default config; diff --git a/packages/presets/src/presets/vuepress/index.ts b/packages/presets/src/presets/vuepress/index.ts index ca2ce290..505ac9e5 100644 --- a/packages/presets/src/presets/vuepress/index.ts +++ b/packages/presets/src/presets/vuepress/index.ts @@ -1,8 +1,15 @@ import type { AzionBuildPreset } from '@aziontech/config'; import config from './config'; import configV3 from './config.v3'; +import configV6 from './config.v6'; import handler from './handler'; import metadata from './metadata'; import prebuild from './prebuild'; -export const vuepress: AzionBuildPreset = { config, configs: { 3: configV3, 4: config }, metadata, handler, prebuild }; +export const vuepress: AzionBuildPreset = { + config, + configs: { 3: configV3, 4: config, 6: configV6 }, + metadata, + handler, + prebuild, +}; From bc5c1b3a965e073e185c52c48ed9f3cafa0f65d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Fri, 6 Nov 2026 10:27:08 -0300 Subject: [PATCH 25/29] docs(config): document the config of the API v6 with a complete example The example is a typed file that a test validates and processes, and that the document embeds as it is. The README only links to the document, as the v4 config is still the default. --- packages/config/README.md | 3 + packages/config/docs/config-v6.md | 300 ++++++++++++++++++ .../versions/v6/azion.config.example.test.ts | 53 ++++ .../src/versions/v6/azion.config.example.ts | 230 ++++++++++++++ 4 files changed, 586 insertions(+) create mode 100644 packages/config/docs/config-v6.md create mode 100644 packages/config/src/versions/v6/azion.config.example.test.ts create mode 100644 packages/config/src/versions/v6/azion.config.example.ts diff --git a/packages/config/README.md b/packages/config/README.md index d34cf6da..f95210ef 100644 --- a/packages/config/README.md +++ b/packages/config/README.md @@ -2,6 +2,9 @@ This module provides comprehensive configuration and validation for the Azion Platform. It supports applications, workloads, connectors, functions, storage, firewall rules, WAF settings, network lists, custom pages, and purge operations. +> **Config API versions:** the examples below are for the default config (Azion API v4). The package also processes the +> v3 and v6 configs, selected with the `version` field of the config. See [Azion config for the API v6](https://github.com/aziontech/lib/blob/main/packages/config/docs/config-v6.md). + ## Table of Contents - [Installation](#installation) diff --git a/packages/config/docs/config-v6.md b/packages/config/docs/config-v6.md new file mode 100644 index 00000000..1ed45b06 --- /dev/null +++ b/packages/config/docs/config-v6.md @@ -0,0 +1,300 @@ +# Azion config for the API v6 + +The Azion API v6 changes how a project is published, so it has its own `azion.config` shape. `@aziontech/config` validates +and processes it into a v6 `manifest.json`, which the Azion CLI uses to create the resources. + +> **Status:** the v6 schemas follow the v6 OpenAPI and may change while the Azion CLI implements the API calls. The v4 config +> is still the default: a config without `version` is a v4 one, and the examples of the README are v4. + +## Using it + +Declare `version: 6` in the config (the type `AzionConfigV6` is exported by the package): + +```typescript +import { defineConfig, processConfig, validateConfig } from '@aziontech/config'; + +const config = defineConfig({ + version: 6, + // ... +}); + +validateConfig(config); // throws on an invalid config +const manifest = processConfig(config); // the v6 manifest, with `version: 6` +``` + +With the Azion Bundler, the version comes from the `version` of the `azion.config`, or from the flag +`--config-version 6` (the flag and the file must not disagree): + +```sh +azbundler build --preset react --config-version 6 +azbundler manifest generate --config-file ./azion.config.ts +``` + +Every preset of `@aziontech/presets` has a v6 config (`configs[6]`). + +## What changes from v4 + +| v4 | v6 | +| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| Saving publishes | Saving writes a draft, and publishing is a separate step done by the CLI | +| `workloads[].domains` and `workloads[].tls.certificate` | `workloads[].bindings[].domains[{ domain, certificate }]`: each binding has the domains and the certificate of an environment | +| No environments | `environments[]`: `name` and `deploymentPolicy` (`single_version` or `versioned_urls`, required and immutable) | +| `workloads[].deployments` | Same format, and `workloads[].bindings[]` binds one of them to an environment | +| `tls.ciphers` can be `null` | `tls.ciphers` is not nullable | +| Rule variables of any phase | Each variable is valid only in the phases the API documents | +| Firewall `set_waf.mode`: `learning \| blocking` | `logging \| blocking` | +| `kv` | Not available | + +Resource limits also follow the v6 API: names of 100 characters at most for applications and rules, cache max age up to one +year, 23 pages at most in a custom page, storage names with the pattern `^[a-z0-9][a-z0-9-]*[a-z0-9]$`, and so on. + +A **binding** references an environment (declared in `environments`) and a deployment of the same workload by name. The +`application`, `firewall` and `customPage` of a deployment `strategy`, the function and connector of the rules, and the WAF +of a firewall rule accept the name of a resource declared in the config, or its ID (an ID is not validated). + +## Complete example + +This is every resource the v6 config has, with the references between them: + +```typescript +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + entry: './src/index.js', + polyfills: true, + }, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + bindings: { + storage: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + }, + ], + storage: [ + { + name: 'my-bucket-assets', + prefix: 'v1', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: 'my-storage-connector', + active: true, + type: 'storage', + attributes: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + { + name: 'my-origin', + active: true, + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'force_https', + host: 'origin.example.com', + followingRedirect: false, + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 3, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + }, + }, + }, + ], + applications: [ + { + name: 'my-app', + active: true, + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + cache: [ + { + name: 'my-cache', + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 7200 }, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'denylist', list: ['order', 'user'] }, + }, + ], + rules: { + request: [ + { + name: 'Run the function', + description: 'Run the function for the API paths', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], + }, + { + name: 'Serve from the storage', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [ + { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, + { type: 'set_connector', attributes: { value: 'my-storage-connector' } }, + ], + }, + ], + response: [ + { + name: 'Add a header', + active: true, + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], + }, + ], + }, + functionsInstances: [ + { + name: 'my-function-instance', + ref: 'my-function', + args: { greeting: 'hello' }, + }, + ], + deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }], + }, + ], + customPages: [ + { + name: 'my-custom-pages', + active: true, + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-storage-connector', ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ], + networkList: [ + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'], active: true }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'], active: true }, + ], + waf: [ + { + name: 'my-waf', + active: true, + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [ + { threat: 'sql_injection', sensitivity: 'high' }, + { threat: 'cross_site_scripting', sensitivity: 'high' }, + ], + }, + }, + }, + ], + firewall: [ + { + name: 'my-firewall', + active: true, + debugRules: false, + functions: false, + networkProtection: true, + waf: true, + rules: [ + { + name: 'Allow the trusted networks', + active: true, + criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], + behaviors: [{ type: 'bypass' }], + }, + { + name: 'Protect with the WAF', + active: true, + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], + }, + ], + }, + ], + environments: [ + { + name: 'production', + description: 'Production environment', + deploymentPolicy: 'single_version', + logVerbosity: 'normal', + robotsPolicy: 'respect_origin', + }, + ], + workloads: [ + { + name: 'my-workload', + active: true, + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { minimumVersion: 'tls_1_3' }, + protocols: { + http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, + }, + deployments: [ + { + name: 'my-deployment', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-custom-pages' }, + }, + }, + ], + bindings: [ + { + environment: 'production', + deployment: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ], + }, + ], + purge: [{ type: 'url', items: ['https://example.com/index.html'], layer: 'cache' }], +}; +``` + +## The manifest + +`processConfig` writes the same blocks as v4 (`build`, `functions`, `storage`, `connectors`, `applications`, `firewall`, +`custom_pages`, ...) plus: + +- `version: 6`. +- `environments`: the environments, with the fields the API requires filled with defaults. +- `workloads[].bindings`: each binding names its environment and deployment in `environment_name` and `deployment_name`. + The Azion CLI creates both and resolves the names to their IDs. +- `workload_deployments`: the deployments of every workload (as in v4), each one with the `workload_name` it belongs to. + +The v6 `tls.ciphers` is left out of the workload when not set. + +## What is not in the v6 config yet + +- `kv`. +- `code` and `azion_form` of the functions: the config keeps `path`. +- Rollout, versions and releases: they are operations of the Azion CLI and the API, not part of the config. diff --git a/packages/config/src/versions/v6/azion.config.example.test.ts b/packages/config/src/versions/v6/azion.config.example.test.ts new file mode 100644 index 00000000..59cde718 --- /dev/null +++ b/packages/config/src/versions/v6/azion.config.example.test.ts @@ -0,0 +1,53 @@ +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { processConfig, validateConfig } from '../../configProcessor'; +import config from './azion.config.example'; + +describe('complete azion.config example of the API v6', () => { + it('is a valid v6 config', () => { + expect(() => validateConfig(config)).not.toThrow(); + }); + + it('is processed into a v6 manifest with every resource', () => { + const manifest = processConfig(config); + + expect(manifest.version).toBe(6); + expect(Object.keys(manifest)).toEqual( + expect.arrayContaining([ + 'build', + 'functions', + 'storage', + 'connectors', + 'applications', + 'custom_pages', + 'network_list', + 'waf', + 'firewall', + 'environments', + 'workloads', + 'workload_deployments', + 'purge', + ]), + ); + expect(manifest.workload_deployments).toHaveLength(1); + expect(manifest.workloads[0].bindings).toEqual([ + { + environment_name: 'production', + deployment_name: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ]); + expect(manifest.applications[0].device_groups).toEqual([{ name: 'mobile', user_agent: 'Android|iPhone' }]); + }); + + it('is the example of the v6 documentation', () => { + const source = readFileSync(join(__dirname, 'azion.config.example.ts'), 'utf8'); + const body = source.slice( + source.indexOf('const config: AzionConfigV6 = {'), + source.indexOf('export default config;'), + ); + const documentation = readFileSync(join(__dirname, '..', '..', '..', 'docs', 'config-v6.md'), 'utf8'); + + expect(documentation).toContain(body.trim()); + }); +}); diff --git a/packages/config/src/versions/v6/azion.config.example.ts b/packages/config/src/versions/v6/azion.config.example.ts new file mode 100644 index 00000000..5dcb0296 --- /dev/null +++ b/packages/config/src/versions/v6/azion.config.example.ts @@ -0,0 +1,230 @@ +import type { AzionConfigV6 } from '@aziontech/config'; + +/** + * Complete example of an azion.config for the Azion API v6. + * It uses every resource the v6 config has. Names reference each other (the Azion CLI resolves them to IDs), and an + * ID can be used instead of a name where the API takes one. + */ +const config: AzionConfigV6 = { + version: 6, + build: { + bundler: 'esbuild', + entry: './src/index.js', + polyfills: true, + }, + functions: [ + { + name: 'my-function', + path: './functions/index.js', + bindings: { + storage: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + }, + ], + storage: [ + { + name: 'my-bucket-assets', + prefix: 'v1', + dir: './dist', + workloadsAccess: 'read_only', + }, + ], + connectors: [ + { + name: 'my-storage-connector', + active: true, + type: 'storage', + attributes: { + bucket: 'my-bucket-assets', + prefix: 'v1', + }, + }, + { + name: 'my-origin', + active: true, + type: 'http', + attributes: { + addresses: [ + { + address: 'origin.example.com', + httpsPort: 443, + modules: { loadBalancer: { serverRole: 'primary', weight: 10 } }, + }, + ], + connectionOptions: { + dnsResolution: 'both', + transportPolicy: 'force_https', + host: 'origin.example.com', + followingRedirect: false, + }, + modules: { + loadBalancer: { + enabled: true, + config: { method: 'round_robin', maxRetries: 3, connectionTimeout: 60, readWriteTimeout: 120 }, + }, + }, + }, + }, + ], + applications: [ + { + name: 'my-app', + active: true, + debug: false, + edgeCacheEnabled: true, + functionsEnabled: true, + applicationAcceleratorEnabled: true, + imageProcessorEnabled: false, + cache: [ + { + name: 'my-cache', + browser: { maxAgeSeconds: 7200 }, + edge: { maxAgeSeconds: 7200 }, + tieredCache: { enabled: true, topology: 'nearest-region' }, + cacheByQueryString: { option: 'denylist', list: ['order', 'user'] }, + }, + ], + rules: { + request: [ + { + name: 'Run the function', + description: 'Run the function for the API paths', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], + behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], + }, + { + name: 'Serve from the storage', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [ + { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, + { type: 'set_connector', attributes: { value: 'my-storage-connector' } }, + ], + }, + ], + response: [ + { + name: 'Add a header', + active: true, + criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], + behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], + }, + ], + }, + functionsInstances: [ + { + name: 'my-function-instance', + ref: 'my-function', + args: { greeting: 'hello' }, + }, + ], + deviceGroups: [{ name: 'mobile', userAgent: 'Android|iPhone' }], + }, + ], + customPages: [ + { + name: 'my-custom-pages', + active: true, + pages: [ + { + code: '404', + page: { + type: 'page_connector', + attributes: { connector: 'my-storage-connector', ttl: 60, uri: '/404.html', customStatusCode: 404 }, + }, + }, + ], + }, + ], + networkList: [ + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'], active: true }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'], active: true }, + ], + waf: [ + { + name: 'my-waf', + active: true, + engineSettings: { + engineVersion: '2021-Q3', + type: 'score', + attributes: { + rulesets: [1], + thresholds: [ + { threat: 'sql_injection', sensitivity: 'high' }, + { threat: 'cross_site_scripting', sensitivity: 'high' }, + ], + }, + }, + }, + ], + firewall: [ + { + name: 'my-firewall', + active: true, + debugRules: false, + functions: false, + networkProtection: true, + waf: true, + rules: [ + { + name: 'Allow the trusted networks', + active: true, + criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], + behaviors: [{ type: 'bypass' }], + }, + { + name: 'Protect with the WAF', + active: true, + criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], + behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], + }, + ], + }, + ], + environments: [ + { + name: 'production', + description: 'Production environment', + deploymentPolicy: 'single_version', + logVerbosity: 'normal', + robotsPolicy: 'respect_origin', + }, + ], + workloads: [ + { + name: 'my-workload', + active: true, + infrastructure: 1, + workloadDomainAllowAccess: true, + tls: { minimumVersion: 'tls_1_3' }, + protocols: { + http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, + }, + deployments: [ + { + name: 'my-deployment', + current: true, + active: true, + strategy: { + type: 'default', + attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-custom-pages' }, + }, + }, + ], + bindings: [ + { + environment: 'production', + deployment: 'my-deployment', + domains: [{ domain: 'example.com', certificate: null }], + }, + ], + }, + ], + purge: [{ type: 'url', items: ['https://example.com/index.html'], layer: 'cache' }], +}; + +export default config; From da031dec51bc329aa58405db018ddd1c382f8a5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 10 Nov 2026 14:12:04 -0300 Subject: [PATCH 26/29] fix(presets): match only the paths without extension in the subpaths rule The regex of the subpaths rule of nuxt, svelte and nitro used [sS]* instead of [\s\S]* and an unescaped dot, so it matched files like /logo.png and skipped paths like /about. Fixes the v4 and v6 configs. The v3 config is kept as it is, since the v3 goldens are frozen. --- .changeset/fix-subpaths-regex.md | 5 +++++ packages/presets/src/presets/configs.test.ts | 18 ++++++++++++++++++ packages/presets/src/presets/nitro/config.ts | 2 +- .../presets/src/presets/nitro/config.v6.ts | 2 +- packages/presets/src/presets/nuxt/config.ts | 2 +- packages/presets/src/presets/nuxt/config.v6.ts | 2 +- packages/presets/src/presets/svelte/config.ts | 2 +- .../presets/src/presets/svelte/config.v6.ts | 2 +- 8 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 .changeset/fix-subpaths-regex.md diff --git a/.changeset/fix-subpaths-regex.md b/.changeset/fix-subpaths-regex.md new file mode 100644 index 00000000..c96ec034 --- /dev/null +++ b/.changeset/fix-subpaths-regex.md @@ -0,0 +1,5 @@ +--- +'@aziontech/presets': patch +--- + +Fix the regex of the "Redirect to index.html for Subpaths" rule of the `nuxt`, `svelte` and `nitro` presets (v4 and v6 configs). It matched files such as `/logo.png` and skipped the paths without extension such as `/about`, because of `[sS]*` (instead of `[\s\S]*`) and an unescaped `.`. It now matches only the paths that do not end with `/` and have no file extension. diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 3cdc5bd9..62de10a3 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -161,6 +161,24 @@ describe('preset configs by API version', () => { { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, ]); }); + it.each( + ['nuxt', 'svelte', 'nitro'].flatMap((name) => ([4, 6] as const).map((version) => [name, version] as const)), + )( + '%s (v%s): the subpaths rule matches the paths without extension and not the files or the directories', + (name, version) => { + const manifest = processConfig(resolvePresetConfig(byName(name), version)); + const rule = manifest.applications[0].rules.find( + (item: { phase: string; rule: { name: string } }) => + item.phase === 'request' && item.rule.name === 'Redirect to index.html for Subpaths', + ); + const regex = new RegExp(rule.rule.criteria[0][0].argument); + + ['/about', '/docs/intro', '/a.b/c', '/v1.2/page'].forEach((uri) => expect(regex.test(uri)).toBe(true)); + ['/logo.png', '/favicon.ico', '/_nuxt/entry.js', '/file.tar.gz', '/', '/docs/'].forEach((uri) => + expect(regex.test(uri)).toBe(false), + ); + }, + ); }); describe.each(goldenPresets)('%s (v3)', (name) => { diff --git a/packages/presets/src/presets/nitro/config.ts b/packages/presets/src/presets/nitro/config.ts index b54384f6..d40a2143 100644 --- a/packages/presets/src/presets/nitro/config.ts +++ b/packages/presets/src/presets/nitro/config.ts @@ -64,7 +64,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/nitro/config.v6.ts b/packages/presets/src/presets/nitro/config.v6.ts index a14caace..33421d59 100644 --- a/packages/presets/src/presets/nitro/config.v6.ts +++ b/packages/presets/src/presets/nitro/config.v6.ts @@ -65,7 +65,7 @@ const config: AzionConfigV6 = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/nuxt/config.ts b/packages/presets/src/presets/nuxt/config.ts index 93b84e6a..00df37b7 100644 --- a/packages/presets/src/presets/nuxt/config.ts +++ b/packages/presets/src/presets/nuxt/config.ts @@ -94,7 +94,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/nuxt/config.v6.ts b/packages/presets/src/presets/nuxt/config.v6.ts index e86a8035..ca38a470 100644 --- a/packages/presets/src/presets/nuxt/config.v6.ts +++ b/packages/presets/src/presets/nuxt/config.v6.ts @@ -95,7 +95,7 @@ const config: AzionConfigV6 = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/svelte/config.ts b/packages/presets/src/presets/svelte/config.ts index 1479eea4..07347279 100644 --- a/packages/presets/src/presets/svelte/config.ts +++ b/packages/presets/src/presets/svelte/config.ts @@ -94,7 +94,7 @@ const config: AzionConfig = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], diff --git a/packages/presets/src/presets/svelte/config.v6.ts b/packages/presets/src/presets/svelte/config.v6.ts index f9175d11..f41188d5 100644 --- a/packages/presets/src/presets/svelte/config.v6.ts +++ b/packages/presets/src/presets/svelte/config.v6.ts @@ -95,7 +95,7 @@ const config: AzionConfigV6 = { variable: '${uri}', conditional: 'if', operator: 'matches', - argument: '^(?!.*/$)(?![sS]*.[a-zA-Z0-9]+$).*', + argument: '^(?!.*/$)(?!.*\\.[a-zA-Z0-9]+$).*', }, ], ], From 3f3f23ca1977d709a604ab2bb872d34c37cf4ffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 10 Nov 2026 17:10:52 -0300 Subject: [PATCH 27/29] feat(config): follow the current openapi-v6-prod in API v6 Deployments are back at the root of the config: the current spec has the Deployments API again and no workload deployments. The requests of the spec also lost active everywhere, the cache module cannot be disabled, the purge layer is only cache, functions take dependencies, device group names are alphanumeric, http versions must include http1 and http2, and the behaviors and variables of the rules need the modules the API lists. The v6 config, manifest, presets and the SPA and MPA rule helpers follow that. --- packages/config/docs/config-v6.md | 87 ++++--- .../src/rules/request/createMPA.test.ts | 3 - .../config/src/rules/request/createMPA.ts | 3 - .../src/rules/request/createSPA.test.ts | 2 - .../config/src/rules/request/createSPA.ts | 2 - .../config/src/versions/accessors.test.ts | 1 + packages/config/src/versions/registry.test.ts | 7 +- .../versions/v6/azion.config.example.test.ts | 5 +- .../src/versions/v6/azion.config.example.ts | 41 ++- packages/config/src/versions/v6/constants.ts | 73 +++++- packages/config/src/versions/v6/index.ts | 6 +- .../applicationProcessConfigStrategy.test.ts | 92 ++++++- .../applicationProcessConfigStrategy.ts | 51 +++- ...tionInstancesProcessConfigStrategy.test.ts | 10 +- .../functionInstancesProcessConfigStrategy.ts | 4 +- .../rulesProcessConfigStrategy.test.ts | 7 +- .../application/rulesProcessConfigStrategy.ts | 3 - .../connectorProcessConfigStrategy.test.ts | 21 +- .../connectorProcessConfigStrategy.ts | 4 - .../customPagesProcessConfigStrategy.test.ts | 5 - .../customPagesProcessConfigStrategy.ts | 2 - .../deploymentProcessConfigStrategy.test.ts | 96 +++++++ .../deploymentProcessConfigStrategy.ts | 68 +++++ .../functionsProcessConfigStrategy.test.ts | 56 ++++- .../functionsProcessConfigStrategy.ts | 32 ++- .../purgeProcessConfigStrategy.test.ts | 4 +- .../firewallProcessConfigStrategy.test.ts | 58 ++++- .../secure/firewallProcessConfigStrategy.ts | 48 +++- .../networkListProcessConfigStrategy.test.ts | 10 +- .../networkListProcessConfigStrategy.ts | 2 - .../secure/wafProcessConfigStrategy.test.ts | 3 - .../secure/wafProcessConfigStrategy.ts | 2 - ...adDeploymentsProcessConfigStrategy.test.ts | 195 --------------- ...orkloadDeploymentsProcessConfigStrategy.ts | 90 ------- .../workloadProcessConfigStrategy.test.ts | 81 +++--- .../workloadProcessConfigStrategy.ts | 34 ++- .../src/versions/v6/processStrategy/index.ts | 4 +- .../versions/v6/schemas/applications/index.ts | 22 +- .../versions/v6/schemas/connectors/index.ts | 10 - .../versions/v6/schemas/customPages/index.ts | 5 - .../versions/v6/schemas/deployments/index.ts | 68 +++++ .../versions/v6/schemas/environments/index.ts | 6 +- .../firewall/functionsInstances/index.ts | 8 +- .../src/versions/v6/schemas/firewall/index.ts | 8 - .../versions/v6/schemas/functions/index.ts | 36 ++- .../versions/v6/schemas/networkList/index.ts | 5 - .../src/versions/v6/schemas/purge/index.ts | 6 +- .../config/src/versions/v6/schemas/schema.ts | 4 +- .../src/versions/v6/schemas/waf/index.ts | 5 - .../versions/v6/schemas/workloads/index.ts | 96 +------ packages/config/src/versions/v6/types.ts | 115 +++++---- .../versions/v6/validateConfig/index.test.ts | 235 ++++++++++++------ .../presets/src/presets/angular/config.v6.ts | 22 +- .../presets/src/presets/astro/config.v6.ts | 22 +- packages/presets/src/presets/configs.test.ts | 48 ++-- .../src/presets/docusaurus/config.v6.ts | 22 +- .../presets/src/presets/eleventy/config.v6.ts | 22 +- .../src/presets/emscripten/config.v6.ts | 22 +- .../presets/src/presets/gatsby/config.v6.ts | 22 +- .../presets/src/presets/hexo/config.v6.ts | 22 +- .../presets/src/presets/html/config.v6.ts | 22 +- .../presets/src/presets/hugo/config.v6.ts | 22 +- .../src/presets/javascript/config.v6.ts | 22 +- .../presets/src/presets/jekyll/config.v6.ts | 22 +- .../presets/src/presets/next/config.v6.ts | 25 +- .../presets/src/presets/nitro/config.v6.ts | 26 +- .../presets/src/presets/nuxt/config.v6.ts | 28 +-- .../src/presets/opennextjs/config.v6.ts | 25 +- .../presets/src/presets/preact/config.v6.ts | 22 +- .../presets/src/presets/qwik/config.v6.ts | 22 +- .../presets/src/presets/react/config.v6.ts | 22 +- .../presets/src/presets/rustwasm/config.v6.ts | 23 +- .../presets/src/presets/stencil/config.v6.ts | 22 +- .../presets/src/presets/svelte/config.v6.ts | 27 +- .../src/presets/typescript/config.v6.ts | 22 +- .../src/presets/vitepress/config.v6.ts | 22 +- packages/presets/src/presets/vue/config.v6.ts | 22 +- .../presets/src/presets/vuepress/config.v6.ts | 22 +- 78 files changed, 1242 insertions(+), 1219 deletions(-) create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts create mode 100644 packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts delete mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts delete mode 100644 packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts create mode 100644 packages/config/src/versions/v6/schemas/deployments/index.ts diff --git a/packages/config/docs/config-v6.md b/packages/config/docs/config-v6.md index 1ed45b06..a8f61381 100644 --- a/packages/config/docs/config-v6.md +++ b/packages/config/docs/config-v6.md @@ -34,23 +34,40 @@ Every preset of `@aziontech/presets` has a v6 config (`configs[6]`). ## What changes from v4 -| v4 | v6 | -| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -| Saving publishes | Saving writes a draft, and publishing is a separate step done by the CLI | -| `workloads[].domains` and `workloads[].tls.certificate` | `workloads[].bindings[].domains[{ domain, certificate }]`: each binding has the domains and the certificate of an environment | -| No environments | `environments[]`: `name` and `deploymentPolicy` (`single_version` or `versioned_urls`, required and immutable) | -| `workloads[].deployments` | Same format, and `workloads[].bindings[]` binds one of them to an environment | -| `tls.ciphers` can be `null` | `tls.ciphers` is not nullable | -| Rule variables of any phase | Each variable is valid only in the phases the API documents | -| Firewall `set_waf.mode`: `learning \| blocking` | `logging \| blocking` | -| `kv` | Not available | +| v4 | v6 | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Saving publishes | Saving writes a draft, and publishing is a separate step done by the CLI | +| `workloads[].domains` and `workloads[].tls.certificate` | `workloads[].bindings[].domains[{ domain, certificate }]`: each binding has the domains and the certificate of an environment | +| No environments | `environments[]`: `name` and `deploymentPolicy` (`single_version` or `versioned_urls`, required and immutable) | +| `workloads[].deployments` with the `strategy` (application, firewall, custom page) | `deployments[]`: `name`, `bindingPolicy` (required), `description`, `deploymentPolicy` (`single_version`, `versioned_urls` or `latest`) and `strategyDefaults.skewProtection`. The application a deployment serves is set by the CLI in a release | +| `active` in applications, rules, functions, function instances, connectors, addresses, firewalls, WAFs, network lists, custom pages and workloads | Removed: the v6 API has no `active` in any resource | +| `edgeCacheEnabled` can be `false` | The cache module cannot be disabled: only `true` | +| Purge `layer`: `cache` or `tiered_cache` | `cache` only | +| Device group `name` of any text | Letters and numbers only (`^[a-zA-Z0-9]+$`) | +| Workload `protocols.http.versions` of any combination | Must include `http1` and `http2` | +| Functions without dependencies | `functions[].dependencies`: up to 20 connectors or network lists the function uses at runtime | +| `tls.ciphers` can be `null` | `tls.ciphers` is not nullable | +| Rule variables of any phase | Each variable is valid only in the phases the API documents | +| Firewall `set_waf.mode`: `learning \| blocking` | `logging \| blocking` | +| `kv` | Not available | + +The behaviors and criterion variables of the rules need the modules the API documents. An application needs +`applicationAcceleratorEnabled` for every variable except `${uri}` and for `forward_cookies`, `filter_request_cookie`, +`rewrite_request`, `capture_match_groups`, `add_request_cookie` and `set_cookie`, `imageProcessorEnabled` for +`optimize_images`, and functions (`functionsEnabled`, or declared `functionsInstances`) for `run_function`. A firewall needs +at least one of its modules (`functions`, `networkProtection`, `waf`) for each behavior, `waf` for the header, `request_args` +and `request_method` variables, `networkProtection` for `network`, and `functions` for `run_function`. The config fails with +a message naming the rule and the module when one is missing. + +A workload with `workloadDomainAllowAccess: true` (the default) cannot be bound to an environment whose `deploymentPolicy` is +`versioned_urls`; for such a workload the default becomes `false`. Resource limits also follow the v6 API: names of 100 characters at most for applications and rules, cache max age up to one year, 23 pages at most in a custom page, storage names with the pattern `^[a-z0-9][a-z0-9-]*[a-z0-9]$`, and so on. -A **binding** references an environment (declared in `environments`) and a deployment of the same workload by name. The -`application`, `firewall` and `customPage` of a deployment `strategy`, the function and connector of the rules, and the WAF -of a firewall rule accept the name of a resource declared in the config, or its ID (an ID is not validated). +A **binding** references an environment (declared in `environments`) and a deployment (declared in `deployments`) by name. The +function and connector of the rules, and the WAF of a firewall rule, accept the name of a resource declared in the config, or +its ID (an ID is not validated). ## Complete example @@ -74,6 +91,11 @@ const config: AzionConfigV6 = { prefix: 'v1', }, }, + // connectors and network lists the function uses at runtime, which a release includes with it + dependencies: [ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-ip-allowlist' }, + ], }, ], storage: [ @@ -87,7 +109,6 @@ const config: AzionConfigV6 = { connectors: [ { name: 'my-storage-connector', - active: true, type: 'storage', attributes: { bucket: 'my-bucket-assets', @@ -96,7 +117,6 @@ const config: AzionConfigV6 = { }, { name: 'my-origin', - active: true, type: 'http', attributes: { addresses: [ @@ -124,7 +144,6 @@ const config: AzionConfigV6 = { applications: [ { name: 'my-app', - active: true, debug: false, edgeCacheEnabled: true, functionsEnabled: true, @@ -144,13 +163,11 @@ const config: AzionConfigV6 = { { name: 'Run the function', description: 'Run the function for the API paths', - active: true, criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], }, { name: 'Serve from the storage', - active: true, criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], behaviors: [ { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, @@ -161,7 +178,6 @@ const config: AzionConfigV6 = { response: [ { name: 'Add a header', - active: true, criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], }, @@ -180,7 +196,6 @@ const config: AzionConfigV6 = { customPages: [ { name: 'my-custom-pages', - active: true, pages: [ { code: '404', @@ -193,13 +208,12 @@ const config: AzionConfigV6 = { }, ], networkList: [ - { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'], active: true }, - { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'], active: true }, + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'] }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'] }, ], waf: [ { name: 'my-waf', - active: true, engineSettings: { engineVersion: '2021-Q3', type: 'score', @@ -216,7 +230,6 @@ const config: AzionConfigV6 = { firewall: [ { name: 'my-firewall', - active: true, debugRules: false, functions: false, networkProtection: true, @@ -224,13 +237,11 @@ const config: AzionConfigV6 = { rules: [ { name: 'Allow the trusted networks', - active: true, criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], behaviors: [{ type: 'bypass' }], }, { name: 'Protect with the WAF', - active: true, criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], }, @@ -246,27 +257,24 @@ const config: AzionConfigV6 = { robotsPolicy: 'respect_origin', }, ], + // the application, firewall and custom page a deployment serves are set by the Azion CLI when it creates the release + deployments: [ + { + name: 'my-deployment', + description: 'Main deployment', + bindingPolicy: 'FLEXIBLE', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], workloads: [ { name: 'my-workload', - active: true, infrastructure: 1, workloadDomainAllowAccess: true, tls: { minimumVersion: 'tls_1_3' }, protocols: { http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, }, - deployments: [ - { - name: 'my-deployment', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-custom-pages' }, - }, - }, - ], bindings: [ { environment: 'production', @@ -286,10 +294,9 @@ const config: AzionConfigV6 = { `custom_pages`, ...) plus: - `version: 6`. -- `environments`: the environments, with the fields the API requires filled with defaults. +- `environments` and `deployments`: the environments and the deployments, with the fields the API requires filled with defaults. - `workloads[].bindings`: each binding names its environment and deployment in `environment_name` and `deployment_name`. The Azion CLI creates both and resolves the names to their IDs. -- `workload_deployments`: the deployments of every workload (as in v4), each one with the `workload_name` it belongs to. The v6 `tls.ciphers` is left out of the workload when not set. diff --git a/packages/config/src/rules/request/createMPA.test.ts b/packages/config/src/rules/request/createMPA.test.ts index 2ae2458f..a2d11f7a 100644 --- a/packages/config/src/rules/request/createMPA.test.ts +++ b/packages/config/src/rules/request/createMPA.test.ts @@ -19,7 +19,6 @@ describe('createMPARules', () => { expect(staticAssetsRule).toEqual({ name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -54,7 +53,6 @@ describe('createMPARules', () => { expect(directoryIndexRule).toEqual({ name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -86,7 +84,6 @@ describe('createMPARules', () => { expect(subpathIndexRule).toEqual({ name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createMPA.ts b/packages/config/src/rules/request/createMPA.ts index 286858ca..20fc5370 100644 --- a/packages/config/src/rules/request/createMPA.ts +++ b/packages/config/src/rules/request/createMPA.ts @@ -30,7 +30,6 @@ export function createMPARules( { name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -62,7 +61,6 @@ export function createMPARules( { name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -91,7 +89,6 @@ export function createMPARules( { name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createSPA.test.ts b/packages/config/src/rules/request/createSPA.test.ts index b7acd3fc..b64b8bec 100644 --- a/packages/config/src/rules/request/createSPA.test.ts +++ b/packages/config/src/rules/request/createSPA.test.ts @@ -19,7 +19,6 @@ describe('createSPARules', () => { expect(staticAssetsRule).toEqual({ name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -54,7 +53,6 @@ describe('createSPARules', () => { expect(indexRedirectRule).toEqual({ name: 'Redirect to index.html', description: 'Handle all routes by rewriting to index.html for client-side routing', - active: true, criteria: [ [ { diff --git a/packages/config/src/rules/request/createSPA.ts b/packages/config/src/rules/request/createSPA.ts index e98679a6..d15d4ba7 100644 --- a/packages/config/src/rules/request/createSPA.ts +++ b/packages/config/src/rules/request/createSPA.ts @@ -30,7 +30,6 @@ export function createSPARules( { name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -62,7 +61,6 @@ export function createSPARules( { name: 'Redirect to index.html', description: 'Handle all routes by rewriting to index.html for client-side routing', - active: true, criteria: [ [ { diff --git a/packages/config/src/versions/accessors.test.ts b/packages/config/src/versions/accessors.test.ts index bd3a6166..aa196c50 100644 --- a/packages/config/src/versions/accessors.test.ts +++ b/packages/config/src/versions/accessors.test.ts @@ -82,6 +82,7 @@ describe('version accessors', () => { 'connectors', 'functions', 'environments', + 'deployments', ]); }); diff --git a/packages/config/src/versions/registry.test.ts b/packages/config/src/versions/registry.test.ts index 1d5acd7d..998e73f7 100644 --- a/packages/config/src/versions/registry.test.ts +++ b/packages/config/src/versions/registry.test.ts @@ -156,8 +156,8 @@ describe('v6 support', () => { firewall: [], custom_pages: [], environments: [], + deployments: [], workloads: [], - workload_deployments: [], }); }); @@ -166,7 +166,6 @@ describe('v6 support', () => { expect(manifest.applications).toEqual([ { name: 'my-app', - active: true, debug: false, modules: { cache: { enabled: true }, @@ -184,9 +183,7 @@ describe('v6 support', () => { networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }], }); - expect(manifest.network_list).toEqual([ - { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'], active: true }, - ]); + expect(manifest.network_list).toEqual([{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }]); }); it('forwards the version to manifest helpers', () => { diff --git a/packages/config/src/versions/v6/azion.config.example.test.ts b/packages/config/src/versions/v6/azion.config.example.test.ts index 59cde718..e0ad1c5d 100644 --- a/packages/config/src/versions/v6/azion.config.example.test.ts +++ b/packages/config/src/versions/v6/azion.config.example.test.ts @@ -25,11 +25,12 @@ describe('complete azion.config example of the API v6', () => { 'firewall', 'environments', 'workloads', - 'workload_deployments', + 'deployments', 'purge', ]), ); - expect(manifest.workload_deployments).toHaveLength(1); + expect(manifest.deployments).toHaveLength(1); + expect(manifest).not.toHaveProperty('workload_deployments'); expect(manifest.workloads[0].bindings).toEqual([ { environment_name: 'production', diff --git a/packages/config/src/versions/v6/azion.config.example.ts b/packages/config/src/versions/v6/azion.config.example.ts index 5dcb0296..e989225b 100644 --- a/packages/config/src/versions/v6/azion.config.example.ts +++ b/packages/config/src/versions/v6/azion.config.example.ts @@ -22,6 +22,11 @@ const config: AzionConfigV6 = { prefix: 'v1', }, }, + // connectors and network lists the function uses at runtime, which a release includes with it + dependencies: [ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-ip-allowlist' }, + ], }, ], storage: [ @@ -35,7 +40,6 @@ const config: AzionConfigV6 = { connectors: [ { name: 'my-storage-connector', - active: true, type: 'storage', attributes: { bucket: 'my-bucket-assets', @@ -44,7 +48,6 @@ const config: AzionConfigV6 = { }, { name: 'my-origin', - active: true, type: 'http', attributes: { addresses: [ @@ -72,7 +75,6 @@ const config: AzionConfigV6 = { applications: [ { name: 'my-app', - active: true, debug: false, edgeCacheEnabled: true, functionsEnabled: true, @@ -92,13 +94,11 @@ const config: AzionConfigV6 = { { name: 'Run the function', description: 'Run the function for the API paths', - active: true, criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/api' }]], behaviors: [{ type: 'run_function', attributes: { value: 'my-function' } }], }, { name: 'Serve from the storage', - active: true, criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], behaviors: [ { type: 'set_cache_policy', attributes: { value: 'my-cache' } }, @@ -109,7 +109,6 @@ const config: AzionConfigV6 = { response: [ { name: 'Add a header', - active: true, criteria: [[{ variable: '${status}', conditional: 'if', operator: 'is_equal', argument: '200' }]], behaviors: [{ type: 'add_response_header', attributes: { value: 'X-Served-By: azion' } }], }, @@ -128,7 +127,6 @@ const config: AzionConfigV6 = { customPages: [ { name: 'my-custom-pages', - active: true, pages: [ { code: '404', @@ -141,13 +139,12 @@ const config: AzionConfigV6 = { }, ], networkList: [ - { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'], active: true }, - { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'], active: true }, + { name: 'my-ip-allowlist', type: 'ip_cidr', items: ['10.0.0.1/32', '192.168.1.0/24'] }, + { name: 'allowed-countries', type: 'countries', items: ['US', 'BR'] }, ], waf: [ { name: 'my-waf', - active: true, engineSettings: { engineVersion: '2021-Q3', type: 'score', @@ -164,7 +161,6 @@ const config: AzionConfigV6 = { firewall: [ { name: 'my-firewall', - active: true, debugRules: false, functions: false, networkProtection: true, @@ -172,13 +168,11 @@ const config: AzionConfigV6 = { rules: [ { name: 'Allow the trusted networks', - active: true, criteria: [{ variable: 'network', conditional: 'if', operator: 'is_in_list', argument: 'my-ip-allowlist' }], behaviors: [{ type: 'bypass' }], }, { name: 'Protect with the WAF', - active: true, criteria: [{ variable: 'request_uri', conditional: 'if', operator: 'starts_with', argument: '/admin' }], behaviors: [{ type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }], }, @@ -194,27 +188,24 @@ const config: AzionConfigV6 = { robotsPolicy: 'respect_origin', }, ], + // the application, firewall and custom page a deployment serves are set by the Azion CLI when it creates the release + deployments: [ + { + name: 'my-deployment', + description: 'Main deployment', + bindingPolicy: 'FLEXIBLE', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], workloads: [ { name: 'my-workload', - active: true, infrastructure: 1, workloadDomainAllowAccess: true, tls: { minimumVersion: 'tls_1_3' }, protocols: { http: { versions: ['http1', 'http2', 'http3'], httpPorts: [80], httpsPorts: [443], quicPorts: [443] }, }, - deployments: [ - { - name: 'my-deployment', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-custom-pages' }, - }, - }, - ], bindings: [ { environment: 'production', diff --git a/packages/config/src/versions/v6/constants.ts b/packages/config/src/versions/v6/constants.ts index c38e8c5f..bfcea8a0 100644 --- a/packages/config/src/versions/v6/constants.ts +++ b/packages/config/src/versions/v6/constants.ts @@ -108,9 +108,76 @@ export const ENVIRONMENT_ROBOTS_POLICIES = ['index', 'noindex', 'respect_origin' export const ENVIRONMENT_BRANCH_TRACKING_MODES = ['branch_is', 'branch_starts_with', 'branch_ends_with'] as const; -export const DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls'] as const; - -export const WORKLOAD_DEPLOYMENT_STRATEGY_TYPES = ['default'] as const; +export const ENVIRONMENT_DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls'] as const; + +export const DEPLOYMENT_POLICIES = ['single_version', 'versioned_urls', 'latest'] as const; + +export const DEPLOYMENT_BINDING_POLICIES = ['STRICT', 'FLEXIBLE'] as const; + +export const FUNCTION_DEPENDENCY_TYPES = ['connector', 'network_list'] as const; + +/** + * Module of an application that each request phase behavior needs enabled (`RequestPhaseBehaviorRequest`). + */ +export const APPLICATION_REQUEST_BEHAVIOR_MODULES = { + forward_cookies: 'application_accelerator', + optimize_images: 'image_processor', + bypass_cache: 'cache', + filter_request_cookie: 'application_accelerator', + run_function: 'functions', + rewrite_request: 'application_accelerator', + capture_match_groups: 'application_accelerator', + add_request_cookie: 'application_accelerator', +} as const; + +/** + * Module of an application that each response phase behavior needs enabled (`ResponsePhaseBehaviorRequest`). + */ +export const APPLICATION_RESPONSE_BEHAVIOR_MODULES = { + run_function: 'functions', + set_cookie: 'application_accelerator', + capture_match_groups: 'application_accelerator', +} as const; + +/** + * Every criterion variable of an application rule except `${uri}` needs the application accelerator module. + */ +export const APPLICATION_ACCELERATOR_FREE_VARIABLES = ['uri'] as const; + +export const FIREWALL_MODULES = ['waf', 'network_protection', 'functions'] as const; + +/** + * Modules of a firewall of which at least one must be enabled for each behavior (`FirewallBehaviorRequest`). + */ +export const FIREWALL_BEHAVIOR_MODULES: Record = { + deny: FIREWALL_MODULES, + drop: FIREWALL_MODULES, + bypass: FIREWALL_MODULES, + set_custom_response: FIREWALL_MODULES, + set_rate_limit: FIREWALL_MODULES, + set_waf: FIREWALL_MODULES, + run_function: ['functions'], +}; + +/** + * Modules of a firewall of which at least one must be enabled for each criterion variable + * (`FirewallCriterionFieldRequest`). A variable that is not listed does not need any module. + */ +export const FIREWALL_VARIABLE_MODULES: Record = { + header_accept: ['waf'], + header_accept_encoding: ['waf'], + header_accept_language: ['waf'], + header_cookie: ['waf'], + header_origin: ['waf'], + header_referer: ['waf'], + header_user_agent: ['waf'], + host: FIREWALL_MODULES, + network: ['network_protection'], + request_args: ['waf'], + request_method: ['waf'], + request_uri: FIREWALL_MODULES, + scheme: FIREWALL_MODULES, +}; export const WORKLOADS_ACCESS_TYPES = ['read_only', 'read_write', 'restricted'] as const; diff --git a/packages/config/src/versions/v6/index.ts b/packages/config/src/versions/v6/index.ts index ccc0f1c3..68d458ef 100644 --- a/packages/config/src/versions/v6/index.ts +++ b/packages/config/src/versions/v6/index.ts @@ -12,9 +12,9 @@ const accessors: ConfigVersionAccessors = { const storage = (config as AzionConfigV6).storage?.[0]; return storage ? { bucket: storage.name, prefix: storage.prefix ?? '' } : undefined; }, - // the keys of a preset that only serve an application, which a firewall-only project does not have. The - // environments only exist to bind a workload to an application, so they go along with the workloads - firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments'], + // the keys of a preset that only serve an application, which a firewall-only project does not have. The environments + // and the deployments only exist to bind a workload to an application, so they go along with the workloads + firewallReplacedKeys: ['applications', 'workloads', 'connectors', 'functions', 'environments', 'deployments'], }; // v6 has its own AzionConfig type, which is not assignable to the default (v4) one used by the shared contract diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts index 9151536d..b2904f7e 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.test.ts @@ -19,7 +19,6 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(result).toEqual([ { name: 'my-app', - active: true, debug: false, modules: { cache: { enabled: true }, @@ -37,9 +36,8 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { applications: [ { name: 'my-app', - active: false, debug: true, - edgeCacheEnabled: false, + edgeCacheEnabled: true, functionsEnabled: true, applicationAcceleratorEnabled: false, imageProcessorEnabled: true, @@ -50,10 +48,9 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(result).toEqual([ { name: 'my-app', - active: false, debug: true, modules: { - cache: { enabled: false }, + cache: { enabled: true }, functions: { enabled: true }, application_accelerator: { enabled: false }, image_processor: { enabled: true }, @@ -89,7 +86,7 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(application.rules).toHaveLength(1); expect(application.rules[0]).toEqual(expect.objectContaining({ phase: 'request' })); - expect(application.functions_instances).toEqual([{ name: 'instance', function: 'fn', args: {}, active: true }]); + expect(application.functions_instances).toEqual([{ name: 'instance', function: 'fn', args: {} }]); }); it('should write the cache settings to the manifest as cache_settings and read them back', () => { @@ -159,7 +156,7 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { const [application] = transformedPayload.applications!; expect(application.rules?.request?.[0].name).toBe('Execute Function'); - expect(application.functionsInstances).toEqual([{ name: 'instance', ref: 'fn', args: {}, active: true }]); + expect(application.functionsInstances).toEqual([{ name: 'instance', ref: 'fn', args: {} }]); expect(application.functionsEnabled).toBe(true); }); }); @@ -180,7 +177,6 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { applications: [ { name: 'my-app', - active: false, debug: true, modules: { cache: { enabled: false }, @@ -197,7 +193,6 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(transformedPayload.applications).toEqual([ { name: 'my-app', - active: false, debug: true, edgeCacheEnabled: false, functionsEnabled: true, @@ -213,7 +208,6 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { applications: [ { name: 'my-app', - active: true, debug: false, edgeCacheEnabled: true, functionsEnabled: false, @@ -230,4 +224,82 @@ describe('ApplicationProcessConfigStrategy (v6)', () => { expect(transformedPayload).toEqual(config); }); }); + + describe('modules the rules need', () => { + const request = (behaviors: object[], variable = '${uri}') => ({ + request: [ + { + name: 'rule', + criteria: [[{ variable, conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors, + }, + ], + }); + const manifest = (application: object) => + strategy.transformToManifest({ version: 6, applications: [{ name: 'my-app', ...application }] } as AzionConfigV6); + + it('should write the cache module as enabled', () => { + expect(manifest({})[0].modules.cache).toEqual({ enabled: true }); + }); + + it('should accept the behaviors of the modules that are enabled', () => { + expect(() => + manifest({ + imageProcessorEnabled: true, + functionsEnabled: true, + rules: request([{ type: 'optimize_images' }, { type: 'run_function', attributes: { value: 10 } }]), + }), + ).not.toThrow(); + }); + + it('should throw when a behavior needs a module that is disabled', () => { + expect(() => manifest({ rules: request([{ type: 'optimize_images' }]) })).toThrow( + 'Application "my-app" rule "rule" uses the behavior "optimize_images", which needs the image_processor module: enable it with imageProcessorEnabled.', + ); + expect(() => + manifest({ + applicationAcceleratorEnabled: false, + rules: request([{ type: 'rewrite_request', attributes: { value: '/x' } }]), + }), + ).toThrow('which needs the application_accelerator module'); + expect(() => manifest({ rules: request([{ type: 'run_function', attributes: { value: 10 } }]) })).toThrow( + 'which needs the functions module', + ); + }); + + it('should not need the functions module flag when the application has function instances', () => { + expect(() => + manifest({ + functionsInstances: [{ name: 'instance', ref: 10 }], + rules: request([{ type: 'run_function', attributes: { value: 10 } }]), + }), + ).not.toThrow(); + }); + + it('should throw for a variable other than uri when the application accelerator is disabled', () => { + expect(() => + manifest({ applicationAcceleratorEnabled: false, rules: request([{ type: 'deliver' }], '${host}') }), + ).toThrow('uses the variable "host", which needs the application_accelerator module'); + expect(() => + manifest({ applicationAcceleratorEnabled: false, rules: request([{ type: 'deliver' }]) }), + ).not.toThrow(); + }); + + it('should check the response rules too', () => { + expect(() => + manifest({ + applicationAcceleratorEnabled: false, + rules: { + response: [ + { + name: 'r', + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'set_cookie', attributes: { value: 'a=b' } }], + }, + ], + }, + }), + ).toThrow('uses the behavior "set_cookie", which needs the application_accelerator module'); + }); + }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts index d393f776..ffe1b174 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/applicationProcessConfigStrategy.ts @@ -1,5 +1,10 @@ import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; -import type { AzionApplicationV6, AzionConfigV6 } from '../../../types'; +import { + APPLICATION_ACCELERATOR_FREE_VARIABLES, + APPLICATION_REQUEST_BEHAVIOR_MODULES, + APPLICATION_RESPONSE_BEHAVIOR_MODULES, +} from '../../../constants'; +import type { AzionApplicationV6, AzionConfigV6, AzionRuleV6 } from '../../../types'; import CacheProcessConfigStrategy from './cacheProcessConfigStrategy'; import DeviceGroupsProcessConfigStrategy from './deviceGroupsProcessConfigStrategy'; import FunctionInstancesProcessConfigStrategy from './functionInstancesProcessConfigStrategy'; @@ -9,6 +14,8 @@ import RulesProcessConfigStrategy from './rulesProcessConfigStrategy'; * ApplicationProcessConfigStrategy * @class ApplicationProcessConfigStrategy * @description Converts the v6 applications between the config and the manifest. + * The cache module cannot be disabled, and the behaviors and criterion variables of the rules need the modules the API + * documents (`RequestPhaseBehaviorRequest`, `ResponsePhaseBehaviorRequest` and the criterion fields). */ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy { private cacheStrategy = new CacheProcessConfigStrategy(); @@ -16,6 +23,42 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy) { + const flags: Record = { + functions: 'functionsEnabled (or declare functionsInstances)', + application_accelerator: 'applicationAcceleratorEnabled', + image_processor: 'imageProcessorEnabled', + cache: 'edgeCacheEnabled', + }; + const check = (rule: AzionRuleV6, behaviorModules: Record) => { + rule.behaviors.forEach((behavior) => { + const module = behaviorModules[behavior.type]; + if (module && !modules[module]?.enabled) { + throw new Error( + `Application "${app.name}" rule "${rule.name}" uses the behavior "${behavior.type}", which needs the ${module} module: enable it with ${flags[module]}.`, + ); + } + }); + rule.criteria.flat().forEach((criterion) => { + const variable = String(criterion.variable).replace(/^\$\{|\}$/g, ''); + if ( + !(APPLICATION_ACCELERATOR_FREE_VARIABLES as readonly string[]).includes(variable) && + !modules.application_accelerator.enabled + ) { + throw new Error( + `Application "${app.name}" rule "${rule.name}" uses the variable "${variable}", which needs the application_accelerator module: enable it with ${flags.application_accelerator}.`, + ); + } + }); + }; + + app.rules?.request?.forEach((rule) => check(rule, APPLICATION_REQUEST_BEHAVIOR_MODULES)); + app.rules?.response?.forEach((rule) => check(rule, APPLICATION_RESPONSE_BEHAVIOR_MODULES)); + } + transformToManifest(config: AzionConfigV6) { if (!config.applications || !Array.isArray(config.applications)) { return []; @@ -25,11 +68,10 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy = { name: app.name, - active: app.active ?? true, debug: app.debug ?? false, modules: { cache: { - enabled: app.edgeCacheEnabled ?? true, + enabled: true, }, functions: { enabled: @@ -44,6 +86,8 @@ class ApplicationProcessConfigStrategy extends ProcessConfigStrategy ({ name: app.name, - active: app.active, debug: app.debug, edgeCacheEnabled: app.modules?.cache?.enabled, functionsEnabled: app.modules?.functions?.enabled, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts index 6598595c..886a57fd 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.test.ts @@ -16,10 +16,10 @@ describe('FunctionInstancesProcessConfigStrategy (v6)', () => { it('should map an instance to the manifest and apply the defaults', () => { expect(strategy.transformToManifest([{ name: 'instance', ref: 'fn' }], config)).toEqual([ - { name: 'instance', function: 'fn', args: {}, active: true }, + { name: 'instance', function: 'fn', args: {} }, ]); - expect(strategy.transformToManifest([{ name: 'i', ref: 'fn', args: { a: 1 }, active: false }], config)).toEqual([ - { name: 'i', function: 'fn', args: { a: 1 }, active: false }, + expect(strategy.transformToManifest([{ name: 'i', ref: 'fn', args: { a: 1 } }], config)).toEqual([ + { name: 'i', function: 'fn', args: { a: 1 } }, ]); }); @@ -34,7 +34,7 @@ describe('FunctionInstancesProcessConfigStrategy (v6)', () => { it('should not validate a function referenced by id', () => { expect(strategy.transformToManifest([{ name: 'instance', ref: 10 }], { version: 6 })).toEqual([ - { name: 'instance', function: 10, args: {}, active: true }, + { name: 'instance', function: 10, args: {} }, ]); }); }); @@ -46,7 +46,7 @@ describe('FunctionInstancesProcessConfigStrategy (v6)', () => { it('should map the manifest instances back to the config', () => { expect(strategy.transformToConfig([{ name: 'i', function: 10, args: { a: 1 } }])).toEqual([ - { name: 'i', ref: 10, args: { a: 1 }, active: true }, + { name: 'i', ref: 10, args: { a: 1 } }, ]); }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts index e9be0cfe..dec21149 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/functionInstancesProcessConfigStrategy.ts @@ -40,7 +40,6 @@ class FunctionInstancesProcessConfigStrategy extends ProcessConfigStrategy; active?: boolean }>, + payload: Array<{ name: string; function: number | string; args?: Record }>, ): AzionFunctionInstance[] { if (!Array.isArray(payload) || payload.length === 0) { return []; @@ -61,7 +60,6 @@ class FunctionInstancesProcessConfigStrategy extends ProcessConfigStrategy { response: [ { name: 'Add header', - active: false, criteria: [[{ variable: 'status', conditional: 'if', operator: 'exists' }]], behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], }, @@ -29,7 +28,6 @@ describe('RulesProcessConfigStrategy (v6)', () => { rule: { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], behaviors: [{ type: 'run_function', attributes: { value: 'fn' } }], }, @@ -39,7 +37,6 @@ describe('RulesProcessConfigStrategy (v6)', () => { rule: { name: 'Add header', description: undefined, - active: false, criteria: [[{ variable: '${status}', conditional: 'if', operator: 'exists' }]], behaviors: [{ type: 'add_response_header', attributes: { value: 'x-test: 1' } }], }, @@ -136,8 +133,8 @@ describe('RulesProcessConfigStrategy (v6)', () => { expect(result.request).toHaveLength(1); expect(result.response).toHaveLength(1); - expect(result.request![0]).toEqual(expect.objectContaining({ name: 'Execute Function', active: true })); - expect(result.response![0]).toEqual(expect.objectContaining({ name: 'Add header', active: false })); + expect(result.request![0]).toEqual(expect.objectContaining({ name: 'Execute Function' })); + expect(result.response![0]).toEqual(expect.objectContaining({ name: 'Add header' })); }); }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts index c4423f4e..899e0583 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/application/rulesProcessConfigStrategy.ts @@ -106,7 +106,6 @@ class RulesProcessConfigStrategy extends ProcessConfigStrategy { rule: { name: rule.name, description: rule.description, - active: rule.active !== undefined ? rule.active : true, criteria: rule.criteria.map((criteriaGroup) => criteriaGroup.map((criterion) => ({ variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, @@ -133,7 +132,6 @@ class RulesProcessConfigStrategy extends ProcessConfigStrategy { rule: { name: rule.name, description: rule.description, - active: rule.active !== undefined ? rule.active : true, criteria: rule.criteria.map((criteriaGroup) => criteriaGroup.map((criterion) => ({ variable: criterion.variable.startsWith('${') ? criterion.variable : `\${${criterion.variable}}`, @@ -172,7 +170,6 @@ class RulesProcessConfigStrategy extends ProcessConfigStrategy { const rule: AzionRule = { name: manifestRule.rule.name, description: manifestRule.rule.description, - active: manifestRule.rule.active !== undefined ? manifestRule.rule.active : true, criteria: manifestRule.rule.criteria.map((criteriaGroup) => criteriaGroup.map((criterion) => { const baseCriterion = { diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts index b9175055..d7f53b49 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.test.ts @@ -21,17 +21,17 @@ describe('ConnectorProcessConfigStrategy (v6)', () => { expect( toManifest([ { name: 'with-prefix', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, - { name: 'no-prefix', type: 'storage', active: false, attributes: { bucket: 'my-bucket' } }, + { name: 'no-prefix', type: 'storage', attributes: { bucket: 'my-bucket' } }, ]), ).toEqual([ - { name: 'with-prefix', active: true, type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, - { name: 'no-prefix', active: false, type: 'storage', attributes: { bucket: 'my-bucket' } }, + { name: 'with-prefix', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'no-prefix', type: 'storage', attributes: { bucket: 'my-bucket' } }, ]); }); it('should map a live ingest connector', () => { expect(toManifest([{ name: 'ingest', type: 'live_ingest', attributes: { region: 'br-east-1' } }])).toEqual([ - { name: 'ingest', active: true, type: 'live_ingest', attributes: { region: 'br-east-1' } }, + { name: 'ingest', type: 'live_ingest', attributes: { region: 'br-east-1' } }, ]); }); @@ -42,10 +42,9 @@ describe('ConnectorProcessConfigStrategy (v6)', () => { expect(connector).toEqual({ name: 'origin', - active: true, type: 'http', attributes: { - addresses: [{ active: true, address: 'origin.example.com', http_port: 80, https_port: 443 }], + addresses: [{ address: 'origin.example.com', http_port: 80, https_port: 443 }], connection_options: { dns_resolution: 'both', transport_policy: 'preserve', @@ -69,11 +68,9 @@ describe('ConnectorProcessConfigStrategy (v6)', () => { { name: 'origin', type: 'http', - active: false, attributes: { addresses: [ { - active: false, address: 'origin.example.com', httpPort: 8080, httpsPort: 8443, @@ -115,12 +112,10 @@ describe('ConnectorProcessConfigStrategy (v6)', () => { expect(connector).toEqual({ name: 'origin', - active: false, type: 'http', attributes: { addresses: [ { - active: false, address: 'origin.example.com', http_port: 8080, https_port: 8443, @@ -171,16 +166,14 @@ describe('ConnectorProcessConfigStrategy (v6)', () => { it('should round trip storage, live ingest and http connectors through the manifest', () => { const connectors: AzionConnectorV6[] = [ - { name: 'files', type: 'storage', active: true, attributes: { bucket: 'my-bucket', prefix: 'p' } }, - { name: 'ingest', type: 'live_ingest', active: true, attributes: { region: 'us-east-2' } }, + { name: 'files', type: 'storage', attributes: { bucket: 'my-bucket', prefix: 'p' } }, + { name: 'ingest', type: 'live_ingest', attributes: { region: 'us-east-2' } }, { name: 'origin', type: 'http', - active: true, attributes: { addresses: [ { - active: true, address: 'origin.example.com', httpPort: 80, httpsPort: 443, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts index 60a083a9..3755c174 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/connectorProcessConfigStrategy.ts @@ -20,7 +20,6 @@ class ConnectorProcessConfigStrategy extends ProcessConfigStrategy { const baseConnector = { name: connector.name, - active: connector.active ?? true, type: connector.type, }; @@ -52,7 +51,6 @@ class ConnectorProcessConfigStrategy extends ProcessConfigStrategy ({ - active: addr.active ?? true, address: addr.address, http_port: addr.httpPort ?? 80, https_port: addr.httpsPort ?? 443, @@ -131,7 +129,6 @@ class ConnectorProcessConfigStrategy extends ProcessConfigStrategy { const baseConnector = { name: connector.name, - active: connector.active, type: connector.type, }; @@ -162,7 +159,6 @@ class ConnectorProcessConfigStrategy extends ProcessConfigStrategy ({ - active: addr.active, address: addr.address, httpPort: addr.http_port, httpsPort: addr.https_port, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts index 7d594be5..3926554c 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.test.ts @@ -34,7 +34,6 @@ describe('CustomPagesProcessConfigStrategy (v6)', () => { ).toEqual([ { name: 'errors', - active: true, pages: [ { code: '404', @@ -54,7 +53,6 @@ describe('CustomPagesProcessConfigStrategy (v6)', () => { withPages([ { name: 'errors', - active: false, pages: [ { code: 'default', @@ -71,7 +69,6 @@ describe('CustomPagesProcessConfigStrategy (v6)', () => { ).toEqual([ { name: 'errors', - active: false, pages: [ { code: 'default', @@ -129,7 +126,6 @@ describe('CustomPagesProcessConfigStrategy (v6)', () => { custom_pages: [ { name: 'errors', - active: true, pages: [ { code: '404', @@ -148,7 +144,6 @@ describe('CustomPagesProcessConfigStrategy (v6)', () => { expect(transformedPayload.customPages).toEqual([ { name: 'errors', - active: true, pages: [ { code: '404', diff --git a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts index d3c0c189..39bfc3c2 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/customPagesProcessConfigStrategy.ts @@ -50,7 +50,6 @@ class CustomPagesProcessConfigStrategy extends ProcessConfigStrategy ({ code: pageEntry.code, page: { @@ -78,7 +77,6 @@ class CustomPagesProcessConfigStrategy extends ProcessConfigStrategy ({ name: customPage.name, - active: customPage.active, // eslint-disable-next-line @typescript-eslint/no-explicit-any pages: customPage.pages.map((pageEntry: any) => ({ code: pageEntry.code, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts new file mode 100644 index 00000000..a2f53993 --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.test.ts @@ -0,0 +1,96 @@ +import type { AzionConfigV6 } from '../../types'; +import DeploymentProcessConfigStrategy from './deploymentProcessConfigStrategy'; + +describe('DeploymentProcessConfigStrategy (v6)', () => { + let strategy: DeploymentProcessConfigStrategy; + + beforeEach(() => { + strategy = new DeploymentProcessConfigStrategy(); + }); + + describe('transformToManifest', () => { + it('should return an empty array when there are no deployments', () => { + expect(strategy.transformToManifest({ version: 6 })).toEqual([]); + }); + + it('should write the binding policy and apply the defaults the API requires to the other fields', () => { + expect( + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + }), + ).toEqual([ + { + name: 'default-deployment', + description: null, + binding_policy: 'FLEXIBLE', + strategy_defaults: {}, + }, + ]); + }); + + it('should write the binding policy that the config declares', () => { + const policies = (['STRICT', 'FLEXIBLE'] as const).map( + (bindingPolicy) => + strategy.transformToManifest({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy }], + })?.[0].binding_policy, + ); + + expect(policies).toEqual(['STRICT', 'FLEXIBLE']); + }); + + it('should map every field of the deployment to the manifest', () => { + const [deployment] = strategy.transformToManifest({ + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }); + + expect(deployment).toEqual({ + name: 'default-deployment', + description: 'Default', + binding_policy: 'STRICT', + strategy_defaults: { skew_protection: { enabled: true, default_ttl_seconds: 3600 } }, + deployment_policy: 'single_version', + }); + }); + }); + + describe('transformToConfig', () => { + it('should not set deployments when the manifest has none', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); + expect(transformedPayload.deployments).toBeUndefined(); + }); + + it('should round trip a deployment through the manifest', () => { + const config: AzionConfigV6 = { + version: 6, + deployments: [ + { + name: 'default-deployment', + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, + }, + ], + }; + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig({ deployments: strategy.transformToManifest(config) }, transformedPayload); + + expect(transformedPayload.deployments).toEqual(config.deployments); + }); + }); +}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts new file mode 100644 index 00000000..9670622c --- /dev/null +++ b/packages/config/src/versions/v6/processStrategy/implementations/deploymentProcessConfigStrategy.ts @@ -0,0 +1,68 @@ +import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; +import type { AzionConfigV6, AzionDeploymentV6 } from '../../types'; + +/** + * DeploymentProcessConfigStrategy + * @class DeploymentProcessConfigStrategy + * @description Converts the v6 deployments between the config and the manifest. + * The creation of a deployment requires `binding_policy`, which the config must declare. The replacement of a + * deployment also requires `description` and `strategy_defaults`, so the manifest defaults them to no description and + * no skew protection. + * The application a deployment serves is not part of it: the Azion CLI sets it when it creates a release. + */ +class DeploymentProcessConfigStrategy extends ProcessConfigStrategy { + transformToManifest(config: AzionConfigV6) { + if (!Array.isArray(config?.deployments) || config.deployments.length === 0) { + return []; + } + + return config.deployments.map((deployment: AzionDeploymentV6) => { + const skewProtection = deployment.strategyDefaults?.skewProtection; + + return { + name: deployment.name, + description: deployment.description ?? null, + binding_policy: deployment.bindingPolicy, + strategy_defaults: skewProtection + ? { + skew_protection: { + enabled: skewProtection.enabled, + default_ttl_seconds: skewProtection.defaultTtlSeconds, + }, + } + : {}, + ...(deployment.deploymentPolicy && { deployment_policy: deployment.deploymentPolicy }), + }; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transformToConfig(payload: { deployments?: any[] }, transformedPayload: AzionConfigV6) { + if (!Array.isArray(payload?.deployments) || payload.deployments.length === 0) { + return; + } + + transformedPayload.deployments = payload.deployments.map((deployment) => { + const skewProtection = deployment.strategy_defaults?.skew_protection; + + return { + name: deployment.name, + description: deployment.description, + bindingPolicy: deployment.binding_policy, + deploymentPolicy: deployment.deployment_policy, + strategyDefaults: skewProtection + ? { + skewProtection: { + enabled: skewProtection.enabled, + defaultTtlSeconds: skewProtection.default_ttl_seconds, + }, + } + : undefined, + }; + }); + + return transformedPayload.deployments; + } +} + +export default DeploymentProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts index 98ba29d6..16fa8dfb 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.test.ts @@ -26,7 +26,6 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { runtime: 'azion_js', default_args: {}, execution_environment: 'application', - active: true, path: './functions/index.js', }, ]); @@ -42,7 +41,6 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { runtime: 'azion_js', defaultArgs: { key: 'value' }, executionEnvironment: 'firewall', - active: false, }, ], }); @@ -53,7 +51,6 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { runtime: 'azion_js', default_args: { key: 'value' }, execution_environment: 'firewall', - active: false, path: './functions/index.js', }, ]); @@ -117,7 +114,6 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { runtime: 'azion_js', default_args: { key: 'value' }, execution_environment: 'firewall', - active: false, }, ], }, @@ -131,9 +127,59 @@ describe('FunctionsProcessConfigStrategy (v6)', () => { runtime: 'azion_js', defaultArgs: { key: 'value' }, executionEnvironment: 'firewall', - active: false, }, ]); }); }); + + describe('dependencies', () => { + const config = (dependencies: object[], extra: Partial = {}) => + ({ + version: 6, + connectors: [{ name: 'my-origin', type: 'live_ingest', attributes: { region: 'us-east-1' } }], + networkList: [{ name: 'my-list', type: 'countries', items: ['BR'] }], + functions: [{ name: 'fn', path: './fn.js', dependencies }], + ...extra, + }) as AzionConfigV6; + + it('should write the dependencies with the name or the ID of the resource', () => { + const [fn] = strategy.transformToManifest( + config([ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 'my-list' }, + { type: 'connector', ref: 10 }, + ]), + ); + + expect(fn.dependencies).toEqual([ + { type: 'connector', id: 'my-origin' }, + { type: 'network_list', id: 'my-list' }, + { type: 'connector', id: 10 }, + ]); + }); + + it('should not write dependencies when the function has none', () => { + expect(strategy.transformToManifest(config([]))[0]).not.toHaveProperty('dependencies'); + }); + + it('should throw when the connector or network list is not declared', () => { + expect(() => strategy.transformToManifest(config([{ type: 'connector', ref: 'other' }]))).toThrow( + 'Function "fn" depends on non-existent Connector "other".', + ); + expect(() => strategy.transformToManifest(config([{ type: 'network_list', ref: 'my-origin' }]))).toThrow( + 'Function "fn" depends on non-existent Network List "my-origin".', + ); + }); + + it('should read the dependencies back from the manifest', () => { + const transformedPayload: AzionConfigV6 = { version: 6 }; + + strategy.transformToConfig( + { functions: [{ name: 'fn', dependencies: [{ type: 'connector', id: 'my-origin' }] }] }, + transformedPayload, + ); + + expect(transformedPayload.functions?.[0].dependencies).toEqual([{ type: 'connector', ref: 'my-origin' }]); + }); + }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts index c124ac56..91a9eeaf 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/functionsProcessConfigStrategy.ts @@ -1,6 +1,6 @@ import type { FunctionExecutionEnvironment, FunctionRuntime } from '../../../../types'; import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; -import type { AzionConfigV6 } from '../../types'; +import type { AzionConfigV6, AzionFunctionDependencyV6 } from '../../types'; /** * FunctionsProcessConfigStrategy V6 @@ -21,6 +21,19 @@ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy resource.name === dependency.ref)) { + const label = dependency.type === 'connector' ? 'Connector' : 'Network List'; + throw new Error(`Function "${functionName}" depends on non-existent ${label} "${dependency.ref}".`); + } + } + /** * Transform azion.config Functions to V6 manifest format */ @@ -40,9 +53,15 @@ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy 0 && { + dependencies: func.dependencies.map((dependency) => { + this.validateDependency(config, dependency, func.name); + return { type: dependency.type, id: dependency.ref }; + }), + }), }; }); } @@ -57,7 +76,7 @@ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy; execution_environment?: string; - active?: boolean; + dependencies?: Array<{ type: string; id: string | number }>; }>; }, transformedPayload: AzionConfigV6, @@ -72,7 +91,12 @@ class FunctionsProcessConfigStrategy extends ProcessConfigStrategy ({ + type: dependency.type as AzionFunctionDependencyV6['type'], + ref: dependency.id, + })), + }), })); } } diff --git a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts index 3a4c0286..97001041 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/purgeProcessConfigStrategy.test.ts @@ -19,14 +19,14 @@ describe('PurgeProcessConfigStrategy (v6)', () => { version: 6, purge: [ { type: 'url', items: ['https://example.com/path'] }, - { type: 'wildcard', items: ['https://example.com/path*'], layer: 'tiered_cache' }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'cache' }, { type: 'cachekey', items: ['example.com/path'] }, ], }; expect(strategy.transformToManifest(config)).toEqual([ { type: 'url', items: ['https://example.com/path'], layer: 'cache' }, - { type: 'wildcard', items: ['https://example.com/path*'], layer: 'tiered_cache' }, + { type: 'wildcard', items: ['https://example.com/path*'], layer: 'cache' }, { type: 'cachekey', items: ['example.com/path'], layer: 'cache' }, ]); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts index b1d92001..be3894e1 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.test.ts @@ -40,19 +40,17 @@ describe('FirewallProcessConfigStrategy (v6)', () => { waf: { enabled: false }, }, debug: false, - active: true, }, ]); }); it('should write active and debugRules to the manifest (v4 ignored them)', () => { const [firewall] = strategy.transformToManifest( - withFirewall({ name: 'my-firewall', active: false, debugRules: true, functions: false, waf: true }), + withFirewall({ name: 'my-firewall', debugRules: true, functions: false, waf: true }), ); expect(firewall).toEqual( expect.objectContaining({ - active: false, debug: true, modules: { functions: { enabled: false }, @@ -85,7 +83,6 @@ describe('FirewallProcessConfigStrategy (v6)', () => { { name: 'rule', description: 'Block admin', - active: true, behaviors: [{ type: 'deny' }], criteria: [ [ @@ -270,7 +267,7 @@ describe('FirewallProcessConfigStrategy (v6)', () => { name: 'my-firewall', functionsInstances: [ { name: 'instance', ref: 'fn', args: { a: 1 } }, - { name: 'off', ref: 10, active: false }, + { name: 'off', ref: 10 }, ], }; @@ -278,8 +275,8 @@ describe('FirewallProcessConfigStrategy (v6)', () => { strategy.transformToManifest(withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }))[0] .functions_instances, ).toEqual([ - { name: 'instance', args: { a: 1 }, active: true, function: 'fn' }, - { name: 'off', args: {}, active: false, function: 10 }, + { name: 'instance', args: { a: 1 }, function: 'fn' }, + { name: 'off', args: {}, function: 10 }, ]); expect(() => strategy.transformToManifest(withFirewall(firewall))).toThrow( 'Function instance "instance" references non-existent Function "fn".', @@ -298,7 +295,6 @@ describe('FirewallProcessConfigStrategy (v6)', () => { it('should round trip a firewall through the manifest', () => { const firewall: AzionFirewallV6 = { name: 'my-firewall', - active: true, debugRules: true, functions: true, networkProtection: true, @@ -307,7 +303,6 @@ describe('FirewallProcessConfigStrategy (v6)', () => { { name: 'rule', description: 'Block admin', - active: true, criteria: [{ variable: '${request_uri}', conditional: 'if', operator: 'starts_with', argument: '/admin' }], behaviors: [ { type: 'set_waf', attributes: { mode: 'blocking', wafId: 'my-waf' } }, @@ -319,12 +314,11 @@ describe('FirewallProcessConfigStrategy (v6)', () => { }, { name: 'deny', - active: true, criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], behaviors: [{ type: 'deny' }], }, ], - functionsInstances: [{ name: 'instance', ref: 'fn', args: { a: 1 }, active: true }], + functionsInstances: [{ name: 'instance', ref: 'fn', args: { a: 1 } }], }; const config = withFirewall(firewall, { functions: [{ name: 'fn', path: './fn.js' }] }); const transformedPayload: AzionConfigV6 = { version: 6 }; @@ -334,4 +328,46 @@ describe('FirewallProcessConfigStrategy (v6)', () => { expect(transformedPayload.firewall).toEqual([firewall]); }); }); + + describe('modules the rules need', () => { + const rule = (variable: string, behaviors: AzionFirewallBehaviorV6[] = [{ type: 'deny' }]) => ({ + name: 'rule', + criteria: [{ variable, conditional: 'if' as const, operator: 'matches' as const, argument: 'x' }], + behaviors, + }); + const manifest = (firewall: Partial) => + strategy.transformToManifest(withFirewall({ name: 'my-firewall', ...firewall })); + + it('should accept the default modules (functions and network protection) for the variables they cover', () => { + expect(() => manifest({ rules: [rule('request_uri')] })).not.toThrow(); + expect(() => manifest({ rules: [rule('host', [{ type: 'drop' }])] })).not.toThrow(); + }); + + it('should throw when a variable needs the waf module and it is disabled', () => { + expect(() => manifest({ rules: [rule('header_user_agent')] })).toThrow( + 'Firewall "my-firewall" rule "rule" uses the variable "header_user_agent", which needs the waf (waf) module enabled.', + ); + expect(() => manifest({ waf: true, rules: [rule('${request_method}')] })).not.toThrow(); + }); + + it('should throw when the network variable needs the network protection module', () => { + expect(() => manifest({ networkProtection: false, rules: [rule('network')] })).toThrow( + 'which needs the network_protection (networkProtection) module enabled', + ); + }); + + it('should throw when no module is enabled for a behavior', () => { + expect(() => + manifest({ functions: false, networkProtection: false, waf: false, rules: [rule('request_uri')] }), + ).toThrow( + 'uses the behavior "deny", which needs one of the waf (waf), network_protection (networkProtection), functions (functions) modules enabled.', + ); + }); + + it('should throw when run_function needs the functions module', () => { + expect(() => + manifest({ functions: false, rules: [rule('network', [{ type: 'run_function', attributes: { value: 1 } }])] }), + ).toThrow('uses the behavior "run_function", which needs the functions (functions) module enabled.'); + }); + }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts index 5bf56247..9edcbed6 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/firewallProcessConfigStrategy.ts @@ -1,5 +1,6 @@ import type { AzionFunction } from '../../../../../types'; import ProcessConfigStrategy from '../../../../shared/processStrategy/processConfigStrategy'; +import { FIREWALL_BEHAVIOR_MODULES, FIREWALL_VARIABLE_MODULES } from '../../../constants'; import type { AzionConfigV6, AzionFirewallBehaviorV6, @@ -12,7 +13,9 @@ import type { * FirewallProcessConfigStrategy V6 * @class FirewallProcessConfigStrategy * @description Converts the v6 firewalls between the config and the manifest. - * Unlike v4, the `active` and `debugRules` of the firewall are written to the manifest. + * Unlike v4, the `debugRules` of the firewall is written to the manifest. + * The behaviors and criterion variables of the rules need the modules the API documents (`FirewallBehaviorRequest` and + * `FirewallCriterionFieldRequest`): at least one of the listed modules must be enabled. */ class FirewallProcessConfigStrategy extends ProcessConfigStrategy { /** @@ -47,6 +50,41 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy } } + /** + * Validate that the modules the rules need are enabled + */ + private validateModules(fw: AzionFirewallV6, modules: Record) { + const flags: Record = { + functions: 'functions', + network_protection: 'networkProtection', + waf: 'waf', + }; + const requireOneOf = (needed: readonly string[], ruleName: string, what: string) => { + if (!needed.some((module) => modules[module]?.enabled)) { + throw new Error( + `Firewall "${fw.name}" rule "${ruleName}" uses ${what}, which needs ${ + needed.length === 1 ? 'the' : 'one of the' + } ${needed.map((module) => `${module} (${flags[module]})`).join(', ')} module${ + needed.length === 1 ? '' : 's' + } enabled.`, + ); + } + }; + + fw.rules?.forEach((rule) => { + rule.behaviors.forEach((behavior) => { + const needed = FIREWALL_BEHAVIOR_MODULES[behavior.type]; + if (needed) requireOneOf(needed, rule.name, `the behavior "${behavior.type}"`); + }); + const variables = rule.criteria ? rule.criteria.map((criterion) => criterion.variable) : [rule.variable]; + variables.forEach((variable) => { + const name = String(variable).replace(/^\$\{|\}$/g, ''); + const needed = FIREWALL_VARIABLE_MODULES[name]; + if (needed) requireOneOf(needed, rule.name, `the variable "${name}"`); + }); + }); + } + transformToManifest(config: AzionConfigV6) { if (!config.firewall || !Array.isArray(config.firewall)) { return []; @@ -68,9 +106,10 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy }, }, debug: fw.debugRules ?? false, - active: fw.active ?? true, }; + this.validateModules(fw, payload.modules); + if (fw.rules && fw.rules.length > 0) { fw.rules.forEach((rule: AzionFirewallRuleV6) => rule.criteria?.forEach((criterion) => { @@ -87,7 +126,6 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy payload.rules_engine = fw.rules.map((rule: AzionFirewallRuleV6) => ({ name: rule.name, description: rule.description || '', - active: rule.active ?? true, behaviors: this.transformBehaviorsToManifest(rule.behaviors), criteria: rule.criteria ? [ @@ -117,7 +155,6 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy return { name: instance.name, args: instance.args || {}, - active: instance.active ?? true, function: instance.ref, }; }); @@ -192,7 +229,6 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy transformedPayload.firewall = payload.firewall.map((fw: any) => { const firewallConfig: AzionFirewallV6 = { name: fw?.name, - active: fw?.active ?? true, functions: fw?.modules?.functions?.enabled ?? false, networkProtection: fw?.modules?.network_protection?.enabled ?? false, waf: fw?.modules?.waf?.enabled ?? false, @@ -204,7 +240,6 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy firewallConfig.rules = fw.rules_engine.map((rule: any) => ({ name: rule.name, description: rule.description || undefined, - active: rule.active ?? true, behaviors: this.transformBehaviorsToConfig(rule.behaviors), // eslint-disable-next-line @typescript-eslint/no-explicit-any criteria: rule.criteria?.[0]?.map((criterion: any) => ({ ...criterion })) || [], @@ -216,7 +251,6 @@ class FirewallProcessConfigStrategy extends ProcessConfigStrategy firewallConfig.functionsInstances = fw.functions_instances.map((instance: any) => ({ name: instance.name, args: instance.args || {}, - active: instance.active ?? true, ref: instance.function, })); } diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts index 1e1957f8..8c76f9a4 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.test.ts @@ -20,14 +20,14 @@ describe('NetworkListProcessConfigStrategy (v6)', () => { version: 6, networkList: [ { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'] }, - { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'], active: false }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'] }, { name: 'blocked-asns', type: 'asn', items: ['13335'] }, ], }), ).toEqual([ - { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'], active: true }, - { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'], active: false }, - { name: 'blocked-asns', type: 'asn', items: ['13335'], active: true }, + { name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8', '2001:db8::/32'] }, + { name: 'blocked-countries', type: 'countries', items: ['BR', 'US'] }, + { name: 'blocked-asns', type: 'asn', items: ['13335'] }, ]); }); }); @@ -44,7 +44,7 @@ describe('NetworkListProcessConfigStrategy (v6)', () => { it('should read the network_list key of the manifest back into the config (v4 read the wrong key)', () => { const config: AzionConfigV6 = { version: 6, - networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'], active: true }], + networkList: [{ name: 'blocked-ips', type: 'ip_cidr', items: ['10.0.0.0/8'] }], }; const transformedPayload: AzionConfigV6 = { version: 6 }; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts index d0116d41..400cb6cd 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/networkListProcessConfigStrategy.ts @@ -20,7 +20,6 @@ class NetworkListProcessConfigStrategy extends ProcessConfigStrategy { waf: [ { name: 'my-waf', - active: false, engineSettings: { engineVersion: '2021-Q3', type: 'score', @@ -49,7 +48,6 @@ describe('WafProcessConfigStrategy (v6)', () => { ).toEqual([ { name: 'my-waf', - active: false, engine_settings: { engine_version: '2021-Q3', type: 'score', @@ -83,7 +81,6 @@ describe('WafProcessConfigStrategy (v6)', () => { waf: [ { name: 'my-waf', - active: true, engineSettings: { engineVersion: '2021-Q3', type: 'score', diff --git a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts index c28eaba8..a16f9927 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/secure/wafProcessConfigStrategy.ts @@ -20,7 +20,6 @@ class WafProcessConfigStrategy extends ProcessConfigStrategy { return waf.map((wafConfig) => ({ name: wafConfig.name, - ...(wafConfig.active !== undefined && { active: wafConfig.active }), engine_settings: { engine_version: wafConfig.engineSettings?.engineVersion ?? '2021-Q3', type: wafConfig.engineSettings?.type ?? 'score', @@ -48,7 +47,6 @@ class WafProcessConfigStrategy extends ProcessConfigStrategy { // eslint-disable-next-line @typescript-eslint/no-explicit-any transformedPayload.waf = waf.map((wafItem: any) => ({ name: wafItem.name, - active: wafItem.active, engineSettings: wafItem.engine_settings && { engineVersion: wafItem.engine_settings.engine_version, type: wafItem.engine_settings.type, diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts deleted file mode 100644 index da6753aa..00000000 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import type { AzionConfigV6, AzionWorkloadDeploymentV6 } from '../../types'; -import WorkloadDeploymentsProcessConfigStrategy from './workloadDeploymentsProcessConfigStrategy'; - -describe('WorkloadDeploymentsProcessConfigStrategy (v6)', () => { - let strategy: WorkloadDeploymentsProcessConfigStrategy; - - const deployment = ( - attributes: AzionWorkloadDeploymentV6['strategy']['attributes'] = { application: 'my-app' }, - extra: Partial = {}, - ): AzionWorkloadDeploymentV6 => ({ - name: 'my-deployment', - strategy: { type: 'default', attributes }, - ...extra, - }); - - const declared: AzionConfigV6 = { - version: 6, - applications: [{ name: 'my-app' }], - firewall: [{ name: 'my-firewall' }], - customPages: [{ name: 'my-page', pages: [] }], - }; - - beforeEach(() => { - strategy = new WorkloadDeploymentsProcessConfigStrategy(); - }); - - describe('transformToManifest', () => { - it('should return an empty array when there are no workloads or deployments', () => { - expect(strategy.transformToManifest({ version: 6 })).toEqual([]); - expect(strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] })).toEqual([]); - }); - - it('should apply the defaults and name the workload each deployment belongs to', () => { - const result = strategy.transformToManifest({ - ...declared, - workloads: [{ name: 'my-workload', deployments: [deployment()] }], - }); - - expect(result).toEqual([ - { - workload_name: 'my-workload', - name: 'my-deployment', - current: true, - active: true, - strategy: { type: 'default', attributes: { application: 'my-app', firewall: null, custom_page: null } }, - }, - ]); - }); - - it('should list the deployments of every workload', () => { - const result = strategy.transformToManifest({ - ...declared, - workloads: [ - { name: 'a', deployments: [deployment(), deployment({ application: 'my-app' }, { name: 'second' })] }, - { name: 'b', deployments: [deployment({ application: 'my-app' }, { name: 'third' })] }, - ], - }); - - expect(result.map((item) => [item.workload_name, item.name])).toEqual([ - ['a', 'my-deployment'], - ['a', 'second'], - ['b', 'third'], - ]); - }); - - it('should keep names as names and IDs as numbers (the CLI resolves the names)', () => { - const [named] = strategy.transformToManifest({ - ...declared, - workloads: [ - { - name: 'w', - deployments: [ - deployment( - { application: 'my-app', firewall: 'my-firewall', customPage: 'my-page' }, - { current: false, active: false }, - ), - ], - }, - ], - }); - const [withIds] = strategy.transformToManifest({ - version: 6, - workloads: [{ name: 'w', deployments: [deployment({ application: 10, firewall: 20, customPage: 30 })] }], - }); - - expect(named).toEqual(expect.objectContaining({ current: false, active: false })); - expect(named.strategy.attributes).toEqual({ - application: 'my-app', - firewall: 'my-firewall', - custom_page: 'my-page', - }); - expect(withIds.strategy.attributes).toEqual({ application: 10, firewall: 20, custom_page: 30 }); - }); - - it('should throw when the application, firewall or custom page is not declared', () => { - const run = (attributes: AzionWorkloadDeploymentV6['strategy']['attributes'], config = declared) => - strategy.transformToManifest({ ...config, workloads: [{ name: 'w', deployments: [deployment(attributes)] }] }); - - expect(() => run({ application: 'other' })).toThrow( - 'Workload deployment "my-deployment" references non-existent Application "other".', - ); - expect(() => run({ application: 'my-app', firewall: 'other' })).toThrow( - 'Workload deployment "my-deployment" references non-existent Firewall "other".', - ); - expect(() => run({ application: 'my-app', customPage: 'other' })).toThrow( - 'Workload deployment "my-deployment" references non-existent Custom Page "other".', - ); - expect(() => run({ application: 'my-app' }, { version: 6 })).toThrow('non-existent Application "my-app"'); - }); - }); - - describe('transformToConfig', () => { - it('should not change the workloads when the manifest has no deployments', () => { - const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'w' }] }; - - expect(strategy.transformToConfig({}, transformedPayload)).toBeUndefined(); - expect(strategy.transformToConfig({ workload_deployments: [] }, transformedPayload)).toBeUndefined(); - expect(transformedPayload.workloads).toEqual([{ name: 'w' }]); - }); - - it('should give each workload the deployments that name it', () => { - const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'a' }, { name: 'b' }] }; - - strategy.transformToConfig( - { - workload_deployments: [ - { - workload_name: 'b', - name: 'second', - current: true, - active: false, - strategy: { type: 'default', attributes: { application: 'my-app', firewall: 'f', custom_page: null } }, - }, - { - workload_name: 'a', - name: 'first', - current: true, - active: true, - strategy: { type: 'default', attributes: { application: 10 } }, - }, - ], - }, - transformedPayload, - ); - - expect(transformedPayload.workloads).toEqual([ - { - name: 'a', - deployments: [ - { - name: 'first', - current: true, - active: true, - strategy: { type: 'default', attributes: { application: 10, firewall: null, customPage: null } }, - }, - ], - }, - { - name: 'b', - deployments: [ - { - name: 'second', - current: true, - active: false, - strategy: { type: 'default', attributes: { application: 'my-app', firewall: 'f', customPage: null } }, - }, - ], - }, - ]); - }); - - it('should round trip through the manifest', () => { - const config: AzionConfigV6 = { - ...declared, - workloads: [ - { - name: 'w', - deployments: [ - deployment( - { application: 'my-app', firewall: 'my-firewall', customPage: null }, - { current: true, active: true }, - ), - ], - }, - ], - }; - const manifest = { workload_deployments: strategy.transformToManifest(config) }; - const transformedPayload: AzionConfigV6 = { version: 6, workloads: [{ name: 'w' }] }; - - strategy.transformToConfig(manifest, transformedPayload); - - expect(transformedPayload.workloads?.[0].deployments).toEqual(config.workloads?.[0].deployments); - }); - }); -}); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts deleted file mode 100644 index 1bdc961d..00000000 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadDeploymentsProcessConfigStrategy.ts +++ /dev/null @@ -1,90 +0,0 @@ -import ProcessConfigStrategy from '../../../shared/processStrategy/processConfigStrategy'; -import type { AzionConfigV6, AzionWorkloadDeploymentV6 } from '../../types'; - -/** - * WorkloadDeploymentsProcessConfigStrategy V6 - * @class WorkloadDeploymentsProcessConfigStrategy - * @description Converts the deployments of the v6 workloads between the config and the manifest. - * The manifest lists the deployments of every workload under `workload_deployments`, as v4 does, and each one carries the - * `workload_name` it belongs to, because the API creates a deployment under a workload - * (`/workspace/workloads/{workload_id}/deployments`) and the Azion CLI is the one that knows the workload ID. - * The application, firewall and custom page of the strategy are IDs in the API: a name is validated against the config - * and kept in the manifest for the CLI to resolve, and an ID goes through as the number it is. - */ -class WorkloadDeploymentsProcessConfigStrategy extends ProcessConfigStrategy { - /** - * Validate that a referenced resource is declared. A number is an ID, which is not validated. - */ - private validateReference( - resources: { name: string }[] | undefined, - nameOrId: string | number, - label: string, - deploymentName: string, - ) { - if (typeof nameOrId === 'string' && !resources?.some((resource) => resource.name === nameOrId)) { - throw new Error(`Workload deployment "${deploymentName}" references non-existent ${label} "${nameOrId}".`); - } - } - - transformToManifest(config: AzionConfigV6) { - const workloads = config?.workloads; - if (!workloads || workloads.length === 0) { - return []; - } - - return workloads.flatMap((workload) => - (workload.deployments ?? []).map((deployment: AzionWorkloadDeploymentV6) => { - const { application, firewall, customPage } = deployment.strategy.attributes; - - this.validateReference(config.applications, application, 'Application', deployment.name); - if (firewall) this.validateReference(config.firewall, firewall, 'Firewall', deployment.name); - if (customPage) this.validateReference(config.customPages, customPage, 'Custom Page', deployment.name); - - return { - workload_name: workload.name, - name: deployment.name, - current: deployment.current ?? true, - active: deployment.active ?? true, - strategy: { - type: deployment.strategy.type, - attributes: { - application, - firewall: firewall ?? null, - custom_page: customPage ?? null, - }, - }, - }; - }), - ); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transformToConfig(payload: { workload_deployments?: any[] }, transformedPayload: AzionConfigV6) { - if (!Array.isArray(payload?.workload_deployments) || payload.workload_deployments.length === 0) { - return; - } - - transformedPayload.workloads = (transformedPayload.workloads ?? []).map((workload) => ({ - ...workload, - deployments: payload - .workload_deployments!.filter((deployment) => deployment.workload_name === workload.name) - .map((deployment) => ({ - name: deployment.name, - current: deployment.current, - active: deployment.active, - strategy: { - type: deployment.strategy.type, - attributes: { - application: deployment.strategy.attributes.application, - firewall: deployment.strategy.attributes.firewall ?? null, - customPage: deployment.strategy.attributes.custom_page ?? null, - }, - }, - })), - })); - - return transformedPayload.workloads; - } -} - -export default WorkloadDeploymentsProcessConfigStrategy; diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts index 15d99aaa..4a164655 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.test.ts @@ -7,10 +7,8 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { const declared: AzionConfigV6 = { version: 6, environments: [{ name: 'production', deploymentPolicy: 'single_version' }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], }; - const deployments: AzionWorkloadV6['deployments'] = [ - { name: 'default-deployment', strategy: { type: 'default', attributes: { application: 'my-app' } } }, - ]; beforeEach(() => { strategy = new WorkloadProcessConfigStrategy(); @@ -28,7 +26,6 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { expect(result).toEqual([ { name: 'my-workload', - active: true, infrastructure: 1, workload_domain_allow_access: true, tls: { minimum_version: 'tls_1_3' }, @@ -63,8 +60,6 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { workloads: [ { name: 'my-workload', - deployments, - active: false, infrastructure: 2, workloadDomainAllowAccess: false, protocols: { http: { versions: ['http2'], httpPorts: [8080], httpsPorts: [8443], quicPorts: [8443] } }, @@ -82,7 +77,6 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { expect(workload).toEqual( expect.objectContaining({ - active: false, infrastructure: 2, workload_domain_allow_access: false, protocols: { http: { versions: ['http2'], http_ports: [8080], https_ports: [8443], quic_ports: [8443] } }, @@ -104,9 +98,7 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { it('should name the environment and the deployment of a binding as names, not as ids (the CLI resolves the ids)', () => { const [workload] = strategy.transformToManifest({ ...declared, - workloads: [ - { name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'default-deployment' }] }, - ], + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], }); expect(Object.keys(workload.bindings[0])).toEqual(['environment_name', 'deployment_name', 'domains']); @@ -116,45 +108,25 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { expect(() => strategy.transformToManifest({ ...declared, - workloads: [ - { name: 'w', deployments, bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }, - ], + workloads: [{ name: 'w', bindings: [{ environment: 'staging', deployment: 'default-deployment' }] }], }), ).toThrow('Workload "w" binding references non-existent Environment "staging".'); }); - it('should throw when a binding references a deployment that the workload does not declare', () => { + it('should throw when a binding references a deployment that is not declared', () => { expect(() => strategy.transformToManifest({ ...declared, - workloads: [{ name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'other' }] }], + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'other' }] }], }), ).toThrow('Workload "w" binding references non-existent Deployment "other".'); - expect(() => - strategy.transformToManifest({ - ...declared, - workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }], - }), - ).toThrow('Workload "w" binding references non-existent Deployment "default-deployment".'); expect(() => strategy.transformToManifest({ version: 6, - workloads: [{ name: 'w', deployments, bindings: [{ environment: 'production', deployment: 'd' }] }], + workloads: [{ name: 'w', bindings: [{ environment: 'production', deployment: 'd' }] }], }), ).toThrow('non-existent Environment "production"'); }); - - it('should not accept a deployment of another workload in a binding', () => { - expect(() => - strategy.transformToManifest({ - ...declared, - workloads: [ - { name: 'a', deployments }, - { name: 'b', bindings: [{ environment: 'production', deployment: 'default-deployment' }] }, - ], - }), - ).toThrow('Workload "b" binding references non-existent Deployment "default-deployment".'); - }); }); describe('transformToConfig', () => { @@ -173,7 +145,6 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { workloads: [ { name: 'my-workload', - active: true, infrastructure: 1, workload_domain_allow_access: true, tls: { ciphers: 3, minimum_version: 'tls_1_2' }, @@ -194,7 +165,6 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { expect(transformedPayload.workloads).toEqual([ { name: 'my-workload', - active: true, infrastructure: 1, workloadDomainAllowAccess: true, tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, @@ -211,4 +181,43 @@ describe('WorkloadProcessConfigStrategy (v6)', () => { ]); }); }); + + describe('workload_domain_allow_access', () => { + const config = ( + policy: 'single_version' | 'versioned_urls', + workload: Partial = {}, + ): AzionConfigV6 => ({ + version: 6, + environments: [{ name: 'production', deploymentPolicy: policy }], + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE' }], + workloads: [ + { name: 'w', bindings: [{ environment: 'production', deployment: 'default-deployment' }], ...workload }, + ], + }); + + it('should be true by default, and false by default when the workload is bound to a versioned_urls environment', () => { + expect(strategy.transformToManifest(config('single_version'))[0].workload_domain_allow_access).toBe(true); + expect(strategy.transformToManifest(config('versioned_urls'))[0].workload_domain_allow_access).toBe(false); + expect( + strategy.transformToManifest({ version: 6, workloads: [{ name: 'w' }] })[0].workload_domain_allow_access, + ).toBe(true); + }); + + it('should accept an explicit value for a single_version environment, and false for a versioned_urls one', () => { + expect( + strategy.transformToManifest(config('single_version', { workloadDomainAllowAccess: false }))[0] + .workload_domain_allow_access, + ).toBe(false); + expect( + strategy.transformToManifest(config('versioned_urls', { workloadDomainAllowAccess: false }))[0] + .workload_domain_allow_access, + ).toBe(false); + }); + + it('should throw when true is set for a workload bound to a versioned_urls environment', () => { + expect(() => strategy.transformToManifest(config('versioned_urls', { workloadDomainAllowAccess: true }))).toThrow( + 'Workload "w" cannot set workloadDomainAllowAccess to true: it is bound to an environment whose deploymentPolicy is versioned_urls.', + ); + }); + }); }); diff --git a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts index 4fe30ceb..5c0f092a 100644 --- a/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts +++ b/packages/config/src/versions/v6/processStrategy/implementations/workloadProcessConfigStrategy.ts @@ -5,13 +5,13 @@ import type { AzionConfigV6, AzionWorkloadV6 } from '../../types'; * WorkloadProcessConfigStrategy V6 * @class WorkloadProcessConfigStrategy * @description Converts the v6 workloads between the config and the manifest. - * A binding references an environment and a deployment of the workload by the name it has in the config. The manifest - * keeps that name in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, - * so it is the one that knows their ids and sends them to the API. + * A binding references an environment and a deployment by the name it has in the config. The manifest keeps that name + * in `environment_name` and `deployment_name`: the Azion CLI creates the environment and the deployment, so it is the + * one that knows their ids and sends them to the API. */ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy { /** - * Validate that the environment of the bindings is declared and that the deployment is one of the workload + * Validate that the environment and the deployment of the bindings are declared */ private validateBindingReferences(config: AzionConfigV6, workload: AzionWorkloadV6) { workload.bindings?.forEach((binding) => { @@ -20,7 +20,7 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy `Workload "${workload.name}" binding references non-existent Environment "${binding.environment}".`, ); } - if (!workload.deployments?.some((deployment) => deployment.name === binding.deployment)) { + if (!config.deployments?.some((deployment) => deployment.name === binding.deployment)) { throw new Error( `Workload "${workload.name}" binding references non-existent Deployment "${binding.deployment}".`, ); @@ -28,6 +28,26 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy }); } + /** + * `workload_domain_allow_access` needs the workload bound to single-version environments only: it is true by default, + * and it is false by default when a binding uses a `versioned_urls` environment. + */ + private resolveWorkloadDomainAllowAccess(config: AzionConfigV6, workload: AzionWorkloadV6) { + const versionedUrls = workload.bindings?.some( + (binding) => + config.environments?.find((environment) => environment.name === binding.environment)?.deploymentPolicy === + 'versioned_urls', + ); + + if (workload.workloadDomainAllowAccess && versionedUrls) { + throw new Error( + `Workload "${workload.name}" cannot set workloadDomainAllowAccess to true: it is bound to an environment whose deploymentPolicy is versioned_urls.`, + ); + } + + return workload.workloadDomainAllowAccess ?? !versionedUrls; + } + transformToManifest(config: AzionConfigV6) { const workloads = config?.workloads; if (!workloads || workloads.length === 0) return []; @@ -37,9 +57,8 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy return { name: workload.name, - active: workload.active ?? true, infrastructure: workload.infrastructure || 1, - workload_domain_allow_access: workload.workloadDomainAllowAccess ?? true, + workload_domain_allow_access: this.resolveWorkloadDomainAllowAccess(config, workload), tls: { ...(workload.tls?.ciphers && { ciphers: workload.tls.ciphers }), minimum_version: workload.tls?.minimumVersion || 'tls_1_3', @@ -82,7 +101,6 @@ class WorkloadProcessConfigStrategy extends ProcessConfigStrategy transformedPayload.workloads = payload.workloads.map((workload) => ({ name: workload.name, - active: workload.active, infrastructure: workload.infrastructure, workloadDomainAllowAccess: workload.workload_domain_allow_access, tls: { diff --git a/packages/config/src/versions/v6/processStrategy/index.ts b/packages/config/src/versions/v6/processStrategy/index.ts index 7e1a616c..895580dc 100644 --- a/packages/config/src/versions/v6/processStrategy/index.ts +++ b/packages/config/src/versions/v6/processStrategy/index.ts @@ -4,6 +4,7 @@ import ApplicationProcessConfigStrategy from './implementations/application/appl import BuildProcessConfigStrategy from './implementations/buildProcessConfigStrategy'; import ConnectorProcessConfigStrategy from './implementations/connectorProcessConfigStrategy'; import CustomPagesProcessConfigStrategy from './implementations/customPagesProcessConfigStrategy'; +import DeploymentProcessConfigStrategy from './implementations/deploymentProcessConfigStrategy'; import EnvironmentProcessConfigStrategy from './implementations/environmentProcessConfigStrategy'; import FunctionsProcessConfigStrategy from './implementations/functionsProcessConfigStrategy'; import PurgeProcessConfigStrategy from './implementations/purgeProcessConfigStrategy'; @@ -11,7 +12,6 @@ import FirewallProcessConfigStrategy from './implementations/secure/firewallProc import NetworkListProcessConfigStrategy from './implementations/secure/networkListProcessConfigStrategy'; import WafProcessConfigStrategy from './implementations/secure/wafProcessConfigStrategy'; import StorageProcessConfigStrategy from './implementations/storageProcessConfigStrategy'; -import WorkloadDeploymentsProcessConfigStrategy from './implementations/workloadDeploymentsProcessConfigStrategy'; import WorkloadProcessConfigStrategy from './implementations/workloadProcessConfigStrategy'; import VersionProcessConfigStrategy from './implementations/versionProcessConfigStrategy'; @@ -28,8 +28,8 @@ function factoryProcessContext() { processConfigContext.setStrategy('custom_pages', new CustomPagesProcessConfigStrategy()); processConfigContext.setStrategy('applications', new ApplicationProcessConfigStrategy()); processConfigContext.setStrategy('environments', new EnvironmentProcessConfigStrategy()); + processConfigContext.setStrategy('deployments', new DeploymentProcessConfigStrategy()); processConfigContext.setStrategy('workloads', new WorkloadProcessConfigStrategy()); - processConfigContext.setStrategy('workload_deployments', new WorkloadDeploymentsProcessConfigStrategy()); processConfigContext.setStrategy('purge', new PurgeProcessConfigStrategy()); return processConfigContext; } diff --git a/packages/config/src/versions/v6/schemas/applications/index.ts b/packages/config/src/versions/v6/schemas/applications/index.ts index 0517585b..a9e72790 100644 --- a/packages/config/src/versions/v6/schemas/applications/index.ts +++ b/packages/config/src/versions/v6/schemas/applications/index.ts @@ -102,11 +102,6 @@ const createRuleSchema = (isRequestPhase = false) => ({ maxLength: 1000, errorMessage: "The 'description' field must be a string with maximum 1000 characters.", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean.", - }, criteria: { type: 'array', items: { @@ -150,11 +145,6 @@ const applicationsSchema = { maxLength: 100, errorMessage: "The 'name' field must be a string with 1 to 100 characters", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, debug: { type: 'boolean', default: false, @@ -162,8 +152,9 @@ const applicationsSchema = { }, edgeCacheEnabled: { type: 'boolean', + enum: [true], default: true, - errorMessage: "The 'edgeCacheEnabled' field must be a boolean", + errorMessage: "The 'edgeCacheEnabled' field can only be true: the cache module cannot be disabled", }, functionsEnabled: { type: 'boolean', @@ -407,8 +398,8 @@ const applicationsSchema = { type: 'string', minLength: 1, maxLength: 250, - pattern: '.*', - errorMessage: "The 'name' field must be a string between 1 and 250 characters", + pattern: '^[a-zA-Z0-9]+$', + errorMessage: "The 'name' field must be a string of 1 to 250 letters and numbers", }, userAgent: { type: 'string', @@ -448,11 +439,6 @@ const applicationsSchema = { default: {}, errorMessage: "The 'args' field must be an object", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, }, required: ['name', 'ref'], additionalProperties: false, diff --git a/packages/config/src/versions/v6/schemas/connectors/index.ts b/packages/config/src/versions/v6/schemas/connectors/index.ts index 9895d72e..8bda230e 100644 --- a/packages/config/src/versions/v6/schemas/connectors/index.ts +++ b/packages/config/src/versions/v6/schemas/connectors/index.ts @@ -61,11 +61,6 @@ const httpAttributesSchema = { items: { type: 'object', properties: { - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, address: { type: 'string', minLength: 1, @@ -348,11 +343,6 @@ const connectorsSchema = { pattern: '.*', errorMessage: "The 'name' field must be a string between 1 and 255 characters", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, type: { type: 'string', enum: CONNECTOR_TYPES, diff --git a/packages/config/src/versions/v6/schemas/customPages/index.ts b/packages/config/src/versions/v6/schemas/customPages/index.ts index 5fdee758..a445cee9 100644 --- a/packages/config/src/versions/v6/schemas/customPages/index.ts +++ b/packages/config/src/versions/v6/schemas/customPages/index.ts @@ -16,11 +16,6 @@ const customPagesSchema = { pattern: '.*', errorMessage: "The 'name' field must be a string between 1 and 255 characters", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, pages: { type: 'array', minItems: 1, diff --git a/packages/config/src/versions/v6/schemas/deployments/index.ts b/packages/config/src/versions/v6/schemas/deployments/index.ts new file mode 100644 index 00000000..555530f0 --- /dev/null +++ b/packages/config/src/versions/v6/schemas/deployments/index.ts @@ -0,0 +1,68 @@ +import { DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES } from '../../constants'; + +/** + * Schema of the v6 deployments, from `DeploymentCreateRequest` and `DeploymentRequest` of the v6 API. + * `bindingPolicy` is required, as in the creation of a deployment. + */ +const deploymentsSchema = { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string', + minLength: 3, + maxLength: 255, + errorMessage: "The 'name' field must be a string between 3 and 255 characters", + }, + description: { + type: ['string', 'null'], + errorMessage: "The 'description' field must be a string or null", + }, + bindingPolicy: { + type: 'string', + enum: DEPLOYMENT_BINDING_POLICIES, + errorMessage: `The 'bindingPolicy' field must be one of: ${DEPLOYMENT_BINDING_POLICIES.join(', ')}`, + }, + deploymentPolicy: { + type: 'string', + enum: DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, + }, + strategyDefaults: { + type: 'object', + properties: { + skewProtection: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + defaultTtlSeconds: { type: 'integer', minimum: 1, maximum: 2147483647 }, + }, + required: ['enabled', 'defaultTtlSeconds'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in skewProtection', + required: "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", + }, + }, + }, + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in strategyDefaults', + }, + }, + }, + required: ['name', 'bindingPolicy'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in deployment objects', + required: { + name: "The 'name' field is required in each deployment", + bindingPolicy: "The 'bindingPolicy' field is required in each deployment", + }, + }, + }, + errorMessage: "The 'deployments' field must be an array of deployment objects", +}; + +export default deploymentsSchema; diff --git a/packages/config/src/versions/v6/schemas/environments/index.ts b/packages/config/src/versions/v6/schemas/environments/index.ts index 15fe9b3f..68225144 100644 --- a/packages/config/src/versions/v6/schemas/environments/index.ts +++ b/packages/config/src/versions/v6/schemas/environments/index.ts @@ -1,5 +1,5 @@ import { - DEPLOYMENT_POLICIES, + ENVIRONMENT_DEPLOYMENT_POLICIES, ENVIRONMENT_BRANCH_TRACKING_MODES, ENVIRONMENT_LOG_VERBOSITY, ENVIRONMENT_ROBOTS_POLICIES, @@ -97,8 +97,8 @@ const environmentsSchema = { }, deploymentPolicy: { type: 'string', - enum: DEPLOYMENT_POLICIES, - errorMessage: `The 'deploymentPolicy' field must be one of: ${DEPLOYMENT_POLICIES.join(', ')}`, + enum: ENVIRONMENT_DEPLOYMENT_POLICIES, + errorMessage: `The 'deploymentPolicy' field must be one of: ${ENVIRONMENT_DEPLOYMENT_POLICIES.join(', ')}`, }, }, required: ['name', 'deploymentPolicy'], diff --git a/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts index 9e7fb74c..ba817d4e 100644 --- a/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts +++ b/packages/config/src/versions/v6/schemas/firewall/functionsInstances/index.ts @@ -1,6 +1,5 @@ /** - * Schema of the function instances of a v6 firewall, from `FirewallFunctionInstanceRequest` of the v6 API: - * the request also has `active`. + * Schema of the function instances of a v6 firewall, from `FirewallFunctionInstanceRequest` of the v6 API. */ const firewallFunctionsInstances = { type: 'object', @@ -20,11 +19,6 @@ const firewallFunctionsInstances = { type: ['string', 'number'], errorMessage: "The 'ref' field must be a string or number referencing an existing Function name or ID", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, }, required: ['name', 'ref'], additionalProperties: false, diff --git a/packages/config/src/versions/v6/schemas/firewall/index.ts b/packages/config/src/versions/v6/schemas/firewall/index.ts index fdca4911..2ae95f90 100644 --- a/packages/config/src/versions/v6/schemas/firewall/index.ts +++ b/packages/config/src/versions/v6/schemas/firewall/index.ts @@ -16,10 +16,6 @@ const firewall = { maxLength: 250, errorMessage: "The firewall configuration must have a 'name' field of type string (1-250 characters)", }, - active: { - type: 'boolean', - errorMessage: "The firewall's 'active' field must be a boolean", - }, debugRules: { type: 'boolean', errorMessage: "The firewall's 'debugRules' field must be a boolean", @@ -52,10 +48,6 @@ const firewall = { maxLength: 1000, errorMessage: "The rule's 'description' field must be a string of at most 1000 characters", }, - active: { - type: 'boolean', - errorMessage: "The rule's 'active' field must be a boolean", - }, match: { type: 'string', errorMessage: "The rule's 'match' field must be a string containing a valid regex pattern", diff --git a/packages/config/src/versions/v6/schemas/functions/index.ts b/packages/config/src/versions/v6/schemas/functions/index.ts index 4146bec2..61b0fe28 100644 --- a/packages/config/src/versions/v6/schemas/functions/index.ts +++ b/packages/config/src/versions/v6/schemas/functions/index.ts @@ -1,3 +1,5 @@ +import { FUNCTION_DEPENDENCY_TYPES } from '../../constants'; + const functionsSchema = { type: 'array', items: { @@ -31,10 +33,36 @@ const functionsSchema = { default: 'application', errorMessage: "The 'executionEnvironment' field must be 'application' or 'firewall'", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", + dependencies: { + type: 'array', + maxItems: 20, + items: { + type: 'object', + properties: { + type: { + type: 'string', + enum: FUNCTION_DEPENDENCY_TYPES, + errorMessage: `The 'type' field must be one of: ${FUNCTION_DEPENDENCY_TYPES.join(', ')}`, + }, + ref: { + type: ['string', 'integer'], + minimum: 1, + minLength: 1, + errorMessage: + "The 'ref' field must be the name of a connector or network list declared in the config, or its ID", + }, + }, + required: ['type', 'ref'], + additionalProperties: false, + errorMessage: { + additionalProperties: 'No additional properties are allowed in function dependencies', + required: "The 'type' and 'ref' fields are required in each function dependency", + }, + }, + errorMessage: { + maxItems: "The 'dependencies' field can have at most 20 items", + type: "The 'dependencies' field must be an array of dependency objects", + }, }, bindings: { type: 'object', diff --git a/packages/config/src/versions/v6/schemas/networkList/index.ts b/packages/config/src/versions/v6/schemas/networkList/index.ts index b838b774..ea75088c 100644 --- a/packages/config/src/versions/v6/schemas/networkList/index.ts +++ b/packages/config/src/versions/v6/schemas/networkList/index.ts @@ -36,11 +36,6 @@ const networkListSchema = { }, errorMessage: "The 'items' field must be an array of strings with 1-20000 items.", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean.", - }, }, required: ['name', 'type', 'items'], additionalProperties: false, diff --git a/packages/config/src/versions/v6/schemas/purge/index.ts b/packages/config/src/versions/v6/schemas/purge/index.ts index ded034dd..889777ee 100644 --- a/packages/config/src/versions/v6/schemas/purge/index.ts +++ b/packages/config/src/versions/v6/schemas/purge/index.ts @@ -1,7 +1,7 @@ /** * Schema of the v6 purge. * Based on v4, checked against `PurgeRequest` (`POST /workspace/purge/{purge_type}`): each item has at least 1 character - * and `layer` is `cache` or `tiered_cache`. The `uri` format of the items is not enforced here: a `cachekey` item is not a URI, + * and `layer` is `cache`. The `uri` format of the items is not enforced here: a `cachekey` item is not a URI, * and the strategy already checks the protocol of a `url` and the asterisk of a `wildcard`. */ const purgeSchema = { @@ -32,8 +32,8 @@ const purgeSchema = { }, layer: { type: 'string', - enum: ['cache', 'tiered_cache'], - errorMessage: "The 'layer' field must be either 'cache' or 'tiered_cache'.", + enum: ['cache'], + errorMessage: "The 'layer' field must be 'cache'.", }, }, required: ['type', 'items'], diff --git a/packages/config/src/versions/v6/schemas/schema.ts b/packages/config/src/versions/v6/schemas/schema.ts index e4351504..3138a26f 100644 --- a/packages/config/src/versions/v6/schemas/schema.ts +++ b/packages/config/src/versions/v6/schemas/schema.ts @@ -2,6 +2,7 @@ import applicationsSchema from './applications'; import buildSchema from './build'; import connectorsSchema from './connectors'; import customPagesSchema from './customPages'; +import deploymentsSchema from './deployments'; import environmentsSchema from './environments'; import firewallSchema from './firewall'; import functionsSchema from './functions'; @@ -32,12 +33,13 @@ const azionConfigSchema = { applications: applicationsSchema, workloads: workloadsSchema, environments: environmentsSchema, + deployments: deploymentsSchema, purge: purgeSchema, }, additionalProperties: false, errorMessage: { additionalProperties: - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, purge', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', type: 'Configuration must be an object', }, }, diff --git a/packages/config/src/versions/v6/schemas/waf/index.ts b/packages/config/src/versions/v6/schemas/waf/index.ts index f23dcce9..4d91da9e 100644 --- a/packages/config/src/versions/v6/schemas/waf/index.ts +++ b/packages/config/src/versions/v6/schemas/waf/index.ts @@ -22,11 +22,6 @@ const wafSchema = { pattern: '.*', errorMessage: "The WAF configuration must have a 'name' field of type string (1-250 characters)", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, engineSettings: { type: 'object', properties: { diff --git a/packages/config/src/versions/v6/schemas/workloads/index.ts b/packages/config/src/versions/v6/schemas/workloads/index.ts index 9b9fe9db..39d3ca4d 100644 --- a/packages/config/src/versions/v6/schemas/workloads/index.ts +++ b/packages/config/src/versions/v6/schemas/workloads/index.ts @@ -1,5 +1,4 @@ import { - WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, WORKLOAD_HTTP_VERSIONS, WORKLOAD_INFRASTRUCTURE, WORKLOAD_MTLS_VERIFICATION, @@ -11,8 +10,6 @@ import { * Schema of the v6 workloads. * Based on v4, checked against `WorkloadRequest` of the v6 API: the domains and the certificate moved to the * `bindings`, `tls.ciphers` is not nullable and the ports and versions of the http protocol have limits. - * `deployments` are the workload deployments (`WorkloadDeploymentRequest`): the strategy type can only be `default` and - * its application, firewall and custom page are IDs in the API, so the config accepts a name or an ID for each of them. */ const workloadsSchema = { type: 'array', @@ -26,11 +23,6 @@ const workloadsSchema = { pattern: '.*', errorMessage: "The 'name' field must be a string between 1 and 100 characters", }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, infrastructure: { type: 'integer', enum: WORKLOAD_INFRASTRUCTURE, @@ -76,7 +68,12 @@ const workloadsSchema = { enum: WORKLOAD_HTTP_VERSIONS, }, maxItems: 3, + // the API requires http1 and http2 + allOf: [{ contains: { const: 'http1' } }, { contains: { const: 'http2' } }], default: ['http1', 'http2', 'http3'], + errorMessage: { + allOf: "The 'versions' field must include http1 and http2", + }, }, httpPorts: { type: 'array', @@ -142,86 +139,6 @@ const workloadsSchema = { }, additionalProperties: false, }, - deployments: { - type: 'array', - items: { - type: 'object', - properties: { - name: { - type: 'string', - minLength: 1, - maxLength: 254, - pattern: '.*', - errorMessage: "The 'name' field must be a string between 1 and 254 characters", - }, - current: { - type: 'boolean', - default: true, - errorMessage: "The 'current' field must be a boolean", - }, - active: { - type: 'boolean', - default: true, - errorMessage: "The 'active' field must be a boolean", - }, - strategy: { - type: 'object', - properties: { - type: { - type: 'string', - enum: WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, - errorMessage: `The 'type' field must be one of: ${WORKLOAD_DEPLOYMENT_STRATEGY_TYPES.join(', ')}`, - }, - attributes: { - type: 'object', - properties: { - application: { - type: ['string', 'integer'], - minimum: 1, - minLength: 1, - errorMessage: - "The 'application' field must be the name of an application declared in 'applications' or an application ID", - }, - firewall: { - type: ['string', 'integer', 'null'], - minimum: 1, - minLength: 1, - errorMessage: - "The 'firewall' field must be the name of a firewall declared in 'firewall', a firewall ID or null", - }, - customPage: { - type: ['string', 'integer', 'null'], - minimum: 1, - minLength: 1, - errorMessage: - "The 'customPage' field must be the name of a custom page declared in 'customPages', a custom page ID or null", - }, - }, - required: ['application'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in strategy attributes', - required: "The 'application' field is required in strategy attributes", - }, - }, - }, - required: ['type', 'attributes'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in strategy', - required: "The 'type' and 'attributes' fields are required in strategy", - }, - }, - }, - required: ['name', 'strategy'], - additionalProperties: false, - errorMessage: { - additionalProperties: 'No additional properties are allowed in deployment items', - required: "The 'name' and 'strategy' fields are required in each deployment", - }, - }, - errorMessage: "The 'deployments' field must be an array of deployment objects", - }, bindings: { type: 'array', items: { @@ -235,8 +152,7 @@ const workloadsSchema = { deployment: { type: 'string', minLength: 1, - errorMessage: - "The 'deployment' field must be the name of a deployment declared in the 'deployments' of the workload", + errorMessage: "The 'deployment' field must be the name of a deployment declared in 'deployments'", }, domains: { type: 'array', diff --git a/packages/config/src/versions/v6/types.ts b/packages/config/src/versions/v6/types.ts index a8abc7a2..3ed84741 100644 --- a/packages/config/src/versions/v6/types.ts +++ b/packages/config/src/versions/v6/types.ts @@ -3,7 +3,7 @@ import type { AzionCache, AzionFunction, AzionFunctionInstance, - AzionRules, + AzionRule, AzionWorkloadMTLS, AzionWorkloadProtocols, WorkloadInfrastructure, @@ -20,7 +20,9 @@ import type { CONNECTOR_TRANSPORT_POLICY, CUSTOM_PAGE_ERROR_CODES, CUSTOM_PAGE_TYPES, + DEPLOYMENT_BINDING_POLICIES, DEPLOYMENT_POLICIES, + ENVIRONMENT_DEPLOYMENT_POLICIES, ENVIRONMENT_BRANCH_TRACKING_MODES, ENVIRONMENT_LOG_VERBOSITY, ENVIRONMENT_ROBOTS_POLICIES, @@ -30,20 +32,52 @@ import type { FIREWALL_RULE_CONDITIONAL, FIREWALL_RULE_OPERATORS, FIREWALL_WAF_MODES, + FUNCTION_DEPENDENCY_TYPES, NETWORK_LIST_TYPES, WAF_ENGINE_TYPES, WAF_ENGINE_VERSIONS, WAF_RULESETS, WAF_SENSITIVITY, WAF_THREAT_TYPES, - WORKLOAD_DEPLOYMENT_STRATEGY_TYPES, WORKLOADS_ACCESS_TYPES, } from './constants'; /** - * Function of the Azion API v6. + * Resource a function uses at runtime, which a release includes with the function. */ -export type AzionFunctionV6 = AzionFunction; +export type AzionFunctionDependencyV6 = { + type: (typeof FUNCTION_DEPENDENCY_TYPES)[number]; + /** Name of a connector or network list declared in the config, or its ID */ + ref: string | number; +}; + +/** + * Function of the Azion API v6 (it has no `active`). + */ +export type AzionFunctionV6 = Omit & { + /** Connectors and network lists the function uses at runtime (at most 20) */ + dependencies?: AzionFunctionDependencyV6[]; +}; + +/** + * Function instance of the Azion API v6 (it has no `active`). + */ +export type AzionFunctionInstanceV6 = Omit; + +/** + * Rule of the Azion API v6 (it has no `active`). + */ +export type AzionRuleV6 = Omit; + +/** + * Rules of an application of the Azion API v6. + */ +export type AzionRulesV6 = { + /** Request rules */ + request?: AzionRuleV6[]; + /** Response rules */ + response?: AzionRuleV6[]; +}; /** * Device group of an application of the Azion API v6. @@ -62,23 +96,22 @@ export type AzionApplicationV6 = { /** Application name */ name: string; /** Enable edge cache */ - edgeCacheEnabled?: boolean; + /** The cache module cannot be disabled, so it can only be true */ + edgeCacheEnabled?: true; /** Enable functions */ functionsEnabled?: boolean; /** Enable application accelerator */ applicationAcceleratorEnabled?: boolean; /** Enable image processor */ imageProcessorEnabled?: boolean; - /** Indicates if the application is active */ - active?: boolean; /** Enable debug mode */ debug?: boolean; /** Cache settings */ cache?: AzionCache[]; /** Rules configuration */ - rules?: AzionRules; + rules?: AzionRulesV6; /** Function instances */ - functionsInstances?: AzionFunctionInstance[]; + functionsInstances?: AzionFunctionInstanceV6[]; /** Device groups */ deviceGroups?: AzionDeviceGroupV6[]; }; @@ -102,54 +135,27 @@ export type AzionWorkloadBindingDomainV6 = { }; /** - * Binding of a workload to an environment and one of its deployments. + * Binding of a workload to an environment and a deployment. */ export type AzionWorkloadBindingV6 = { /** Name of an environment declared in `environments` */ environment: string; - /** Name of a deployment declared in the `deployments` of the same workload */ + /** Name of a deployment declared in `deployments` */ deployment: string; /** Domains served by the binding */ domains?: AzionWorkloadBindingDomainV6[]; }; -/** - * Deployment of a workload of the Azion API v6. - */ -export type AzionWorkloadDeploymentV6 = { - /** Deployment name */ - name: string; - /** Whether it is the current deployment of the workload */ - current?: boolean; - /** Whether the deployment is active */ - active?: boolean; - /** What the deployment serves */ - strategy: { - type: (typeof WORKLOAD_DEPLOYMENT_STRATEGY_TYPES)[number]; - attributes: { - /** Name or ID of the application */ - application: string | number; - /** Name or ID of the firewall */ - firewall?: string | number | null; - /** Name or ID of the custom page */ - customPage?: string | number | null; - }; - }; -}; - /** * Workload of the Azion API v6. */ export type AzionWorkloadV6 = { name: string; - active?: boolean; infrastructure?: WorkloadInfrastructure; tls?: AzionWorkloadTLSV6; protocols?: AzionWorkloadProtocols; mtls?: AzionWorkloadMTLS; workloadDomainAllowAccess?: boolean; - /** Deployments of the workload: the application, firewall and custom page each one serves */ - deployments?: AzionWorkloadDeploymentV6[]; /** Environments and deployments the workload is bound to, with the domains of each binding */ bindings?: AzionWorkloadBindingV6[]; }; @@ -175,7 +181,22 @@ export type AzionEnvironmentV6 = { branchMatch: string; } | null; /** How the releases of the environment are served. Required by the API, and it cannot be changed afterwards */ - deploymentPolicy: (typeof DEPLOYMENT_POLICIES)[number]; + deploymentPolicy: (typeof ENVIRONMENT_DEPLOYMENT_POLICIES)[number]; +}; + +/** + * Deployment of the Azion API v6. + */ +export type AzionDeploymentV6 = { + /** Deployment name */ + name: string; + description?: string | null; + /** Whether a release can swap the resources of the deployment. Required by the API */ + bindingPolicy: (typeof DEPLOYMENT_BINDING_POLICIES)[number]; + deploymentPolicy?: (typeof DEPLOYMENT_POLICIES)[number]; + strategyDefaults?: { + skewProtection?: { enabled: boolean; defaultTtlSeconds: number }; + }; }; /** @@ -196,7 +217,6 @@ export type AzionStorageV6 = { * Address of an HTTP connector. */ export type AzionConnectorAddressV6 = { - active?: boolean; /** IPv4/IPv6 address or CNAME */ address: string; httpPort?: number; @@ -259,8 +279,6 @@ export type AzionConnectorHttpAttributesV6 = { type AzionConnectorBaseV6 = { /** Connector name */ name: string; - /** Indicates if the connector is active */ - active?: boolean; }; /** @@ -300,8 +318,6 @@ export type AzionCustomPageEntryV6 = { export type AzionCustomPageV6 = { /** Custom page name */ name: string; - /** Active status */ - active?: boolean; /** Pages, one for each error code */ pages: AzionCustomPageEntryV6[]; }; @@ -316,8 +332,6 @@ export type AzionNetworkListV6 = { type: (typeof NETWORK_LIST_TYPES)[number]; /** Items of the list */ items: string[]; - /** Active status */ - active?: boolean; }; /** @@ -358,7 +372,6 @@ export type AzionFirewallBehaviorV6 = export type AzionFirewallRuleV6 = { name: string; description?: string; - active?: boolean; /** Regex the variable must match */ match?: string; variable?: string; @@ -371,7 +384,6 @@ export type AzionFirewallRuleV6 = { */ export type AzionFirewallV6 = { name: string; - active?: boolean; debugRules?: boolean; /** Enable the functions module */ functions?: boolean; @@ -380,7 +392,7 @@ export type AzionFirewallV6 = { /** Enable the waf module */ waf?: boolean; rules?: AzionFirewallRuleV6[]; - functionsInstances?: AzionFunctionInstance[]; + functionsInstances?: AzionFunctionInstanceV6[]; }; /** @@ -388,7 +400,6 @@ export type AzionFirewallV6 = { */ export type AzionWafV6 = { name: string; - active?: boolean; engineSettings?: { engineVersion?: (typeof WAF_ENGINE_VERSIONS)[number]; type?: (typeof WAF_ENGINE_TYPES)[number]; @@ -409,7 +420,7 @@ export type AzionPurgeV6 = { /** Items to be purged */ items: string[]; /** Cache layer to be purged */ - layer?: 'cache' | 'tiered_cache'; + layer?: 'cache'; /** Purge type */ type: 'url' | 'cachekey' | 'wildcard'; }; @@ -442,6 +453,8 @@ export type AzionConfigV6 = { workloads?: AzionWorkloadV6[]; /** Environments */ environments?: AzionEnvironmentV6[]; + /** Deployments */ + deployments?: AzionDeploymentV6[]; /** Purge configurations */ purge?: AzionPurgeV6[]; }; diff --git a/packages/config/src/versions/v6/validateConfig/index.test.ts b/packages/config/src/versions/v6/validateConfig/index.test.ts index 0fcccacc..2ee2831e 100644 --- a/packages/config/src/versions/v6/validateConfig/index.test.ts +++ b/packages/config/src/versions/v6/validateConfig/index.test.ts @@ -56,7 +56,6 @@ describe('validateConfig (v6)', () => { applications: [ { name: 'my-app', - active: true, debug: false, edgeCacheEnabled: true, functionsEnabled: true, @@ -69,7 +68,7 @@ describe('validateConfig (v6)', () => { }); it('requires the name', () => { - expect(() => validateConfig({ version: 6, applications: [{ active: true }] })).toThrow( + expect(() => validateConfig({ version: 6, applications: [{}] })).toThrow( "The 'name' field is required in an application", ); }); @@ -108,7 +107,7 @@ describe('validateConfig (v6)', () => { it('rejects properties the v6 schema does not know yet', () => { expect(() => validateConfig({ version: 6, kv: [] })).toThrow( - 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, purge', + 'Config can only contain the following properties: version, build, functions, storage, connectors, customPages, networkList, waf, firewall, applications, workloads, environments, deployments, purge', ); }); @@ -129,7 +128,6 @@ describe('validateConfig (v6) functions', () => { runtime: 'azion_js', defaultArgs: { key: 'value' }, executionEnvironment: 'firewall', - active: false, }, ], }), @@ -192,7 +190,7 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { describe('functionsInstances', () => { it('accepts an instance and requires name and ref', () => { expect(() => - validateConfig(app({ functionsInstances: [{ name: 'i', ref: 'fn', args: { a: 1 }, active: true }] })), + validateConfig(app({ functionsInstances: [{ name: 'i', ref: 'fn', args: { a: 1 } }] })), ).not.toThrow(); expect(() => validateConfig(app({ functionsInstances: [{ name: 'i', ref: 10 }] }))).not.toThrow(); expect(() => validateConfig(app({ functionsInstances: [{ name: 'i' }] }))).toThrow( @@ -214,7 +212,7 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { validateConfig( app({ rules: { - request: [requestRule({ description: 'd', active: true })], + request: [requestRule({ description: 'd' })], response: [requestRule({ behaviors: [{ type: 'add_response_header', attributes: { value: 'x: y' } }] })], }, }), @@ -309,7 +307,7 @@ describe('validateConfig (v6) application functionsInstances and rules', () => { }); }); -describe('validateConfig (v6) workloads, workload deployments and environments', () => { +describe('validateConfig (v6) workloads, environments and deployments', () => { const workload = (extra: Record = {}) => ({ version: 6, workloads: [{ name: 'my-workload', ...extra }], @@ -318,19 +316,16 @@ describe('validateConfig (v6) workloads, workload deployments and environments', version: 6, environments: [{ name: 'production', deploymentPolicy: 'single_version', ...extra }], }); - const workloadDeployment = (extra: Record = {}) => - workload({ - deployments: [ - { name: 'default-deployment', strategy: { type: 'default', attributes: { application: 'my-app' } }, ...extra }, - ], - }); + const deployment = (extra: Record = {}) => ({ + version: 6, + deployments: [{ name: 'default-deployment', bindingPolicy: 'FLEXIBLE', ...extra }], + }); describe('workloads', () => { it('accepts a complete workload', () => { expect(() => validateConfig( workload({ - active: true, infrastructure: 2, workloadDomainAllowAccess: false, tls: { ciphers: 3, minimumVersion: 'tls_1_2' }, @@ -351,7 +346,7 @@ describe('validateConfig (v6) workloads, workload deployments and environments', }); it('requires only the name', () => { - expect(() => validateConfig({ version: 6, workloads: [{ active: true }] })).toThrow( + expect(() => validateConfig({ version: 6, workloads: [{}] })).toThrow( "The 'name' field is required in workloads", ); expect(() => validateConfig(workload())).not.toThrow(); @@ -382,9 +377,14 @@ describe('validateConfig (v6) workloads, workload deployments and environments', it('applies the limits of the http protocol of the v6 API', () => { const http = (extra: Record) => - workload({ protocols: { http: { versions: ['http1'], httpPorts: [80], httpsPorts: [443], ...extra } } }); + workload({ + protocols: { http: { versions: ['http1', 'http2'], httpPorts: [80], httpsPorts: [443], ...extra } }, + }); expect(() => validateConfig(http({}))).not.toThrow(); + // the API requires http1 and http2 + expect(() => validateConfig(http({ versions: ['http3'] }))).toThrow(); + expect(() => validateConfig(http({ versions: ['http1', 'http3'] }))).toThrow(); expect(() => validateConfig(http({ httpPorts: [] }))).toThrow(); expect(() => validateConfig(http({ httpPorts: [80, 81, 82, 83, 84] }))).toThrow(); expect(() => validateConfig(http({ httpsPorts: Array.from({ length: 13 }, (_, i) => 443 + i) }))).toThrow(); @@ -481,70 +481,49 @@ describe('validateConfig (v6) workloads, workload deployments and environments', }); describe('deployments', () => { - it('accepts a complete deployment, with the references as names or as IDs', () => { - expect(() => - validateConfig( - workloadDeployment({ - current: true, - active: false, - strategy: { - type: 'default', - attributes: { application: 'my-app', firewall: 'my-firewall', customPage: 'my-page' }, - }, - }), - ), - ).not.toThrow(); + it('accepts a complete deployment', () => { expect(() => validateConfig( - workloadDeployment({ - strategy: { type: 'default', attributes: { application: 10, firewall: 20, customPage: null } }, + deployment({ + description: 'Default', + bindingPolicy: 'STRICT', + deploymentPolicy: 'single_version', + strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 3600 } }, }), ), ).not.toThrow(); }); - it('requires name and strategy and limits the name to 254 characters', () => { - expect(() => validateConfig(workload({ deployments: [{ name: 'd' }] }))).toThrow( - "The 'name' and 'strategy' fields are required in each deployment", + it('limits the name to 3-255 characters and requires it', () => { + expect(() => validateConfig({ version: 6, deployments: [{ bindingPolicy: 'STRICT' }] })).toThrow( + "The 'name' field is required in each deployment", ); - expect(() => validateConfig(workloadDeployment({ name: 'd'.repeat(254) }))).not.toThrow(); - expect(() => validateConfig(workloadDeployment({ name: 'd'.repeat(255) }))).toThrow( - "The 'name' field must be a string between 1 and 254 characters", + expect(() => validateConfig({ version: 6, deployments: [{ name: 'ab', bindingPolicy: 'FLEXIBLE' }] })).toThrow( + "The 'name' field must be a string between 3 and 255 characters", ); - expect(() => validateConfig(workloadDeployment({ name: '' }))).toThrow(); }); - it('requires the type and the application of the strategy, and the type can only be default', () => { - expect(() => validateConfig(workloadDeployment({ strategy: { attributes: { application: 'a' } } }))).toThrow( - "The 'type' and 'attributes' fields are required in strategy", - ); - expect(() => validateConfig(workloadDeployment({ strategy: { type: 'default', attributes: {} } }))).toThrow( - "The 'application' field is required in strategy attributes", + it('requires the bindingPolicy (the creation of a deployment requires it)', () => { + expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( + "The 'bindingPolicy' field is required in each deployment", ); - expect(() => - validateConfig(workloadDeployment({ strategy: { type: 'canary', attributes: { application: 'a' } } })), - ).toThrow("The 'type' field must be one of: default"); + expect(() => validateConfig(deployment({ bindingPolicy: 'STRICT' }))).not.toThrow(); + expect(() => validateConfig(deployment({ bindingPolicy: 'FLEXIBLE' }))).not.toThrow(); }); - it('rejects an ID below 1, an empty name and unknown properties', () => { - const attributes = (extra: Record) => - workloadDeployment({ strategy: { type: 'default', attributes: { application: 'a', ...extra } } }); - - expect(() => validateConfig(attributes({ application: 0 }))).toThrow(); - expect(() => validateConfig(attributes({ application: '' }))).toThrow(); - expect(() => validateConfig(attributes({ customPage: 0 }))).toThrow(); - expect(() => validateConfig(attributes({ unknown: 1 }))).toThrow( - 'No additional properties are allowed in strategy attributes', + it('rejects values out of the enums and invalid skew protection', () => { + expect(() => validateConfig(deployment({ bindingPolicy: 'strict' }))).toThrow( + "The 'bindingPolicy' field must be one of: STRICT, FLEXIBLE", ); - expect(() => validateConfig(workloadDeployment({ unknown: 1 }))).toThrow( - 'No additional properties are allowed in deployment items', + expect(() => validateConfig(deployment({ deploymentPolicy: 'rolling' }))).toThrow( + "The 'deploymentPolicy' field must be one of: single_version, versioned_urls", ); - }); - - it('does not accept the top-level deployments of the dev spec (the production API has no Deployments API)', () => { - expect(() => validateConfig({ version: 6, deployments: [{ name: 'default-deployment' }] })).toThrow( - 'Config can only contain the following properties', + expect(() => validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true } } }))).toThrow( + "The 'enabled' and 'defaultTtlSeconds' fields are required in skewProtection", ); + expect(() => + validateConfig(deployment({ strategyDefaults: { skewProtection: { enabled: true, defaultTtlSeconds: 0 } } })), + ).toThrow(); }); }); }); @@ -640,7 +619,6 @@ describe('validateConfig (v6) storage and connectors', () => { http({ addresses: [ { - active: true, address: 'origin.example.com', httpPort: 8080, httpsPort: 8443, @@ -859,7 +837,6 @@ describe('validateConfig (v6) waf and firewall', () => { expect(() => validateConfig( waf({ - active: false, engineSettings: { engineVersion: '2021-Q3', type: 'score', @@ -874,9 +851,7 @@ describe('validateConfig (v6) waf and firewall', () => { }); it('requires the name and limits it to 250 characters', () => { - expect(() => validateConfig({ version: 6, waf: [{ active: true }] })).toThrow( - "The 'name' field is required in the WAF object", - ); + expect(() => validateConfig({ version: 6, waf: [{}] })).toThrow("The 'name' field is required in the WAF object"); expect(() => validateConfig({ version: 6, waf: [{ name: 'a'.repeat(251) }] })).toThrow(); }); @@ -920,7 +895,6 @@ describe('validateConfig (v6) waf and firewall', () => { expect(() => validateConfig( firewall({ - active: true, debugRules: false, functions: true, networkProtection: true, @@ -929,12 +903,11 @@ describe('validateConfig (v6) waf and firewall', () => { { name: 'rule', description: 'Block admin', - active: true, criteria: [{ variable: '${host}', conditional: 'if', operator: 'exists' }], behaviors: [{ type: 'bypass' }], }, ], - functionsInstances: [{ name: 'instance', ref: 'fn', args: {}, active: false }], + functionsInstances: [{ name: 'instance', ref: 'fn', args: {} }], }), ), ).not.toThrow(); @@ -1100,7 +1073,7 @@ describe('validateConfig (v6) waf and firewall', () => { const instance = (value: Record) => firewall({ functionsInstances: [value] }); it('accepts active (the v6 request has it) and limits the name to 100 characters', () => { - expect(() => validateConfig(instance({ name: 'i', ref: 'fn', active: false }))).not.toThrow(); + expect(() => validateConfig(instance({ name: 'i', ref: 'fn' }))).not.toThrow(); expect(() => validateConfig(instance({ name: 'a'.repeat(100), ref: 10 }))).not.toThrow(); expect(() => validateConfig(instance({ name: 'a'.repeat(101), ref: 'fn' }))).toThrow( 'The name must be a string between 1 and 100 characters long', @@ -1125,7 +1098,7 @@ describe('validateConfig (v6) networkList', () => { it('accepts every type of list, with and without active', () => { expect(() => validateConfig(list())).not.toThrow(); - expect(() => validateConfig(list({ type: 'asn', items: ['13335'], active: false }))).not.toThrow(); + expect(() => validateConfig(list({ type: 'asn', items: ['13335'] }))).not.toThrow(); expect(() => validateConfig(list({ type: 'countries', items: ['BR', 'US'] }))).not.toThrow(); }); @@ -1213,7 +1186,7 @@ describe('validateConfig (v6) customPages', () => { entry({ type: 'page_connector' }, { connector: 10, ttl: 300, uri: '/error.html', customStatusCode: 200 }), { code: 'default', page: { attributes: { connector: 'my-connector', uri: null, customStatusCode: null } } }, ], - { active: false }, + {}, ), ), ).not.toThrow(); @@ -1332,7 +1305,7 @@ describe('validateConfig (v6) purge', () => { version: 6, purge: [ { type: 'url', items: ['https://example.com/a'], layer: 'cache' }, - { type: 'cachekey', items: ['example.com/a'], layer: 'tiered_cache' }, + { type: 'cachekey', items: ['example.com/a'], layer: 'cache' }, { type: 'wildcard', items: ['https://example.com/*'] }, ], }), @@ -1353,7 +1326,7 @@ describe('validateConfig (v6) purge', () => { "The 'type' field must be either 'url', 'cachekey' or 'wildcard'.", ); expect(() => validateConfig({ version: 6, purge: [{ type: 'url', items: ['a'], layer: 'edge' }] })).toThrow( - "The 'layer' field must be either 'cache' or 'tiered_cache'.", + "The 'layer' field must be 'cache'.", ); }); @@ -1379,3 +1352,113 @@ describe('validateConfig (v6) purge', () => { }); }); }); + +describe('validateConfig (v6) changes of the current openapi-v6-prod', () => { + describe('active was removed from the requests', () => { + const rejected: Array<[string, Record]> = [ + ['application', { applications: [{ name: 'a', active: true }] }], + [ + 'application rule', + { + applications: [ + { + name: 'a', + rules: { + request: [ + { + name: 'r', + active: true, + criteria: [[{ variable: '${uri}', conditional: 'if', operator: 'matches', argument: '^/' }]], + behaviors: [{ type: 'deliver' }], + }, + ], + }, + }, + ], + }, + ], + [ + 'function instance', + { applications: [{ name: 'a', functionsInstances: [{ name: 'i', ref: 1, active: true }] }] }, + ], + ['function', { functions: [{ name: 'f', path: './f.js', active: true }] }], + [ + 'connector', + { connectors: [{ name: 'c', type: 'live_ingest', active: true, attributes: { region: 'us-east-1' } }] }, + ], + [ + 'connector address', + { connectors: [{ name: 'c', type: 'http', attributes: { addresses: [{ address: 'a.com', active: true }] } }] }, + ], + ['firewall', { firewall: [{ name: 'f', active: true }] }], + [ + 'firewall rule', + { + firewall: [{ name: 'f', rules: [{ name: 'r', active: true, criteria: [], behaviors: [{ type: 'deny' }] }] }], + }, + ], + ['waf', { waf: [{ name: 'w', active: true }] }], + ['network list', { networkList: [{ name: 'n', type: 'countries', items: ['BR'], active: true }] }], + ['custom page', { customPages: [{ name: 'p', active: true, pages: [] }] }], + ['workload', { workloads: [{ name: 'w', active: true }] }], + ]; + + it.each(rejected)('rejects active in a %s', (_name, extra) => { + expect(() => validateConfig({ version: 6, ...extra })).toThrow(); + }); + }); + + it('accepts only true for edgeCacheEnabled (the cache module cannot be disabled)', () => { + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', edgeCacheEnabled: true }] })).not.toThrow(); + expect(() => validateConfig({ version: 6, applications: [{ name: 'a', edgeCacheEnabled: false }] })).toThrow(); + }); + + it('limits the name of a device group to letters and numbers', () => { + const group = (name: string) => ({ + version: 6, + applications: [{ name: 'a', deviceGroups: [{ name, userAgent: 'x' }] }], + }); + + expect(() => validateConfig(group('mobile1'))).not.toThrow(); + expect(() => validateConfig(group('my mobile'))).toThrow(); + expect(() => validateConfig(group('my-mobile'))).toThrow(); + }); + + describe('function dependencies', () => { + const fn = (dependencies: unknown) => ({ version: 6, functions: [{ name: 'f', path: './f.js', dependencies }] }); + + it('accepts connectors and network lists by name or ID', () => { + expect(() => + validateConfig( + fn([ + { type: 'connector', ref: 'my-origin' }, + { type: 'network_list', ref: 5 }, + ]), + ), + ).not.toThrow(); + }); + + it('requires type and ref, and rejects another type, an empty ref and more than 20 items', () => { + expect(() => validateConfig(fn([{ type: 'connector' }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'waf', ref: 'x' }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'connector', ref: 0 }]))).toThrow(); + expect(() => validateConfig(fn([{ type: 'connector', ref: 1, id: 1 }]))).toThrow(); + expect(() => + validateConfig(fn(Array.from({ length: 21 }, (_, i) => ({ type: 'connector', ref: i + 1 })))), + ).toThrow(); + expect(() => + validateConfig(fn(Array.from({ length: 20 }, (_, i) => ({ type: 'connector', ref: i + 1 })))), + ).not.toThrow(); + }); + }); + + it('accepts the latest deployment policy only in a deployment, not in an environment', () => { + expect(() => + validateConfig({ + version: 6, + deployments: [{ name: 'abc', bindingPolicy: 'FLEXIBLE', deploymentPolicy: 'latest' }], + }), + ).not.toThrow(); + expect(() => validateConfig({ version: 6, environments: [{ name: 'abc', deploymentPolicy: 'latest' }] })).toThrow(); + }); +}); diff --git a/packages/presets/src/presets/angular/config.v6.ts b/packages/presets/src/presets/angular/config.v6.ts index 3ea2fcb7..0fb45cbc 100644 --- a/packages/presets/src/presets/angular/config.v6.ts +++ b/packages/presets/src/presets/angular/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/astro/config.v6.ts b/packages/presets/src/presets/astro/config.v6.ts index a8b2b837..6817e2f2 100644 --- a/packages/presets/src/presets/astro/config.v6.ts +++ b/packages/presets/src/presets/astro/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/configs.test.ts b/packages/presets/src/presets/configs.test.ts index 62de10a3..7694514b 100644 --- a/packages/presets/src/presets/configs.test.ts +++ b/packages/presets/src/presets/configs.test.ts @@ -18,6 +18,12 @@ const goldenPresets = readdirSync(goldenDir) .filter((file) => file.endsWith('.input.json')) .map((file) => file.replace('.input.json', '')); +// the v6 API has no `active` in any resource, while the v4 manifest still writes it +const withoutActive = (value: unknown) => + value === undefined + ? undefined + : JSON.parse(JSON.stringify(value, (key, item) => (key === 'active' ? undefined : item))); + const byName = (name: string) => presets.find((preset) => preset.metadata.name === name) as AzionBuildPreset; describe('preset configs by API version', () => { @@ -49,7 +55,7 @@ describe('preset configs by API version', () => { }); it.each(presets.map((preset) => [preset.metadata.name, preset] as const))( - '%s: validates and produces the manifest of the v4 config, with the environment and the binding of the v6', + '%s: validates and produces the manifest of the v4 config, with the environment, the deployment and the binding of the v6', (name) => { const config = resolvePresetConfig(byName(name), 6); expect(config.version).toBe(6); @@ -63,12 +69,11 @@ describe('preset configs by API version', () => { expect(v6.version).toBe(6); expect(plain(v6.build)).toEqual(plain(v4.build)); expect(v6.storage).toEqual(v4.storage); - expect(v6.connectors).toEqual(v4.connectors); - expect(plain(v6.functions)).toEqual(plain(v4.functions)); - expect(v6.applications).toEqual(v4.applications); - expect(v6.workload_deployments).toEqual( - v4.workload_deployments.map((deployment: object) => ({ workload_name: '$WORKLOAD_NAME', ...deployment })), - ); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(plain(v6.functions)).toEqual(withoutActive(plain(v4.functions))); + expect(v6.applications).toEqual(withoutActive(v4.applications)); + expect(v6).not.toHaveProperty('workload_deployments'); + expect(v6.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); expect(v6.environments.map((environment: { name: string }) => environment.name)).toEqual(['$ENVIRONMENT_NAME']); expect(v6.workloads[0].bindings).toEqual([ { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, @@ -90,8 +95,8 @@ describe('preset configs by API version', () => { const v4 = processConfig(resolvePresetConfig(byName('javascript'), 4)); const v6 = processConfig(resolvePresetConfig(byName('javascript'), 6)); - expect(v6.functions).toEqual(v4.functions); - expect(v6.applications).toEqual(v4.applications); + expect(v6.functions).toEqual(withoutActive(v4.functions)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); expect(v6.applications[0].modules.functions.enabled).toBe(true); }); @@ -104,8 +109,8 @@ describe('preset configs by API version', () => { expect(v6.version).toBe(6); expect(v6.storage).toEqual(v4.storage); - expect(v6.connectors).toEqual(v4.connectors); - expect(v6.applications).toEqual(v4.applications); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); expect(v6.applications[0].cache_settings).toHaveLength(1); // the rules deliver the static assets from the storage connector expect(JSON.stringify(v6.applications[0].rules)).toContain('"set_connector"'); @@ -121,8 +126,8 @@ describe('preset configs by API version', () => { expect(v6.version).toBe(6); expect(v6.storage).toEqual(v4.storage); - expect(v6.connectors).toEqual(v4.connectors); - expect(v6.applications).toEqual(v4.applications); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); + expect(v6.applications).toEqual(withoutActive(v4.applications)); expect(v6.applications[0].cache_settings).toHaveLength(1); expect(v6.storage[0].dir).toBe('./_site'); }); @@ -136,14 +141,14 @@ describe('preset configs by API version', () => { expect(v6.version).toBe(6); expect(v6.storage).toEqual(v4.storage); - expect(v6.connectors).toEqual(v4.connectors); + expect(v6.connectors).toEqual(withoutActive(v4.connectors)); // the function keeps the storage binding - expect(v6.functions).toEqual(v4.functions); + expect(v6.functions).toEqual(withoutActive(v4.functions)); expect(v6.functions[0].bindings).toEqual({ storage: { bucket: '$BUCKET_NAME', prefix: '$BUCKET_PREFIX' } }); - expect(v6.applications).toEqual(v4.applications); + expect(v6.applications).toEqual(withoutActive(v4.applications)); }); - it('javascript: binds the workload to an environment and to its own deployment', () => { + it('javascript: binds the workload to an environment and a deployment declared in the config', () => { const manifest = processConfig(resolvePresetConfig(byName('javascript'), 6)); expect(manifest.environments.map((environment: { name: string }) => environment.name)).toEqual([ @@ -152,11 +157,12 @@ describe('preset configs by API version', () => { expect( manifest.environments.map((environment: { deployment_policy: string }) => environment.deployment_policy), ).toEqual(['single_version']); - expect(manifest).not.toHaveProperty('deployments'); + expect(manifest.deployments.map((deployment: { name: string }) => deployment.name)).toEqual(['$DEPLOYMENT_NAME']); + expect(manifest.deployments.map((deployment: { binding_policy: string }) => deployment.binding_policy)).toEqual([ + 'FLEXIBLE', + ]); expect(manifest.workloads).toHaveLength(1); - expect(manifest.workloads[0]).toEqual( - expect.objectContaining({ name: '$WORKLOAD_NAME', active: true, infrastructure: 1 }), - ); + expect(manifest.workloads[0]).toEqual(expect.objectContaining({ name: '$WORKLOAD_NAME', infrastructure: 1 })); expect(manifest.workloads[0].bindings).toEqual([ { environment_name: '$ENVIRONMENT_NAME', deployment_name: '$DEPLOYMENT_NAME', domains: [] }, ]); diff --git a/packages/presets/src/presets/docusaurus/config.v6.ts b/packages/presets/src/presets/docusaurus/config.v6.ts index 53d84147..6d2414d2 100644 --- a/packages/presets/src/presets/docusaurus/config.v6.ts +++ b/packages/presets/src/presets/docusaurus/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/eleventy/config.v6.ts b/packages/presets/src/presets/eleventy/config.v6.ts index c1a6e1ff..afdc6d02 100644 --- a/packages/presets/src/presets/eleventy/config.v6.ts +++ b/packages/presets/src/presets/eleventy/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/emscripten/config.v6.ts b/packages/presets/src/presets/emscripten/config.v6.ts index b60a0de6..7720c9f4 100644 --- a/packages/presets/src/presets/emscripten/config.v6.ts +++ b/packages/presets/src/presets/emscripten/config.v6.ts @@ -48,7 +48,6 @@ const config: AzionConfigV6 = { { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [ [ { @@ -84,24 +83,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/gatsby/config.v6.ts b/packages/presets/src/presets/gatsby/config.v6.ts index 5ff287f9..559b1fd7 100644 --- a/packages/presets/src/presets/gatsby/config.v6.ts +++ b/packages/presets/src/presets/gatsby/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/hexo/config.v6.ts b/packages/presets/src/presets/hexo/config.v6.ts index 5ff287f9..559b1fd7 100644 --- a/packages/presets/src/presets/hexo/config.v6.ts +++ b/packages/presets/src/presets/hexo/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/html/config.v6.ts b/packages/presets/src/presets/html/config.v6.ts index 5fbaaa14..f1535552 100644 --- a/packages/presets/src/presets/html/config.v6.ts +++ b/packages/presets/src/presets/html/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/hugo/config.v6.ts b/packages/presets/src/presets/hugo/config.v6.ts index 5ff287f9..559b1fd7 100644 --- a/packages/presets/src/presets/hugo/config.v6.ts +++ b/packages/presets/src/presets/hugo/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/javascript/config.v6.ts b/packages/presets/src/presets/javascript/config.v6.ts index 033c3bdb..8e212f9b 100644 --- a/packages/presets/src/presets/javascript/config.v6.ts +++ b/packages/presets/src/presets/javascript/config.v6.ts @@ -20,7 +20,6 @@ const config: AzionConfigV6 = { { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [ [ { @@ -56,24 +55,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/jekyll/config.v6.ts b/packages/presets/src/presets/jekyll/config.v6.ts index c1a6e1ff..afdc6d02 100644 --- a/packages/presets/src/presets/jekyll/config.v6.ts +++ b/packages/presets/src/presets/jekyll/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/next/config.v6.ts b/packages/presets/src/presets/next/config.v6.ts index 1e5b74d0..ea9f962d 100644 --- a/packages/presets/src/presets/next/config.v6.ts +++ b/packages/presets/src/presets/next/config.v6.ts @@ -16,7 +16,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -55,7 +54,6 @@ const config: AzionConfigV6 = { { name: 'Next.js Static Assets and set cache policy', description: 'Serve Next.js static assets through edge connector and set cache policy', - active: true, criteria: [ [ { @@ -87,7 +85,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Static Assets and set cache policy', description: 'Serve static assets through edge connector and set cache policy', - active: true, criteria: [ [ { @@ -119,7 +116,6 @@ const config: AzionConfigV6 = { { name: 'Execute Next.js Function', description: 'Execute Next.js edge function for all requests', - active: true, criteria: [ [ { @@ -158,24 +154,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/nitro/config.v6.ts b/packages/presets/src/presets/nitro/config.v6.ts index 33421d59..6b1a3fbb 100644 --- a/packages/presets/src/presets/nitro/config.v6.ts +++ b/packages/presets/src/presets/nitro/config.v6.ts @@ -19,7 +19,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -58,7 +57,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -87,7 +85,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -116,7 +113,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Static Assets and set cache policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -149,7 +145,6 @@ const config: AzionConfigV6 = { { name: 'Execute Nitro Function', description: 'Execute Nitro function for all requests', - active: true, criteria: [ [ { @@ -188,24 +183,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/nuxt/config.v6.ts b/packages/presets/src/presets/nuxt/config.v6.ts index ca38a470..6410ca6c 100644 --- a/packages/presets/src/presets/nuxt/config.v6.ts +++ b/packages/presets/src/presets/nuxt/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -56,7 +55,6 @@ const config: AzionConfigV6 = { { name: 'Nuxt Static Assets and set cache policy', description: 'Serve Nuxt static assets through edge connector and set cache policy', - active: true, criteria: [ [ { @@ -88,7 +86,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -117,7 +114,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -147,7 +143,6 @@ const config: AzionConfigV6 = { name: 'Execute Nuxt Function when starts with /api/_content', description: 'Handle @nuxt/content API requests - executes Nuxt function for content management endpoints. Remove this rule if your project does not use the @nuxt/content library.', - active: true, criteria: [ [ { @@ -176,7 +171,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Static Assets and set cache policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -209,7 +203,6 @@ const config: AzionConfigV6 = { { name: 'Execute Nuxt Function', description: 'Execute Nuxt function for all requests', - active: true, criteria: [ [ { @@ -248,24 +241,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/opennextjs/config.v6.ts b/packages/presets/src/presets/opennextjs/config.v6.ts index 843b43e7..de816d77 100644 --- a/packages/presets/src/presets/opennextjs/config.v6.ts +++ b/packages/presets/src/presets/opennextjs/config.v6.ts @@ -19,7 +19,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -58,7 +57,6 @@ const config: AzionConfigV6 = { { name: 'Set storage origin for all requests _next_static and set cache policy', description: 'Serve Next.js static assets through edge connector and set cache policy', - active: true, criteria: [ [ { @@ -90,7 +88,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Static Assets and set cache policy', description: 'Serve static assets through edge connector and set cache policy', - active: true, criteria: [ [ { @@ -122,7 +119,6 @@ const config: AzionConfigV6 = { { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [ [ { @@ -161,24 +157,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/preact/config.v6.ts b/packages/presets/src/presets/preact/config.v6.ts index f1cdebf5..cbdb8c84 100644 --- a/packages/presets/src/presets/preact/config.v6.ts +++ b/packages/presets/src/presets/preact/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/qwik/config.v6.ts b/packages/presets/src/presets/qwik/config.v6.ts index f1cdebf5..cbdb8c84 100644 --- a/packages/presets/src/presets/qwik/config.v6.ts +++ b/packages/presets/src/presets/qwik/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/react/config.v6.ts b/packages/presets/src/presets/react/config.v6.ts index f1cdebf5..cbdb8c84 100644 --- a/packages/presets/src/presets/react/config.v6.ts +++ b/packages/presets/src/presets/react/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/rustwasm/config.v6.ts b/packages/presets/src/presets/rustwasm/config.v6.ts index 296d3895..af803187 100644 --- a/packages/presets/src/presets/rustwasm/config.v6.ts +++ b/packages/presets/src/presets/rustwasm/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -45,7 +44,6 @@ const config: AzionConfigV6 = { { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [ [ { @@ -81,24 +79,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/stencil/config.v6.ts b/packages/presets/src/presets/stencil/config.v6.ts index 5fbaaa14..f1535552 100644 --- a/packages/presets/src/presets/stencil/config.v6.ts +++ b/packages/presets/src/presets/stencil/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/svelte/config.v6.ts b/packages/presets/src/presets/svelte/config.v6.ts index f41188d5..b9f443f7 100644 --- a/packages/presets/src/presets/svelte/config.v6.ts +++ b/packages/presets/src/presets/svelte/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -56,7 +55,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Immutable Assets and Set Cache Policy', description: 'Delivers immutable assets and set cache policy.', - active: true, criteria: [ [ { @@ -88,7 +86,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html for Subpaths', description: 'Handle subpath requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -117,7 +114,6 @@ const config: AzionConfigV6 = { { name: 'Redirect to index.html', description: 'Handle directory requests by rewriting to index.html', - active: true, criteria: [ [ { @@ -146,7 +142,6 @@ const config: AzionConfigV6 = { { name: 'Deliver Static Assets and Set Cache Policy', description: 'Deliver static assets directly from storage and set cache policy', - active: true, criteria: [ [ { @@ -179,7 +174,6 @@ const config: AzionConfigV6 = { { name: 'Execute Svelte Function', description: 'Execute Svelte function for all requests', - active: true, criteria: [ [ { @@ -218,24 +212,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/typescript/config.v6.ts b/packages/presets/src/presets/typescript/config.v6.ts index 93717c73..2b9f734b 100644 --- a/packages/presets/src/presets/typescript/config.v6.ts +++ b/packages/presets/src/presets/typescript/config.v6.ts @@ -19,7 +19,6 @@ const config: AzionConfigV6 = { { name: 'Execute Function', description: 'Execute function for all requests', - active: true, criteria: [ [ { @@ -55,24 +54,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/vitepress/config.v6.ts b/packages/presets/src/presets/vitepress/config.v6.ts index 5852b6e6..38046f35 100644 --- a/packages/presets/src/presets/vitepress/config.v6.ts +++ b/packages/presets/src/presets/vitepress/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/vue/config.v6.ts b/packages/presets/src/presets/vue/config.v6.ts index f1cdebf5..cbdb8c84 100644 --- a/packages/presets/src/presets/vue/config.v6.ts +++ b/packages/presets/src/presets/vue/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', diff --git a/packages/presets/src/presets/vuepress/config.v6.ts b/packages/presets/src/presets/vuepress/config.v6.ts index 5852b6e6..38046f35 100644 --- a/packages/presets/src/presets/vuepress/config.v6.ts +++ b/packages/presets/src/presets/vuepress/config.v6.ts @@ -17,7 +17,6 @@ const config: AzionConfigV6 = { connectors: [ { name: '$CONNECTOR_NAME', - active: true, type: 'storage', attributes: { bucket: '$BUCKET_NAME', @@ -51,24 +50,17 @@ const config: AzionConfigV6 = { deploymentPolicy: 'single_version', }, ], + // the application a deployment serves is set by the Azion CLI when it creates the release + deployments: [ + { + name: '$DEPLOYMENT_NAME', + bindingPolicy: 'FLEXIBLE', + }, + ], workloads: [ { name: '$WORKLOAD_NAME', - active: true, infrastructure: 1, - deployments: [ - { - name: '$DEPLOYMENT_NAME', - current: true, - active: true, - strategy: { - type: 'default', - attributes: { - application: '$APPLICATION_NAME', - }, - }, - }, - ], bindings: [ { environment: '$ENVIRONMENT_NAME', From a8a12102348806828049dab1c62a91f777875388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Tue, 10 Nov 2026 17:11:04 -0300 Subject: [PATCH 28/29] chore: update the v6 changeset to the current openapi-v6-prod The deployments are at the root of the config again, and the v6 resources have no active. --- .changeset/config-api-v6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/config-api-v6.md b/.changeset/config-api-v6.md index 0fe792ed..be5c1fc6 100644 --- a/.changeset/config-api-v6.md +++ b/.changeset/config-api-v6.md @@ -5,5 +5,5 @@ Support the Azion API v6 config in the same packages. -- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments` (the deployment policy is required) and workloads with their `deployments` and `bindings` (a binding references an environment and one of the deployments of the workload by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. +- `@aziontech/config`: a config with `version: 6` is now validated and processed into a v6 manifest. v3 and v4 are unchanged, and a config without `version` is still the v4 one. v6 changes the publishing model: Save creates a Draft version and publishing is a separate step, so the config declares `environments` and `deployments` (the environment and deployment policies are required) and workloads with `bindings` (a binding references an environment and a deployment by name). Adds the build, applications (rules, cache settings, function instances and device groups), functions (with bindings), purge, storage, connectors, firewall, WAF, network lists and custom pages. `validateConfig`, `processConfig`, `validateManifest` and `convertJsonConfigToObject` accept v6, and `defineConfig` types the config as `AzionConfigV6`. The v3 and v4 manifests now carry the API version. The v6 API has no `active` in its resources, so the v6 config and manifest do not have it, and the `createSPARules` and `createMPARules` helpers no longer write `active: true` (it is the default of the v4 and v3 rules). - `@aziontech/presets`: every preset now provides its v6 config in `configs[6]` (`nitro` has no v3 config, as it did not exist on v3). `config` remains the default (v4) config. From bcf077ebc5e722a2e4488d01f0e9fdf694ae8625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Filho?= Date: Wed, 11 Nov 2026 09:21:45 -0300 Subject: [PATCH 29/29] fix(presets): resolve nuxt manifest from build output with fallbacks Nuxt >= 4.6 builds into node_modules/.cache/nuxt/.nuxt when .nuxt already exists, so .nuxt/manifest/meta is no longer reliable. Read the manifest from .output/public/_nuxt/builds/meta first, then fall back to the cache dir and .nuxt, picking the file referenced by latest.json to avoid stale manifests. --- .changeset/fix-nuxt-manifest.md | 5 ++ packages/presets/src/presets/nuxt/prebuild.ts | 54 ++++++++++++++++--- 2 files changed, 51 insertions(+), 8 deletions(-) create mode 100644 .changeset/fix-nuxt-manifest.md diff --git a/.changeset/fix-nuxt-manifest.md b/.changeset/fix-nuxt-manifest.md new file mode 100644 index 00000000..efdb425d --- /dev/null +++ b/.changeset/fix-nuxt-manifest.md @@ -0,0 +1,5 @@ +--- +'@aziontech/presets': patch +--- + +Fix the `nuxt` preset prebuild reading a stale or missing manifest. Nuxt >= 4.6 builds into `node_modules/.cache/nuxt/.nuxt` when `.nuxt` already exists, so `.nuxt/manifest/meta` is no longer reliable. The manifest is now read from `.output/public/_nuxt/builds/meta` first, then from the cache dir and `.nuxt`, picking the file that `latest.json` references. diff --git a/packages/presets/src/presets/nuxt/prebuild.ts b/packages/presets/src/presets/nuxt/prebuild.ts index 982ec0e8..97bb1eea 100644 --- a/packages/presets/src/presets/nuxt/prebuild.ts +++ b/packages/presets/src/presets/nuxt/prebuild.ts @@ -2,10 +2,19 @@ import { AzionPrebuildResult, BuildConfiguration, BuildContext } from '@aziontec import { exec } from '@aziontech/utils/node'; import { existsSync } from 'fs'; import { mkdir, readFile, readdir } from 'fs/promises'; +import { dirname, join } from 'path'; const NUXT_CONFIG_FILES = ['nuxt.config.js', 'nuxt.config.ts', 'nuxt.config.mjs', 'nuxt.config.cjs']; const PATHS = { - MANIFEST_DIR: '.nuxt/manifest/meta', + // Candidate locations of the Nuxt app manifest (`/.json`), in priority order: + // 1. final build output, independent of `buildDir` (Nuxt 4.5.x and 4.6.x) + // 2. Nuxt >= 4.6 builds into the cache dir when `.nuxt` already exists + // 3. default `buildDir` (Nuxt <= 4.5.x) + MANIFEST_DIRS: [ + '.output/public/_nuxt/builds/meta', + 'node_modules/.cache/nuxt/.nuxt/manifest/meta', + '.nuxt/manifest/meta', + ], OUTPUT_DIR: '.output/public', SERVER_ENTRY: '.output/server/index.mjs', } as const; @@ -40,11 +49,40 @@ async function readNuxtPreset() { } } -async function readManifest(dirManifest: string) { - const files = await readdir(dirManifest); - const manifestFile = files.find((file) => file.endsWith('.json')); - const manifest = await readFile(`${dirManifest}/${manifestFile}`, 'utf8'); - return JSON.parse(manifest); +async function readManifestFromDir(dirManifest: string) { + let manifestFile: string | undefined; + + // `latest.json` sits next to the `meta` dir and points to the current build id. + // Prefer it to avoid reading a stale manifest when more than one build id is present. + try { + const latest = JSON.parse(await readFile(join(dirname(dirManifest), 'latest.json'), 'utf8')); + if (typeof latest?.id === 'string' && existsSync(join(dirManifest, `${latest.id}.json`))) { + manifestFile = `${latest.id}.json`; + } + } catch { + // no latest.json, fall back to the first manifest file found + } + + if (!manifestFile) { + const files = await readdir(dirManifest); + manifestFile = files.find((file) => file.endsWith('.json')); + } + if (!manifestFile) { + throw new Error(`No manifest file found in ${dirManifest}`); + } + + return JSON.parse(await readFile(join(dirManifest, manifestFile), 'utf8')); +} + +async function readManifest(dirs: readonly string[] = PATHS.MANIFEST_DIRS) { + for (const dir of dirs) { + try { + return await readManifestFromDir(dir); + } catch { + // try next candidate + } + } + throw new Error(`Nuxt manifest not found in: ${dirs.join(', ')}`); } function createAzionPrebuildResult(manifest: Record): AzionPrebuildResult { @@ -79,7 +117,7 @@ async function prebuild(buildConfig: BuildConfiguration, ctx: BuildContext): Pro await mkdir(PATHS.OUTPUT_DIR, { recursive: true }); if (hasNitroPreset) { try { - const manifest = await readManifest(PATHS.MANIFEST_DIR); + const manifest = await readManifest(); configureNitroPreset(buildConfig); return createAzionPrebuildResult(manifest); } catch { @@ -97,7 +135,7 @@ async function prebuild(buildConfig: BuildConfiguration, ctx: BuildContext): Pro verbose: true, }); try { - const manifest = await readManifest(PATHS.MANIFEST_DIR); + const manifest = await readManifest(); configureNitroPreset(buildConfig); return createAzionPrebuildResult(manifest); } catch {