Skip to content

Commit

Permalink
[Fleet] Fix incorrect conversion of string to numeric values in agent…
Browse files Browse the repository at this point in the history
… YAML (#90371)

* Convert user values back to string after yaml template compilation if they were strings originally

* Add better test cases and adjust patch

* Fix when field is undefined

* Handle array of strings too
  • Loading branch information
jen-huang authored Feb 5, 2021
1 parent befe410 commit f4dc6d0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
16 changes: 16 additions & 0 deletions x-pack/plugins/fleet/server/services/epm/agent/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,23 @@ password: {{password}}
{{#if password}}
hidden_password: {{password}}
{{/if}}
{{#if optional_field}}
optional_field: {{optional_field}}
{{/if}}
foo: {{bar}}
some_text_field: {{should_be_text}}
multi_text_field:
{{#each multi_text}}
- {{this}}
{{/each}}
`;
const vars = {
paths: { value: ['/usr/local/var/log/nginx/access.log'] },
password: { type: 'password', value: '' },
optional_field: { type: 'text', value: undefined },
bar: { type: 'text', value: 'bar' },
should_be_text: { type: 'text', value: '1234' },
multi_text: { type: 'text', value: ['1234', 'foo', 'bar'] },
};

const output = compileTemplate(vars, streamTemplate);
Expand All @@ -35,6 +48,9 @@ hidden_password: {{password}}
exclude_files: ['.gz$'],
processors: [{ add_locale: null }],
password: '',
foo: 'bar',
some_text_field: '1234',
multi_text_field: ['1234', 'foo', 'bar'],
});
});

Expand Down
12 changes: 12 additions & 0 deletions x-pack/plugins/fleet/server/services/epm/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ function replaceVariablesInYaml(yamlVariables: { [k: string]: any }, yaml: any)
return yaml;
}

const maybeEscapeNumericString = (value: string) => {
return value.length && !isNaN(+value) ? `"${value}"` : value;
};

function buildTemplateVariables(variables: PackagePolicyConfigRecord, templateStr: string) {
const yamlValues: { [k: string]: any } = {};
const vars = Object.entries(variables).reduce((acc, [key, recordEntry]) => {
Expand All @@ -84,6 +88,14 @@ function buildTemplateVariables(variables: PackagePolicyConfigRecord, templateSt
const yamlKeyPlaceholder = `##${key}##`;
varPart[lastKeyPart] = `"${yamlKeyPlaceholder}"`;
yamlValues[yamlKeyPlaceholder] = recordEntry.value ? safeLoad(recordEntry.value) : null;
} else if (recordEntry.type && recordEntry.type === 'text' && recordEntry.value?.length) {
if (Array.isArray(recordEntry.value)) {
varPart[lastKeyPart] = recordEntry.value.map((value: string) =>
maybeEscapeNumericString(value)
);
} else {
varPart[lastKeyPart] = maybeEscapeNumericString(recordEntry.value);
}
} else {
varPart[lastKeyPart] = recordEntry.value;
}
Expand Down

0 comments on commit f4dc6d0

Please sign in to comment.