diff --git a/plugins/foreign/foreign.c b/plugins/foreign/foreign.c index 92b96ce..070bc3f 100644 --- a/plugins/foreign/foreign.c +++ b/plugins/foreign/foreign.c @@ -3175,12 +3175,26 @@ cmd_foreign(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) if (sp_buf_init(&j) != 0) return sp_buf_puts(out, "error: out of memory"); if (strcmp(sub, "search") == 0) { - (void)sp_buf_printf(&j, "{\"query\":\"%s%s%s\"}", a1, - a2[0] != '\0' ? " " : "", a2); + /* + * The text is the operator's, so it is escaped: a quote in + * /foreign search he said "hi" used to end the JSON string + * early and the whole search was answered with "'query' is + * required". + */ + sp_buf_puts(&j, "{\"query\":\""); + (void)sp_json_escape(&j, a1); + if (a2[0] != '\0') { + sp_buf_puts(&j, " "); + (void)sp_json_escape(&j, a2); + } + sp_buf_puts(&j, "\"}"); rc = tool_search(j.p, out, h); } else { - (void)sp_buf_printf(&j, "{\"source\":\"%s\",\"id\":\"%s\"}", - a1, a2); + sp_buf_puts(&j, "{\"source\":\""); + (void)sp_json_escape(&j, a1); + sp_buf_puts(&j, "\",\"id\":\""); + (void)sp_json_escape(&j, a2); + sp_buf_puts(&j, "\"}"); rc = strcmp(sub, "import") == 0 ? import_any(h, src_of(a1), a2, out) : tool_read(j.p, out, h); } diff --git a/tests/test_foreign.c b/tests/test_foreign.c index 7716684..26b5179 100644 --- a/tests/test_foreign.c +++ b/tests/test_foreign.c @@ -702,6 +702,18 @@ main(void) CHECK(contains(out.p, cla)); sp_buf_clear(&out); + /* + * The command's argument is the operator's text and goes into a JSON + * request. Unescaped, a quote in it ended the string early and + * /foreign search he said "hi" was answered with "'query' is + * required" - the whole phrase was lost. + */ + CHECK(sp_host_command(host, "foreign", + "search OC-ASSISTANT-PROSE \"quoted\"", &out) == 0); + CHECK(contains(out.p, "OC-ASSISTANT-PROSE")); + CHECK(!contains(out.p, "'query' is required")); + sp_buf_clear(&out); + /* * A store that cannot be read says why. The message used to be built * from errno, which nothing on the path had set: a database with the