Compare commits

..
5 Commits
Author SHA1 Message Date
brad ArantandClaude Opus 5.5 2847ce5fa7 Add jetc --lint-sql to find <sql> that pastes values (phase 2)
Implements phase 2 of docs/design-sql-bound-parameters.md. jetc --lint-sql
[--strict] <file|dir>... lists each <sql> whose statement contains a $[...]
or #[...] reference instead of a <bind>, with file:line and where each value
comes from. Row values ($[.col], $[session.col], $[?N], $[#]) are only
reported with --strict. References in <bind>, <if>, <set> and the other
attribute-only tags, <comment> and |> <| are skipped. A custom tag defined
as <sql><container></sql> (barant.com's <showtable>) is checked at each use.
Exit status is 0 for none found, 1 for findings, 2 for an unreadable path.

- jetc/JetLint.*: the scanner; jetc.cpp: the option
- build scripts and runbindtests.sh: link JetLint.cpp
- tests/runlinttests.sh and tests/lintsql/: fixtures and expected output
- docs: worklist for the local copies of both sites, design doc status,
  manual note on the lint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:29:28 -08:00
brad ArantandClaude Opus 5.5 fd81bb877f Document <bind> and bound parameters in the user manual
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:22:50 -08:00
brad ArantandClaude Opus 5.5 cfdb3cbf57 Avoid a trigraph warning in the SqlBind unit test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:22:03 -08:00
brad ArantandClaude Opus 5.5 3c6411c16e Error on unterminated tags instead of looping forever
The Tag constructor's attribute loop made no progress at end of data, so
a tag that never closed - such as <set value="a\"> with its closing quote
escaped - hung jet-2.0. Throw "unterminated <name> tag." at end of data,
and "unterminated value for X in <name>." when an attribute value's
closing quote is missing.

Needs CoreUtils with the getTokenExclude fix for <set value="a\\">.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:57:51 -08:00
brad ArantandClaude Opus 5.5 a18d1358b0 Add <bind> bound parameters for <sql> (phase 1)
Implements phase 1 of docs/design-sql-bound-parameters.md: <bind> supplies
the value for the next ? placeholder of the enclosing <sql>, with typed
validation (int, decimal, date, datetime, bool, ident with allow list),
null="empty", and refusal to change the connection character set.

- SqlBind.*: MySQL-free placeholder scanning and binding logic
- __bind.*, __sql, __mysql: runtime wiring
- Tag.cpp, jetc/JetParser.cpp: bind is a void tag in both
- jetc/JetCodegen: emit sized ZString literals for text holding a NUL,
  which previously truncated the compiled page
- tests: unit tests, end-to-end test against MySQL (interpreted and
  jetc-compiled), and the generator for the binary test page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:55:23 -08:00
38 changed files with 1847 additions and 10 deletions

No files matched your search

+305
View File
@@ -0,0 +1,305 @@
#include "SqlBind.h"
#include "Exception.h"
#include <cctype>
namespace jet {
namespace {
std::string lower(std::string s) {
for(char &c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
std::string trim(const std::string &s) {
size_t b = 0, e = s.size();
while(b < e && std::isspace((unsigned char)s[b])) ++b;
while(e > b && std::isspace((unsigned char)s[e - 1])) --e;
return s.substr(b, e - b);
}
std::string where(int position) {
return "bind " + std::to_string(position) + ": ";
}
bool allDigits(const std::string &s, size_t from, size_t to) {
if(from >= to) return false;
for(size_t i = from; i < to; ++i)
if(!std::isdigit((unsigned char)s[i])) return false;
return true;
}
// ^-?[0-9]{1,maxDigits}$
bool isInteger(const std::string &s, size_t maxDigits) {
size_t start = (!s.empty() && s[0] == '-') ? 1 : 0;
size_t digits = s.size() - start;
return digits >= 1 && digits <= maxDigits && allDigits(s, start, s.size());
}
// ^-?[0-9]{1,30}(\.[0-9]{1,30})?$
bool isDecimal(const std::string &s) {
size_t dot = s.find('.');
if(dot == std::string::npos) return isInteger(s, 30);
std::string frac = s.substr(dot + 1);
return isInteger(s.substr(0, dot), 30) && frac.size() >= 1 && frac.size() <= 30 && allDigits(frac, 0, frac.size());
}
int num(const std::string &s, size_t at, size_t len) {
return std::stoi(s.substr(at, len));
}
// YYYY-MM-DD with a real month and day range.
bool isDate(const std::string &s) {
if(s.size() != 10 || s[4] != '-' || s[7] != '-') return false;
if(!allDigits(s, 0, 4) || !allDigits(s, 5, 7) || !allDigits(s, 8, 10)) return false;
int month = num(s, 5, 2), day = num(s, 8, 2);
return month >= 1 && month <= 12 && day >= 1 && day <= 31;
}
// YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS
bool isDateTime(const std::string &s) {
if(s.size() != 16 && s.size() != 19) return false;
if(!isDate(s.substr(0, 10)) || s[10] != ' ' || s[13] != ':') return false;
if(!allDigits(s, 11, 13) || !allDigits(s, 14, 16)) return false;
if(num(s, 11, 2) > 23 || num(s, 14, 2) > 59) return false;
if(s.size() == 19) {
if(s[16] != ':' || !allDigits(s, 17, 19) || num(s, 17, 2) > 59) return false;
}
return true;
}
// Walks query and calls onPlaceholder(index) for every '?' that is
// outside '...', "...", `...`, -- / # line comments and /* */
// comments. With NO_BACKSLASH_ESCAPES off, a backslash escapes the
// next character inside '...' and "..."; with it on, it doesn't.
// A doubled quote ('', "", ``) is an escaped quote in every mode.
template<typename F>
void scan(const std::string &q, bool noBackslashEscapes, F onPlaceholder) {
size_t i = 0, n = q.size();
while(i < n) {
char c = q[i];
if(c == '\'' || c == '"' || c == '`') {
char quote = c;
++i;
while(i < n) {
if(quote != '`' && !noBackslashEscapes && q[i] == '\\') { i += 2; continue; }
if(q[i] == quote) {
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
++i;
break;
}
++i;
}
continue;
}
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
while(i < n && q[i] != '\n') ++i;
continue;
}
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
size_t end = q.find("*/", i + 2);
i = (end == std::string::npos) ? n : end + 2;
continue;
}
if(c == '?') onPlaceholder(i);
++i;
}
}
// Lowercased words ([a-z0-9_@.$]) outside quotes and comments.
std::vector<std::string> words(const std::string &q) {
std::vector<std::string> out;
std::string cur;
size_t i = 0, n = q.size();
auto flush = [&]() { if(!cur.empty()) { out.push_back(lower(cur)); cur.clear(); } };
while(i < n) {
char c = q[i];
if(c == '\'' || c == '"' || c == '`') {
flush();
char quote = c;
++i;
while(i < n) {
if(quote != '`' && q[i] == '\\') { i += 2; continue; }
if(q[i] == quote) {
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
++i;
break;
}
++i;
}
out.push_back("'"); // a literal stands between words
continue;
}
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
flush();
while(i < n && q[i] != '\n') ++i;
continue;
}
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
flush();
size_t end = q.find("*/", i + 2);
i = (end == std::string::npos) ? n : end + 2;
continue;
}
if(std::isalnum((unsigned char)c) || c == '_' || c == '@' || c == '.' || c == '$')
cur += c;
else
flush();
++i;
}
flush();
return out;
}
}
BoundValue makeBoundValue(const std::string &value,
const std::string &typeIn,
const std::string &nullModeIn,
bool hasAllow,
const std::string &allow,
int position) {
std::string type = typeIn.empty() ? "string" : lower(trim(typeIn));
std::string nullMode = lower(trim(nullModeIn));
if(nullMode != "" && nullMode != "empty")
throw coreutils::Exception(where(position) + "null must be \"empty\".");
if(hasAllow && type != "ident")
throw coreutils::Exception(where(position) + "allow is only valid with type=\"ident\".");
BoundValue b;
if(nullMode == "empty" && value.empty()) {
b.kind = BoundValue::SQLNULL;
return b;
}
if(type == "string") {
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "int") {
if(!isInteger(value, 19))
throw coreutils::Exception(where(position) + "value is not a valid int.");
b.kind = BoundValue::BARE;
b.text = value;
} else if(type == "decimal") {
if(!isDecimal(value))
throw coreutils::Exception(where(position) + "value is not a valid decimal.");
b.kind = BoundValue::BARE;
b.text = value;
} else if(type == "bool") {
std::string v = lower(value);
b.kind = BoundValue::BARE;
if(v == "1" || v == "true" || v == "yes")
b.text = "1";
else if(v == "0" || v == "false" || v == "no")
b.text = "0";
else
throw coreutils::Exception(where(position) + "value is not a valid bool.");
} else if(type == "date") {
if(!isDate(value))
throw coreutils::Exception(where(position) + "value is not a valid date (YYYY-MM-DD).");
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "datetime") {
if(!isDateTime(value))
throw coreutils::Exception(where(position) + "value is not a valid datetime (YYYY-MM-DD HH:MM[:SS]).");
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "ident") {
if(!hasAllow)
throw coreutils::Exception(where(position) + "type=\"ident\" requires an allow list.");
// Match case-insensitively, but emit the allow list's own spelling:
// what reaches the query always comes from the page, never the request.
std::string match;
bool found = false;
size_t start = 0;
while(start <= allow.size()) {
size_t comma = allow.find(',', start);
if(comma == std::string::npos) comma = allow.size();
std::string entry = trim(allow.substr(start, comma - start));
if(!entry.empty() && lower(entry) == lower(value)) {
match = entry;
found = true;
break;
}
start = comma + 1;
}
if(!found)
throw coreutils::Exception(where(position) + "value is not in the allow list.");
b.kind = BoundValue::BARE;
std::string m = lower(match);
if(m == "asc" || m == "desc") {
b.text = (m == "asc") ? "ASC" : "DESC";
} else {
b.text = "`";
for(char c : match) {
if(c == '`') b.text += '`';
b.text += c;
}
b.text += "`";
}
} else
throw coreutils::Exception(where(position) + "unknown type \"" + type + "\".");
return b;
}
size_t countPlaceholders(const std::string &query, bool noBackslashEscapes) {
size_t count = 0;
scan(query, noBackslashEscapes, [&](size_t) { ++count; });
return count;
}
std::string bindPlaceholders(const std::string &query,
const std::vector<BoundValue> &values,
bool noBackslashEscapes,
const std::function<std::string(const std::string &)> &quoteEscape) {
std::vector<size_t> at;
scan(query, noBackslashEscapes, [&](size_t i) { at.push_back(i); });
if(at.size() != values.size())
throw coreutils::Exception("sql: " + std::to_string(at.size()) + " placeholders but " +
std::to_string(values.size()) + " bind values");
std::string out;
out.reserve(query.size() + 32 * values.size());
size_t last = 0;
for(size_t k = 0; k < at.size(); ++k) {
out.append(query, last, at[k] - last);
const BoundValue &v = values[k];
if(v.kind == BoundValue::SQLNULL)
out += "NULL";
else if(v.kind == BoundValue::BARE)
out += v.text;
else {
out += '\'';
out += quoteEscape(v.text);
out += '\'';
}
last = at[k] + 1;
}
out.append(query, last, std::string::npos);
return out;
}
bool isCharsetChange(const std::string &query) {
std::vector<std::string> w = words(query);
if(w.empty() || w[0] != "set")
return false;
for(size_t i = 1; i < w.size(); ++i) {
const std::string &x = w[i];
if(x == "names" || x == "charset")
return true;
if(x == "character" && i + 1 < w.size() && w[i + 1] == "set")
return true;
// character_set_client, @@character_set_client, @@session.character_set_client, ...
for(const char *var : {"character_set_client", "character_set_connection", "collation_connection"}) {
std::string v(var);
if(x.size() >= v.size() && x.compare(x.size() - v.size(), v.size(), v) == 0)
return true;
}
}
return false;
}
}
+64
View File
@@ -0,0 +1,64 @@
#ifndef __SqlBind_h__
#define __SqlBind_h__
#include <functional>
#include <string>
#include <vector>
// Bound parameters for <sql> - see docs/design-sql-bound-parameters.md.
//
// Everything here is plain string logic with no MySQL or Tag dependency,
// so it can be unit tested on its own (tests/sqlbind_test.cpp). __bind
// builds BoundValues with makeBoundValue(); __sql substitutes them into
// the rendered query with bindPlaceholders(), passing in the connection's
// own escaping function.
namespace jet {
struct BoundValue {
enum Kind {
SQLNULL, // emitted as NULL
BARE, // already validated (int/decimal/bool/ASC/DESC/`ident`) - emitted as is
QUOTED // escaped with the connection's escaper and wrapped in '...'
};
Kind kind = QUOTED;
std::string text;
};
// Validates value against type and returns how it must be emitted.
// position is the 1-based bind number, used only in error messages.
// Error messages never contain the value itself (it may be a password).
// type: string (default if empty), int, decimal, bool, date, datetime, ident
// nullMode: "" (bind '' for an empty value) or "empty" (bind NULL)
// allow: comma list of permitted identifiers - required for ident,
// not allowed on any other type
BoundValue makeBoundValue(const std::string &value,
const std::string &type,
const std::string &nullMode,
bool hasAllow,
const std::string &allow,
int position);
// Number of '?' placeholders in query that are outside string literals,
// backtick identifiers and comments.
size_t countPlaceholders(const std::string &query, bool noBackslashEscapes);
// Replaces each placeholder (as counted above) with the matching bound
// value, in order. Throws if the placeholder and value counts differ.
// quoteEscape escapes the body of a single-quoted string literal (no
// surrounding quotes) for the actual connection.
std::string bindPlaceholders(const std::string &query,
const std::vector<BoundValue> &values,
bool noBackslashEscapes,
const std::function<std::string(const std::string &)> &quoteEscape);
// True for a SET statement that changes the connection character set
// (SET NAMES, SET CHARACTER SET, SET CHARSET, or an assignment to
// character_set_client / character_set_connection / collation_connection).
// Changing it after connect makes client-side escaping and server-side
// parsing disagree, so <sql> refuses these.
bool isCharsetChange(const std::string &query);
}
#endif
+11 -2
View File
@@ -6,6 +6,7 @@
#include "Global.h"
#include "__mysql.h"
#include "__sql.h"
#include "__bind.h"
#include "__imap.h"
#include "__imaplist.h"
#include "__imapmessage.h"
@@ -65,6 +66,10 @@ namespace jet {
bool finished = false;
while(!finished) {
in.skipWhitespace();
// Nothing below makes progress at end of data, so a tag that
// never closes would otherwise loop here forever.
if(in.eod())
throw coreutils::Exception("unterminated <" + name.str() + "> tag.");
if(in.ifNext(">")) {
// jet-1.4's real parser knew which built-ins never take
// a body (its own "void element" list) - real 1.4
@@ -88,7 +93,7 @@ namespace jet {
(nameLower == "cookie") || (nameLower == "header") ||
(nameLower == "read") || (nameLower == "write") ||
(nameLower == "call") || (nameLower == "system") ||
(nameLower == "dump");
(nameLower == "dump") || (nameLower == "bind");
// A CUSTOM tag (not one of jet's own built-ins above)
// written bare, with no explicit close, is genuinely
// ambiguous: is a real body coming (scan for
@@ -155,7 +160,8 @@ namespace jet {
keywords[keywordName] = in.getTokenExclude(dq ? "\"" : "'");
else
throw coreutils::Exception("keyword name must be unique for tag.");
in.ifNext(dq ? "\"" : "'");
if(!in.ifNext(dq ? "\"" : "'"))
throw coreutils::Exception("unterminated value for " + keywordName.str() + " in <" + name.str() + ">.");
} else if(keywordName.getLength() > 0) {
// Unquoted attribute value (e.g. TYPE=NE, SCOPE=LOCAL - real
// 1.4 content throughout). Neither quote style matched, but
@@ -494,6 +500,9 @@ namespace jet {
} else if(ifTagName(in, "sql")) {
__sql _sql(in, out, global, this, local);
continue;
} else if(ifTagName(in, "bind")) {
__bind _bind(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imap")) {
__imap _imap(in, out, global, this, local);
continue;
+29
View File
@@ -0,0 +1,29 @@
#include "__bind.h"
#include "__sql.h"
#include "Exception.h"
#include "SqlBind.h"
namespace jet {
__bind::__bind(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
output = false;
// Nearest enclosing <sql>, through any <if>/<for>/etc. in between.
__sql *sql = NULL;
for(Tag *scope = parent; scope && !sql; scope = scope->parent)
sql = dynamic_cast<__sql *>(scope);
if(!sql)
throw coreutils::Exception("bind must be inside sql.");
if(!keywordDefined("value"))
throw coreutils::Exception("bind must have a value.");
std::string value = resolveKeyword("value").str();
std::string type = keywordDefined("type") ? resolveKeyword("type").str() : "";
std::string nullMode = keywordDefined("null") ? resolveKeyword("null").str() : "";
bool hasAllow = keywordDefined("allow");
std::string allow = hasAllow ? resolveKeyword("allow").str() : "";
sql->addBind(makeBoundValue(value, type, nullMode, hasAllow, allow, (int)sql->bindCount() + 1));
}
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef ____bind_h__
#define ____bind_h__
#include "Tag.h"
namespace jet {
// <bind value="..." [type="..."] [null="empty"] [allow="a,b"]> - supplies
// the value for the next '?' placeholder of the enclosing <sql>. Always
// void (no closing tag) and produces no output. See
// docs/design-sql-bound-parameters.md.
class __bind : public Tag {
public:
__bind(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
};
}
#endif
+17
View File
@@ -108,6 +108,10 @@ namespace jet {
if(!mysql) {
MYSQL *handle = mysql_init(NULL);
// Pin the connection character set so <bind>'s client-side
// escaping and the server's parsing always agree (<sql> refuses
// SET NAMES and friends for the same reason).
mysql_options(handle, MYSQL_SET_CHARSET_NAME, "utf8mb4");
mysql = mysql_real_connect(handle,
hostVal.c_str(),
userVal.c_str(),
@@ -207,6 +211,19 @@ namespace jet {
}
}
std::string __mysql::escapeString(const std::string &value) {
std::string to(value.size() * 2 + 1, '\0');
unsigned long len = mysql_real_escape_string_quote(mysql, to.data(), value.data(), value.size(), '\'');
if(len == (unsigned long)-1)
throw coreutils::Exception("sql: bind value could not be escaped.");
to.resize(len);
return to;
}
bool __mysql::noBackslashEscapes() {
return (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES) != 0;
}
void __mysql::nextRow() {
row = mysql_fetch_row(result);
fieldLength = mysql_fetch_lengths(result);
+7
View File
@@ -22,6 +22,13 @@ namespace jet {
bool hasRow();
coreutils::ZString getColumnValue(coreutils::ZString column);
// Body of a single-quoted SQL string literal for this connection
// (mysql_real_escape_string_quote: uses the connection's character
// set and honours NO_BACKSLASH_ESCAPES). Used by <bind>.
std::string escapeString(const std::string &value);
// True while the session's sql_mode includes NO_BACKSLASH_ESCAPES.
bool noBackslashEscapes();
private:
// Explicitly initialized - result/row/fieldLength were otherwise
// left as garbage stack values until query() first ran. A
+15 -1
View File
@@ -26,7 +26,21 @@ namespace jet {
if(!global.sessionExists(sessionId))
throw coreutils::Exception("sessionid does not exist.");
processContainer(container);
global.getSession(sessionId)->query(out);
__mysql *session = global.getSession(sessionId);
// No <bind> inside: the query runs exactly as rendered, with no '?'
// replacement at all, so existing queries containing a literal '?'
// are unaffected. See docs/design-sql-bound-parameters.md.
if(binds.empty()) {
if(isCharsetChange(out.str()))
throw coreutils::Exception("sql: changing the connection character set is not allowed.");
session->query(out);
return;
}
std::string bound = bindPlaceholders(out.str(), binds, session->noBackslashEscapes(),
[session](const std::string &s) { return session->escapeString(s); });
if(isCharsetChange(bound))
throw coreutils::Exception("sql: changing the connection character set is not allowed.");
session->query(coreutils::MString(bound));
}
}
+9
View File
@@ -2,6 +2,8 @@
#define ____sql_h__
#include "Tag.h"
#include "SqlBind.h"
#include <vector>
namespace jet {
@@ -10,6 +12,13 @@ namespace jet {
public:
__sql(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
// Called by each <bind> inside this <sql> while its body renders.
void addBind(BoundValue value) { binds.push_back(std::move(value)); }
size_t bindCount() const { return binds.size(); }
private:
std::vector<BoundValue> binds;
};
}
BIN
View File
Binary file not shown.
+91
View File
@@ -377,6 +377,82 @@ variable parsing. This sequence is |> this is not parsed or resolved
and is different from the <exclude /> tag as exclude may be further
parsed if output is again evaluated.
\section{bind}
Use the bind tag inside an sql tag to supply the value for a ?
placeholder in the statement. Each bind fills the next ? in order. The
value is escaped or checked before it reaches the server, so whatever
it contains can never change the meaning of the statement. Use bind for
every value that comes from a request, a cookie or a session instead of
writing \$[name] into the statement text.
The bind tag has no closing tag and produces no output. It must be
inside an sql tag, although it may be inside other tags (if, for and so
on) within that sql tag.
\begin{verbatim}
<sql>select id, name from users where email=? and status=?
<bind value="$[email]">
<bind value="ACTIVE">
</sql>
\end{verbatim}
The attributes are:
value - the value to bind. Required. Any expression or variable
reference may be used here.
type - how the value is checked and sent. The values are:
\begin{itemize}
\item string - the default. Quoted and escaped.
\item int - a whole number of up to 19 digits, optionally negative.
Sent without quotes.
\item decimal - a number with an optional fraction, for example
-12.50. Sent without quotes.
\item bool - 1, true, yes, 0, false or no (any case). Sent as 1 or 0.
\item date - YYYY-MM-DD.
\item datetime - YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS.
\item ident - a column or table name, or a sort direction, for the
places SQL cannot take a value (ORDER BY and so on). Requires the allow
attribute. Names are sent in backticks; ASC and DESC are sent as they
are.
\end{itemize}
null - set to empty to send SQL NULL when the value is empty. Without
it an empty value is sent as an empty string (and is an error for int,
decimal, bool, date and datetime).
allow - for type="ident" only. A comma separated list of the values
that are permitted. Any other value is an error.
\begin{verbatim}
<sql>select * from products order by ? ?
<bind value="$[sort]" type="ident" allow="name,price,created">
<bind value="$[dir]" type="ident" allow="ASC,DESC">
</sql>
\end{verbatim}
A ? inside a quoted string, a backtick name or a comment in the
statement is not a placeholder. An sql tag that contains no bind tags
is run exactly as written, so a ? in it is left alone.
These are errors, and can be caught with try/catch: a value that does
not fit its type, an ident that is not in the allow list, a bind
outside an sql tag, a bind with no value, an unknown type, and a
statement whose number of ? placeholders differs from its number of
bind tags. The error text never contains the bound value itself.
To find the sql tags that still write values into the statement text,
run the jet compiler's lint over a site:
\begin{verbatim}
jetc --lint-sql /path/to/site
\end{verbatim}
It prints the file and line of each one, with the variables it uses.
Add \texttt{-{}-strict} to include values from the rows of an earlier query.
\section{call}
Use the call tag to evoke an executable file from a jet script.
@@ -570,6 +646,21 @@ As long as sql statements are executed within the same mysql
containing tag then the same mysql session is used for each sql
statement.
Values that come from a request, a cookie or a session should be
passed with bind tags and ? placeholders rather than written into the
statement text. See the bind tag.
\begin{verbatim}
<sql>delete from cart_item where session_uuid=? and sku=?
<bind value="$[_session_id]">
<bind value="$[sku]">
</sql>
\end{verbatim}
A statement that changes the connection character set (SET NAMES, SET
CHARACTER SET and similar) is refused. The connection always uses
utf8mb4.
The attributes are:
sessionid
+238
View File
@@ -0,0 +1,238 @@
# Design: bound parameters for `<sql>`
**Status:** phases 1 and 2 implemented (2026-11-20) · **Author:** Brad Arant (drafted with Claude) · **Date:** 2026-10-23
**Applies to:** JetCore (`__sql`, `__mysql`, `Tag.cpp` tag dispatch, `jetc` parser/codegen)
## 1. The problem
`<sql>` builds its query by rendering its body as text, then sending the finished
string to MySQL:
```cpp
// __sql.cpp today
processContainer(container); // every $[...] substituted as plain text
global.getSession(sessionId)->query(out); // mysql_real_query(the whole string)
```
So a request value lands *inside the SQL text*:
```html
<sql>select id from users where email='$[email]' and secret='$[password]'</sql>
```
With `email = x' or '1'='1' -- ` that becomes a different query. There is no
escaping function in Jet, so this is the only way to write a query, and it's
unsafe everywhere a value comes from a request. Numeric positions are worse:
`where id=$[id]` has no quotes, so even escaping wouldn't help (`id = 1 or 1=1`).
Measured on 2026-10-23 (`<sql>` blocks whose body contains a request/session
value other than `$[.column]`, `$[_login_id]` or `$[_session_id]`):
| Site | `<sql>` blocks | with values pasted in | files |
|---|---:|---:|---:|
| barant.com | 152 | 117 | 64 |
| ClockPlanet | 94 | 83 | 35 |
Roughly 80% of all queries. Login, signup, cart, checkout and admin pages are
all in that set.
## 2. Goals
1. A way to pass values to `<sql>` that **can never change the query's meaning**,
whatever they contain.
2. **No change to how results are read** - `<ifrow>`, `<whilerow>`, `$[.column]`,
`$[?N]`, `$[#]` keep working exactly as today.
3. Easy, mechanical migration of existing pages; old pages keep running until migrated.
4. A path to *enforcing* it, so new unsafe queries can't be written by accident.
Non-goals: an ORM, query builders, or changing `<database>`/`<mysql>` connection handling.
## 3. Proposed syntax
Placeholders are `?` in the query; values come from `<bind>` tags inside the
`<sql>`, in order:
```html
<sql>
select id, name from users where email=? and status=?
<bind value="$[email]">
<bind value="ACTIVE">
</sql>
```
`<bind>` attributes:
| attribute | meaning |
|---|---|
| `value` | the value (any Jet expression - `$[...]` is fine here, that's the point) |
| `type` | `string` (default), `int`, `decimal`, `bool`, `date`, `datetime`, `ident` |
| `null` | `empty` = bind SQL `NULL` when the value is empty (default: bind `''`) |
| `allow` | for `type="ident"` only: comma list of permitted identifiers |
Type behaviour (a value that doesn't fit throws a catchable Jet exception -
`<try>`/`<catch>` works, see §6):
- `string` - quoted and escaped (§4).
- `int` - must match `^-?[0-9]{1,19}$`; emitted bare. This fixes the unquoted
`where id=$[id]` case.
- `decimal` - must match `^-?[0-9]{1,30}(\.[0-9]{1,30})?$`; emitted bare.
- `bool` - `1/0/true/false/yes/no` → `1`/`0`.
- `date` / `datetime` - must parse as `YYYY-MM-DD` / `YYYY-MM-DD HH:MM[:SS]`; quoted.
- `ident` - for the things SQL can't parameterise (column in `ORDER BY`, a sort
direction, a table name). The value must be in `allow` or it throws; emitted
backtick-quoted (`ASC`/`DESC` emitted bare). Example:
```html
<sql>select * from products order by ? ?
<bind value="$[sort]" type="ident" allow="name,price,created">
<bind value="$[dir]" type="ident" allow="ASC,DESC">
</sql>
```
Why `<bind>` and not `<param>`: `param` is an HTML element (inside `<object>`),
and `jetc`'s void-tag list treats it as HTML. A Jet-only name avoids any ambiguity.
Why positional `?` and not named (`:email`): `?` is what MySQL and every SQL
library uses, it needs no new attribute-name syntax in the parser, and the
`<bind>` lines sit right under the query so the order is easy to read. Named
binds can be added later without breaking this (§9).
## 4. How it works
### Emulated binding (recommended for phase 1)
`__sql` collects the `<bind>` values while its body renders, then replaces each
`?` that is **outside** a string literal, backtick identifier or comment with the
bound value, rendered safely - and only then calls `query()` as today.
- Strings are escaped with `mysql_real_escape_string_quote(mysql, to, from, len, '\'')`
and wrapped in single quotes. This uses the *connection's* character set and
respects `NO_BACKSLASH_ESCAPES`, which plain `mysql_real_escape_string` doesn't.
- The connection's character set is pinned at connect time
(`mysql_options(MYSQL_SET_CHARSET_NAME, "utf8mb4")` in `__mysql`), so escaping
and server parsing always agree. `<sql>` refuses a `SET NAMES`/`SET CHARACTER SET`
statement (the classic way to make escaping and parsing disagree).
- Number of `?` must equal number of `<bind>`s, otherwise throw
`"sql: 3 placeholders but 2 bind values"`.
This is the same approach PHP's PDO uses by default. Its big advantage here:
**the result path doesn't change at all** - `query()` still runs
`mysql_real_query` and `mysql_store_result`, so `MYSQL_ROW`, `getColumnValue()`,
`<ifrow>`, `<whilerow>` and the column-index map are untouched.
### Why not real server-side prepared statements (yet)
`mysql_stmt_*` returns rows through typed bind buffers, not `MYSQL_ROW`, so
`getColumnValue()`, `$[?N]`, `$[#]` and the field-index map would all need a
second implementation, and some statements (multi-statements, some DDL) can't be
prepared. That's a bigger change for no extra safety over correct emulation.
It stays open as a later option (§9), behind the same `<bind>` syntax, so pages
written now won't need touching again.
### Code shape
- **New** `__bind.h/.cpp`: on construction, find the nearest enclosing `__sql`
(walk `parent` with `dynamic_cast<__sql*>`; throw `"bind must be inside sql"`
if none), resolve `value`/`type`/`null`/`allow`, validate per type, and call
`sql->addBind(...)`. Produces no output.
- **`__sql`**: a `std::vector<BoundValue>` member and `addBind()`. After
`processContainer(container)`, run `bindPlaceholders(out)` - a small scanner
that tracks `'...'` (with `''` and `\'`), `"..."`, `` `...` ``, `-- `, `#` and
`/* */` so `?` inside them is left alone - then `query(result)`.
- **`__mysql`**: `escapeString(const MString&)` wrapper around
`mysql_real_escape_string_quote`; pin `utf8mb4` at connect.
- **`Tag.cpp`**: add `ifTagName(in, "bind")` next to `sql` (line ~494).
- **`jetc` `JetParser.cpp`**: add `"bind"` to the Jet void-tag list (it has no
closing tag); **`JetCodegen.cpp`**: emit `__bind` like the other tags.
Estimated size: ~200 lines plus tests.
## 5. Existing pages: nothing breaks
A `<sql>` with no `<bind>` runs exactly as today - no `?` replacement at all,
so existing queries containing a literal `?` are unaffected. Migration is
page by page:
```html
<!-- before -->
<sql>select * from users where email="$[email]" and status="CONFIRM"</sql>
<!-- after -->
<sql>select * from users where email=? and status="CONFIRM"
<bind value="$[email]">
</sql>
<!-- before: unquoted number, injectable even with escaping -->
<sql>delete from cart_item where session_uuid='$[_session_id]' and sku='$[sku]'</sql>
<!-- after -->
<sql>delete from cart_item where session_uuid=? and sku=?
<bind value="$[_session_id]">
<bind value="$[sku]">
</sql>
```
## 6. Errors
- Bad `<bind>` value (wrong type, ident not allowed), placeholder/bind count
mismatch, `<bind>` outside `<sql>`: throw `coreutils::Exception` with a clear
message, caught by `<try>`/`<catch>` like the MySQL errors fixed on 2026-09-13.
- The exception text never includes the bound value itself (it may be a password).
## 7. Enforcement
Once pages are migrated, make the unsafe form an error instead of a habit:
1. **`jetc --lint-sql`** - lists every `<sql>` whose body contains `$[...]`
other than `$[.column]` (row values from an outer query), with file:line.
This is the migration worklist (§8) and a CI check.
As implemented (`jetc/JetLint.cpp`): `jetc --lint-sql [--strict] <file|dir>...`
scans every file under the given paths. It reports `$[...]` and local
`#[...]` references, with the kind of each (`global`, `cgi`, `session`,
`env`, `keyword`, `local`). Row values (`$[.col]`, `$[session.col]`,
`$[?N]`, `$[#]`, `$[?#]`) are not reported unless `--strict` is given.
References in the attributes of `<bind>`, `<if>`, `<else>`, `<ifrow>`,
`<while>`, `<whilerow>`, `<until>`, `<for>` and `<set>` are not reported,
since those never become statement text; nor is anything inside
`<comment>` or `|> <|`. A custom tag defined as `<sql ...><container></sql>`
(barant.com's `<showtable>`) takes its statement from the caller's content,
so each use of it is checked like an `<sql>`. Exit status: 0 nothing found,
1 findings, 2 a path could not be read. Tests: `tests/runlinttests.sh`.
2. **Per-site strict mode** - an APIServer site setting
`"sqlInterpolation": "warn" | "error"`. In `error` mode `<sql>` refuses to run
if its body substituted any `$[...]` except `$[.column]`; `warn` logs it.
Default `warn` for existing sites, `error` for new ones.
3. **Escape hatch** - `<sql raw="yes">` for the rare trusted dynamic SQL
(generated by the site itself, never from input), so it's visible in review
and greppable.
## 8. Migration plan
| Phase | What | Notes |
|---|---|---|
| 1 | Implement `<bind>`, escaping, utf8mb4 pinning, tests | JetCore only; no page changes. Done 2026-11-20 |
| 2 | `jetc --lint-sql`; run on both sites | produces the worklist (≈200 queries). Done 2026-11-20 on the local copies: see [sql-lint-worklist.md](sql-lint-worklist.md) |
| 3 | Convert the high-risk pages first | login/signup/password reset, cart/checkout/payment (`pp.jet`), admin procs, ClockPlanet `mobile_api.jet` and auth |
| 4 | Convert the rest; turn on `warn` | logs show anything missed |
| 5 | Switch both sites to `error` | unsafe queries can no longer ship |
Phase 3 is the one that matters most for security and is a few days' work;
each conversion is mechanical and testable page by page.
## 9. Later
- Named binds: `where email=:email` + `<bind name="email" value="...">`.
- Real prepared statements (`mysql_stmt_*`) behind the same `<bind>` syntax.
- The companion fix for output: HTML-escape `$[...]` by default with an explicit
raw form - the same "safe unless you say otherwise" rule for the other half of
the injection problem (cross-site scripting).
## 10. Tests
- Every type: valid values bind correctly; invalid values throw.
- Injection strings (`' or '1'='1`, `\'`, multibyte sequences such as `0xbf27`,
`--`, `;`, NUL bytes) are stored and read back byte-for-byte unchanged.
- `?` inside `'...'`, `"..."`, `` `...` ``, `--`, `#` and `/* */` is never replaced.
- Placeholder/bind count mismatch throws; `<bind>` outside `<sql>` throws.
- A `<sql>` with no binds produces exactly the same query text as before.
- `<ifrow>`/`<whilerow>`/`$[.col]`/`$[?N]`/`$[#]` behave identically on bound queries.
- `NO_BACKSLASH_ESCAPES` on and off.
+166
View File
@@ -0,0 +1,166 @@
# `<sql>` migration worklist
Output of `jetc --lint-sql` (phase 2 of [design-sql-bound-parameters.md](design-sql-bound-parameters.md)),
generated 2026-11-20 from the copies of the two sites in `~/Development`.
Each line is a `<sql>` (or a use of a custom tag that wraps one, such as
barant.com's `<showtable>`) whose statement pastes in a variable instead of
using `<bind>`. The kind in brackets is where the value comes from: `global`
includes request parameters, `cgi` is a POST body field, `session` is
`$[@name]`, `local` is `#[name]`.
These local copies are not the whole of either live site. ClockPlanet in
particular has only billing and a few site pages here (no `mobile_api.jet`), so
rerun the lint on the live site trees for the full list:
```
jetc --lint-sql /path/to/site
```
Phase 3 starts with login/signup/password reset, cart/checkout/payment and
admin procs (see the design doc §8).
## barant.com (`JetCore/jetc/barant-site`)
```
./src/SIPPHONE.tag:178: <sql> pastes $[_login_id] (global)
./src/account-info.subpage:3: <sql> pastes $[_login_id] (global)
./src/account-info.subpage:14: <sql> pastes $[_login_id] (global)
./src/account-info.subpage:28: <sql> pastes $[_login_id] (global)
./src/account-info.subpage:54: <sql> pastes $[_login_id] (global)
./src/account-invoices.subpage:3: <sql> pastes $[@_invoice_id] (session)
./src/account-invoices.subpage:14: <showtable> (wraps sql) pastes $[_login_id] (global)
./src/accountconfirm.page:14: <sql> pastes $[uuid] (global)
./src/accountconfirm.page:15: <sql> pastes $[uuid] (global)
./src/accountconfirm.page:16: <sql> pastes $[id] (global)
./src/add_track.page:10: <sql> pastes $[collection_id] (global)
./src/add_track.proc:5: <sql> pastes $[login_id] (global), $[collection_id] (global), $[name] (global), $[artist] (global), $[description] (global), $[price] (global), $[filedata_binary] (global)
./src/addtasknote.page:12: <sql> pastes $[_task_id] (global)
./src/addtasknote.proc:3: <sql> pastes $[_task_id] (global), $[_login_id] (global), $[noteb] (global), $[task_status_id] (global)
./src/addtocart.proc:1: <sql> pastes $[_session_id] (global), $[sku] (global)
./src/addtocart.proc:4: <sql> pastes $[_session_id] (global), $[sku] (global), $[qty] (global)
./src/admin-mailaccounts.subpage:19: <sql> pastes $[@_login_id] (session)
./src/barant.tag:70: <sql> pastes #[table] (local), #[where] (local), #[sortfield] (local)
./src/cart.menu:2: <sql> pastes $[_session_id] (global)
./src/cart.page:17: <sql> pastes $[_session_id] (global)
./src/cart.page:34: <sql> pastes $[_session_id] (global)
./src/cart.page:67: <sql> pastes $[_session_id] (global)
./src/changeprojecticon.proc:3: <sql> pastes $[datax] (global)
./src/changeprojecticon.proc:9: <sql> pastes $[image_id] (global), $[_project_id] (global)
./src/checkout.page:65: <sql> pastes $[_session_id] (global)
./src/checkout.page:75: <sql> pastes $[_session_id] (global)
./src/copy_invoice.jet:14: <sql> pastes $[source_invoice_id] (global)
./src/copy_invoice.jet:19: <sql> pastes $[new_invoice_id] (global), $[source_invoice_id] (global)
./src/create_invoice.jet:14: <sql> pastes $[user_id] (global)
./src/createaccount.proc:17: <sql> pastes $[email:0] (global)
./src/createaccount.proc:28: <sql> pastes $[name] (global), $[company_name] (global), $[email] (global), $[password] (global)
./src/createaccount.proc:46: <sql> pastes $[id] (global), $[link] (global)
./src/createproject.proc:2: <sql> pastes $[_login_id] (global), $[text] (global), $[description] (global)
./src/createreleasetarget.proc:4: <sql> pastes $[_project_id] (global), $[release] (global), $[descriptionx] (global)
./src/createrequest.proc:4: <sql> pastes $[_project_id] (global), $[_login_id] (global), $[priority] (global), $[release_id] (global), $[textx] (global), $[descriptionx] (global)
./src/createtask.proc:5: <sql> pastes $[_request_id] (global), $[_login_id] (global), $[textx] (global), $[descriptionx] (global)
./src/deleterequest.proc:3: <sql> pastes $[_request_id] (global)
./src/documents.jet:2: <sql> pastes $[id] (global), $[@_login_id] (session)
./src/documents_api.jet:17: <sql> pastes $[@_login_id] (session), $[name] (global)
./src/documents_api.jet:29: <sql> pastes $[id] (global), $[@_login_id] (session)
./src/documents_api.jet:31: <sql> pastes $[id] (global), $[@_login_id] (session)
./src/documents_api.jet:43: <sql> pastes $[@_login_id] (session)
./src/documents_delete.proc:4: <sql> pastes $[delete_id] (global), $[@_login_id] (session)
./src/documents_delete.proc:6: <sql> pastes $[delete_id] (global), $[@_login_id] (session)
./src/documents_upload.proc:4: <sql> pastes $[@_login_id] (session), $[name] (global)
./src/editinvoice.page:180: <sql> pastes $[@_invoice_id] (session)
./src/editinvoice.page:234: <sql> pastes $[@_invoice_id] (session)
./src/editproduct.page:8: <sql> pastes $[_product_sku] (global)
./src/editrequest.page:7: <sql> pastes $[_request_id] (global)
./src/edittask.page:12: <sql> pastes $[_task_id] (global)
./src/invoice.method:1: <sql> pastes $[@_invoice_id] (session)
./src/invoice.method:28: <sql> pastes $[@_invoice_id] (session)
./src/invoice.method:51: <sql> pastes $[@_invoice_id] (session)
./src/invoices.menu:2: <sql> pastes $[_user_id] (global)
./src/login.method:1: <sql> pastes $[login_email] (global), $[login_password] (global)
./src/login.method:16: <sql> pastes $[login_id] (global)
./src/login.method:17: <sql> pastes $[login_id] (global)
./src/mailaccounts.jet:25: <sql> pastes $[@_login_id] (session), $[mail_email] (global), $[mail_host] (global), $[mail_password] (global)
./src/mailaccounts.jet:38: <sql> pastes $[account_id] (global), $[@_login_id] (session)
./src/make_invoice.method:5: <sql> pastes $[_session_id] (global)
./src/make_invoice.method:47: <sql> pastes $[_login_id] (global), $[total] (global)
./src/make_invoice.method:62: <sql> pastes $[invoice_id] (global), $[total] (global), $[card_brand] (global), $[last_4_digits] (global), $[exp_month] (global), $[exp_year] (global), $[payment_id] (global), $[tranonce] (global)
./src/make_invoice.method:74: <sql> pastes $[_session_id] (global)
./src/make_invoice.method:81: <sql> pastes $[invoice_id] (global)
./src/make_invoice.method:96: <sql> pastes $[license] (global)
./src/make_invoice.method:97: <sql> pastes $[_login_id] (global), $[invoice_id] (global), $[license] (global), $[key] (global)
./src/make_invoice.method:110: <sql> pastes $[_session_id] (global)
./src/memberhometemplate.temp:25: <sql> pastes $[login_id] (global)
./src/menu.bar:18: <sql> pastes $[_session_id] (global)
./src/musicianhome.page:13: <sql> pastes $[login_id] (global)
./src/musicianhome.page:35: <sql> pastes $[login_id] (global)
./src/myprojects.page:15: <showtable> (wraps sql) pastes $[_login_id] (global)
./src/myworklist.page:10: <showtable> (wraps sql) pastes $[_login_id] (global)
./src/newcollection.proc:11: <sql> pastes $[login_id] (global), $[name] (global), $[artist] (global), $[description] (global), $[price] (global)
./src/payinvoice.page:7: <sql> pastes $[_invoice_id] (global)
./src/phones.section:1: <sql> pastes $[@_login_id] (session)
./src/phones.section:9: <showtable> (wraps sql) pastes $[@_login_id] (session)
./src/processorder.proc:4: <sql> pastes $[_login_id] (global)
./src/processorder.proc:7: <sql> pastes $[_session_id] (global)
./src/processorder.proc:12: <sql> pastes $[invoice_id] (global)
./src/processorder.proc:27: <sql> pastes $[license] (global)
./src/processorder.proc:28: <sql> pastes $[_login_id] (global), $[invoice_id] (global), $[license] (global), $[key] (global)
./src/processorder.proc:41: <sql> pastes $[_session_id] (global)
./src/project.page:16: <sql> pastes $[_project_id] (global)
./src/project.page:37: <showtable> (wraps sql) pastes $[_project_id] (global)
./src/project.tag:3: <sql> pastes $[_project_id] (global)
./src/projects.menu:1: <sql> pastes $[_login_id] (global)
./src/projman.bar:15: <sql> pastes $[_session_id] (global)
./src/registermusician.proc:2: <sql> pastes $[login_id] (global)
./src/removecartitem.proc:1: <sql> pastes $[_session_id] (global), $[sku] (global)
./src/removefromcart.proc:1: <sql> pastes $[_session_id] (global)
./src/request.page:12: <sql> pastes $[_request_id] (global)
./src/request.page:43: <showtable> (wraps sql) pastes $[_request_id] (global)
./src/selectproject.proc:2: <sql> pastes $[project_id] (global)
./src/selecttask.proc:2: <sql> pastes $[task_id] (global)
./src/send_invoice_email.method:5: <sql> pastes $[_send_invoice_id] (global)
./src/task.page:12: <sql> pastes $[_request_id] (global)
./src/task.page:35: <sql> pastes $[_task_id] (global)
./src/taskassignresource.page:15: <sql> pastes $[_task_id] (global)
./src/taskassignresource.proc:5: <sql> pastes $[_task_id] (global), $[user_id] (global), $[estimate_hours] (global)
./src/update_invoice.proc:3: <sql> pastes $[@_invoice_id] (session)
./src/update_invoice.proc:5: <sql> pastes $[@_invoice_id] (session), $[sku$[ix]] (global), $[quantity$[ix]] (global), $[description$[ix]] (global), $[textarea$[ix]] (global), $[price$[ix]] (global), $[total$[ix]] (global), $[tax_amount$[ix]] (global), $[type$[ix]] (global)
./src/update_invoice.proc:8: <sql> pastes $[invoice_total] (global), $[user_id] (global), $[@_invoice_id] (session)
./src/update_product.proc:2: <sql> pastes $[type] (global), $[description] (global), $[text] (global), $[price] (global), $[image] (global), $[_product_sku] (global)
./src/updatecartqty.proc:2: <sql> pastes $[_session_id] (global), $[sku] (global)
./src/updatecartqty.proc:4: <sql> pastes $[qty] (global), $[_session_id] (global), $[sku] (global)
./src/updaterequest.proc:6: <sql> pastes $[textx] (global), $[descriptionx] (global), $[priority] (global), $[owner_id] (global), $[release_id] (global), $[_request_id] (global)
./src/upload_modular1_1_preset.proc:5: <sql> pastes $[title] (global), $[textx] (global), $[preset_datax] (global), $[audio_samplex] (global)
lint-sql: 108 of 139 <sql> blocks (and uses of tags that wrap <sql>) paste values into the statement, in 64 of 76 files (global 174, local 3, session 22)
```
## ClockPlanet (`~/Development/ClockPlanet`)
```
./billing/account.page:9: <sql> pastes $[_acct_bid] (global)
./billing/account.page:46: <sql> pastes $[_acct_bid] (global), $[_acct_req] (global)
./billing/account.page:157: <sql> pastes $[_acct_bid] (global)
./billing/account.page:159: <sql> pastes $[_acct_bid] (global)
./billing/billing_api.jet:28: <sql> pastes $[_mail_key] (global)
./billing/billing_api.jet:50: <sql> pastes $[_mail_key] (global)
./billing/billing_api.jet:53: <sql> pastes $[_notice_business] (global)
./billing/dobilling_pay.proc:16: <sql> pastes $[_bp_bid] (global)
./billing/dobilling_settings.proc:7: <sql> pastes $[_bs_bid] (global), $[_bs_low] (global), $[_bs_rep] (global)
./billing/dobilling_settings.proc:14: <sql> pastes $[_bs_low] (global), $[_bs_rep] (global), $[_bs_bid] (global)
./billing/doemployee_add.proc:6: <sql> pastes $[@_login_business_id] (session), $[name] (global), $[role] (global), $[phone] (global), $[mode] (global), $[invitecode] (global)
./billing/invoice.method:1: <sql> pastes $[_cp_invoice_id] (global)
./billing/invoice.method:33: <sql> pastes $[_cp_invoice_id] (global)
./billing/invoice.method:52: <sql> pastes $[_cp_invoice_id] (global)
./billing/send_invoice_email.method:3: <sql> pastes $[_send_invoice_id] (global)
./site-live/billing-current.txt:10: <sql> pastes $[_acct_bid] (global)
./site-live/billing-current.txt:49: <sql> pastes $[_acct_bid] (global), $[_acct_req] (global)
./site-live/billing-current.txt:114: <sql> pastes $[_acct_bid] (global)
./site-live/billing-current.txt:116: <sql> pastes $[_acct_bid] (global)
./site-live/billing-current.txt:252: <sql> pastes $[_mail_key] (global)
./site-live/billing-current.txt:272: <sql> pastes $[_mail_key] (global)
./site-live/billing-current.txt:275: <sql> pastes $[_notice_business] (global)
./site-live/billing-current.txt:313: <sql> pastes $[@_login_business_id] (session), $[name] (global), $[role] (global), $[phone] (global), $[mode] (global), $[invitecode] (global)
./site-live/sites.page:12: <sql> pastes $[@_login_business_id] (session)
./site-live/sites.page:32: <sql> pastes $[@_login_business_id] (session)
./site-live/sites.page:36: <sql> pastes $[@_login_business_id] (session)
lint-sql: 26 of 28 <sql> blocks paste values into the statement, in 9 of 10 files (global 37, session 5)
```
+10 -3
View File
@@ -32,6 +32,13 @@ namespace jetc {
return r;
}
std::string Codegen::zstr(const std::string &raw) {
// A plain C string literal stops at its first NUL, so text holding
// one (raw bytes in a page) has to carry its length explicitly.
if (raw.find('\0') == std::string::npos) return cstr(raw);
return "coreutils::ZString(" + cstr(raw) + ", " + std::to_string(raw.size()) + ")";
}
const char *Codegen::staticTypeOp(const std::string &type, const char *rc) {
// type is known at compile time (a literal attribute value, not a
// runtime expression) so the comparison operator is picked once here
@@ -59,7 +66,7 @@ namespace jetc {
case NodeKind::TEXT: {
if (n->text.empty()) break;
target << I << "out << " << cstr(n->text) << ";\n";
target << I << "out << " << zstr(n->text) << ";\n";
break;
}
@@ -166,7 +173,7 @@ namespace jetc {
}
case NodeKind::FALLBACK: {
target << I << "{ coreutils::ZString span(" << cstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
target << I << "{ coreutils::ZString span(" << zstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
break;
}
@@ -213,7 +220,7 @@ namespace jetc {
// correctness fallback: any invocation this compiler doesn't
// itself recognize - e.g. reached through content this pass
// never compiled - still resolves it exactly as it always has).
target << I << "{ coreutils::ZString span(" << cstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
target << I << "{ coreutils::ZString span(" << zstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
if (compiledOk) {
// The registration into compiledTags right after is the only
// new behavior beyond the raw registration above - a pure
+1
View File
@@ -86,6 +86,7 @@ namespace jetc {
void emitNode(const NodePtr &n, int indent, std::ostringstream &target);
static std::string ind(int indent);
static std::string cstr(const std::string &raw); // C++ string-literal escape
static std::string zstr(const std::string &raw); // same, as a sized ZString if it holds a NUL
static const char *staticTypeOp(const std::string &type, const char *rcVar);
};
+322
View File
@@ -0,0 +1,322 @@
#include "JetLint.h"
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <map>
#include <sstream>
// See JetLint.h. This is a plain text scan of the page source rather than a
// use of jetc's Parser: the parser keeps no line numbers, compiles some
// content into fallback spans, and stops at the first error, while a lint
// run over a whole site has to report every <sql> in every file.
namespace jetc {
namespace {
bool startsWithNoCase(const std::string &s, size_t pos, const char *word) {
for (size_t i = 0; word[i]; ++i)
if (pos + i >= s.size() || std::tolower((unsigned char)s[pos + i]) != word[i]) return false;
return true;
}
bool isTagEndChar(char c) {
return c == '>' || c == '/' || std::isspace((unsigned char)c);
}
// "<name" at pos, followed by whitespace, '>' or '/'.
bool isOpenTag(const std::string &s, size_t pos, const std::string &name) {
if (s[pos] != '<' || !startsWithNoCase(s, pos + 1, name.c_str())) return false;
size_t after = pos + 1 + name.size();
return after < s.size() && isTagEndChar(s[after]);
}
// "</name" + optional whitespace + ">" at pos. Returns the position
// after the '>', or npos.
size_t closeTagEnd(const std::string &s, size_t pos, const std::string &name) {
if (s.compare(pos, 2, "</") != 0 || !startsWithNoCase(s, pos + 2, name.c_str())) return std::string::npos;
size_t i = pos + 2 + name.size();
while (i < s.size() && std::isspace((unsigned char)s[i])) ++i;
return (i < s.size() && s[i] == '>') ? i + 1 : std::string::npos;
}
// pos is at '<'. Returns the position of the '>' ending the opening
// tag, skipping quoted attribute values, or npos.
size_t openTagEnd(const std::string &s, size_t pos) {
char quote = 0;
for (size_t i = pos + 1; i < s.size(); ++i) {
char c = s[i];
if (quote) { if (c == quote) quote = 0; }
else if (c == '"' || c == '\'') quote = c;
else if (c == '>') return i;
}
return std::string::npos;
}
// pos is at "$[" or "#[". Returns the position after the matching
// ']' (nested references included), or npos.
size_t refEnd(const std::string &s, size_t pos) {
int depth = 0;
for (size_t i = pos; i < s.size(); ++i) {
if ((s[i] == '$' || s[i] == '#') && i + 1 < s.size() && s[i + 1] == '[') { ++depth; ++i; }
else if (s[i] == ']' && --depth == 0) return i + 1;
}
return std::string::npos;
}
// What a reference reads from, from its type designator (see
// Tag::getVariable). "row" is a column of an earlier query.
std::string refKind(const std::string &ref) {
if (ref[0] == '#') return "local";
char d = ref.size() > 2 ? ref[2] : 0;
switch (d) {
case ':': return "cgi";
case '@': return "session";
case '&': return "env";
case '%': return "keyword";
case '!': return "global";
case '.': case '?': case '#': return "row";
}
// $[session.column] - a dot outside any nested reference.
int depth = 0;
for (size_t i = 2; i + 1 < ref.size(); ++i) {
if (ref[i] == '[') ++depth;
else if (ref[i] == ']') --depth;
else if (ref[i] == '.' && depth == 0) return "row";
}
return "global";
}
int lineAt(const std::string &s, size_t pos) {
return 1 + (int)std::count(s.begin(), s.begin() + pos, '\n');
}
// Tags inside a <sql> whose attributes never become statement text:
// <bind> passes its value safely, and the rest only decide what the
// body renders.
const char *const attributeOnlyTags[] = {
"bind", "if", "else", "ifrow", "while", "whilerow", "until", "for", "set",
};
}
void lintSqlText(const std::string &file, const std::string &s, bool strict,
const std::vector<std::string> &wrappers,
std::vector<LintFinding> &findings, LintStats &stats) {
std::vector<std::string> names{"sql"};
names.insert(names.end(), wrappers.begin(), wrappers.end());
bool counted = false;
size_t pos = 0;
while ((pos = s.find('<', pos)) != std::string::npos) {
std::string name;
for (const auto &n : names)
if (isOpenTag(s, pos, n)) { name = n; break; }
if (name.empty()) { ++pos; continue; }
if (!counted) { ++stats.files; counted = true; }
++stats.sqlBlocks;
size_t tagStart = pos;
size_t gt = openTagEnd(s, pos);
if (gt == std::string::npos) break;
pos = gt + 1;
if (s[gt - 1] == '/') continue; // <sql ... /> has no statement
LintFinding finding{file, lineAt(s, tagStart), name, {}};
int depth = 1;
size_t i = pos;
while (i < s.size()) {
size_t end;
if (s[i] == '<') {
if ((end = closeTagEnd(s, i, name)) != std::string::npos) {
i = end;
if (--depth == 0) break;
continue;
}
if (isOpenTag(s, i, name)) {
// A nested block of the same tag is its own block; it is
// reported when the outer scan reaches it.
++depth;
size_t e = openTagEnd(s, i);
i = (e == std::string::npos) ? s.size() : e + 1;
continue;
}
if (isOpenTag(s, i, "comment")) {
size_t c = s.find("</comment>", i);
i = (c == std::string::npos) ? s.size() : c + 10;
continue;
}
bool skipped = false;
for (const char *tag : attributeOnlyTags)
if (isOpenTag(s, i, tag)) {
size_t e = openTagEnd(s, i);
i = (e == std::string::npos) ? s.size() : e + 1;
skipped = true;
break;
}
if (skipped) continue;
} else if (s.compare(i, 2, "|>") == 0) {
// |> ... <| is never parsed, so nothing in it is a reference.
size_t c = s.find("<|", i + 2);
i = (c == std::string::npos) ? s.size() : c + 2;
continue;
} else if ((s[i] == '$' || s[i] == '#') && i + 1 < s.size() && s[i + 1] == '[') {
end = refEnd(s, i);
if (end == std::string::npos) end = s.size();
LintRef ref{s.substr(i, end - i), ""};
ref.kind = refKind(ref.text);
i = end;
if (ref.kind == "row" && !strict) continue;
bool seen = false;
for (auto &r : finding.refs) seen = seen || r.text == ref.text;
if (!seen) finding.refs.push_back(ref);
continue;
}
++i;
}
if (!finding.refs.empty()) {
++stats.flaggedBlocks;
findings.push_back(finding);
}
// Carry on from the end of this <sql>'s opening tag, not its body,
// so a nested <sql> is still counted and checked.
}
}
namespace {
bool fileMentions(const std::string &text, const std::vector<std::string> &names) {
for (size_t p = 0; (p = text.find('<', p)) != std::string::npos; ++p)
for (const auto &n : names)
if (isOpenTag(text, p, n)) return true;
return false;
}
bool readFile(const std::string &path, std::string &text) {
std::ifstream in(path, std::ios::binary);
if (!in) return false;
std::ostringstream ss;
ss << in.rdbuf();
text = ss.str();
return true;
}
}
void findSqlWrappers(const std::string &s, std::vector<std::string> &wrappers) {
for (size_t pos = 0; (pos = s.find('<', pos)) != std::string::npos; ++pos) {
if (!isOpenTag(s, pos, "tag")) continue;
size_t gt = openTagEnd(s, pos);
if (gt == std::string::npos) return;
std::string open = s.substr(pos, gt - pos);
// name="X" (or name='X')
std::string lower = open;
for (auto &c : lower) c = (char)std::tolower((unsigned char)c);
size_t n = lower.find("name=");
if (n == std::string::npos || n + 5 >= open.size()) continue;
char q = open[n + 5];
if (q != '"' && q != '\'') continue;
size_t e = open.find(q, n + 6);
if (e == std::string::npos) continue;
std::string name = open.substr(n + 6, e - n - 6);
// Tag names match without regard to case (isOpenTag lowercases).
for (auto &c : name) c = (char)std::tolower((unsigned char)c);
size_t close = std::string::npos;
for (size_t c = gt; (c = s.find("</", c)) != std::string::npos; ++c)
if (closeTagEnd(s, c, "tag") != std::string::npos) { close = c; break; }
std::string body = s.substr(gt + 1, (close == std::string::npos ? s.size() : close) - gt - 1);
// An <sql> in the definition whose statement is the caller's content.
for (size_t p = 0; (p = body.find('<', p)) != std::string::npos; ++p) {
if (!isOpenTag(body, p, "sql")) continue;
size_t bgt = openTagEnd(body, p);
if (bgt == std::string::npos) break;
size_t end = std::string::npos;
for (size_t c = bgt; (c = body.find("</", c)) != std::string::npos; ++c)
if (closeTagEnd(body, c, "sql") != std::string::npos) { end = c; break; }
std::string stmt = body.substr(bgt + 1, (end == std::string::npos ? body.size() : end) - bgt - 1);
bool hasContainer = false;
for (size_t c = 0; (c = stmt.find('<', c)) != std::string::npos; ++c)
hasContainer = hasContainer || isOpenTag(stmt, c, "container");
if (hasContainer && !name.empty() &&
std::find(wrappers.begin(), wrappers.end(), name) == wrappers.end()) {
wrappers.push_back(name);
break;
}
}
}
}
int lintSql(const std::vector<std::string> &paths, bool strict, std::ostream &out, std::ostream &err) {
namespace fs = std::filesystem;
std::vector<std::string> files;
bool error = false;
for (const auto &p : paths) {
std::error_code ec;
if (fs::is_directory(p, ec)) {
std::vector<std::string> found;
for (auto it = fs::recursive_directory_iterator(p, fs::directory_options::skip_permission_denied, ec);
it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (ec) break;
std::string name = it->path().filename().string();
if (it->is_directory(ec) && !name.empty() && name[0] == '.') { it.disable_recursion_pending(); continue; }
if (it->is_regular_file(ec)) found.push_back(it->path().string());
}
std::sort(found.begin(), found.end());
files.insert(files.end(), found.begin(), found.end());
} else if (fs::is_regular_file(p, ec)) {
files.push_back(p);
} else {
err << "jetc: cannot open " << p << std::endl;
error = true;
}
}
// Two passes: a custom tag defined anywhere in the scanned files as
// <sql ...><container></sql> takes its statement from the caller's
// content, so each use of it is checked like an <sql>.
std::vector<std::string> texts(files.size());
std::vector<bool> readOk(files.size(), false);
std::vector<std::string> wrappers;
for (size_t i = 0; i < files.size(); ++i) {
if (!readFile(files[i], texts[i])) { err << "jetc: cannot read " << files[i] << std::endl; error = true; continue; }
readOk[i] = true;
findSqlWrappers(texts[i], wrappers);
}
std::vector<std::string> names{"sql"};
names.insert(names.end(), wrappers.begin(), wrappers.end());
std::vector<LintFinding> findings;
LintStats stats;
for (size_t i = 0; i < files.size(); ++i) {
if (!readOk[i] || !fileMentions(texts[i], names)) continue;
lintSqlText(files[i], texts[i], strict, wrappers, findings, stats);
}
std::map<std::string, int> byKind;
std::map<std::string, bool> flaggedFiles;
for (const auto &f : findings) {
flaggedFiles[f.file] = true;
out << f.file << ":" << f.line << ": <" << f.tag << ">"
<< (f.tag == "sql" ? "" : " (wraps sql)") << " pastes ";
for (size_t i = 0; i < f.refs.size(); ++i) {
out << (i ? ", " : "") << f.refs[i].text << " (" << f.refs[i].kind << ")";
++byKind[f.refs[i].kind];
}
out << "\n";
}
out << "lint-sql: " << stats.flaggedBlocks << " of " << stats.sqlBlocks
<< " <sql> blocks" << (wrappers.empty() ? "" : " (and uses of tags that wrap <sql>)")
<< " paste values into the statement, in " << flaggedFiles.size()
<< " of " << stats.files << " files";
if (!byKind.empty()) {
out << " (";
bool first = true;
for (auto &[kind, n] : byKind) { out << (first ? "" : ", ") << kind << " " << n; first = false; }
out << ")";
}
out << std::endl;
if (error) return 2;
return findings.empty() ? 0 : 1;
}
}
+57
View File
@@ -0,0 +1,57 @@
#ifndef __JetLint_h__
#define __JetLint_h__
#include <string>
#include <vector>
#include <ostream>
// jetc --lint-sql: phase 2 of docs/design-sql-bound-parameters.md.
//
// Lists every <sql> whose body pastes a variable into the statement text
// ($[...] or #[...]) instead of passing it with <bind>. These are the
// queries to migrate. A value from a row of an earlier query
// ($[.column], $[session.column], $[?N], $[#]) is not reported, as the
// design doc specifies, unless strict is set.
namespace jetc {
struct LintRef {
std::string text; // the reference as written, e.g. "$[:email]"
std::string kind; // cgi, global, local, session, env, keyword, row, ...
};
struct LintFinding {
std::string file;
int line; // line of the <sql tag
std::string tag; // "sql", or a custom tag that wraps <sql><container></sql>
std::vector<LintRef> refs;
};
struct LintStats {
int files = 0; // files that contain at least one <sql>
int sqlBlocks = 0;
int flaggedBlocks = 0;
};
// Scans one file's text. Appends to findings and stats.
// wrappers: custom tag names whose uses count as <sql> (see
// findSqlWrappers).
void lintSqlText(const std::string &file, const std::string &text, bool strict,
const std::vector<std::string> &wrappers,
std::vector<LintFinding> &findings, LintStats &stats);
// Adds to wrappers each custom tag defined in text (<tag name="X">)
// whose definition runs the caller's content as its statement:
// <sql ...><container></sql>.
void findSqlWrappers(const std::string &text, std::vector<std::string> &wrappers);
// Scans files and directories (recursively; every regular file,
// whatever its extension). Tag definitions are collected from all of
// them first, so a wrapper defined in one file is found in all.
// Prints one line per finding and a summary. Returns 0 when nothing is found, 1 when something is,
// 2 on an error (unreadable path).
int lintSql(const std::vector<std::string> &paths, bool strict, std::ostream &out, std::ostream &err);
}
#endif
+5
View File
@@ -83,6 +83,11 @@ namespace jetc {
// otherwise), it was previously miscategorized as void.
"set", "include", "cookie", "header", "read", "write",
"call", "system", "dump",
// <bind> (see __bind.cpp) supplies one <sql> placeholder value
// and never has a closing tag - without this a bare
// <bind value="..."> outside a <sql> span would scan forward
// for a "</bind>" that doesn't exist.
"bind",
// <container> (see parseContainerSlot/Tag::renderContainer) -
// real content always writes it as a bare marker with no
// separate closing tag, even when it carries its own
+1 -1
View File
@@ -21,7 +21,7 @@ OUTNAME="$2"
if [ ! -x "$HERE/jetc" ]; then
echo "Building jetc..."
g++ -g -std=c++23 -o "$HERE/jetc" "$HERE/jetc.cpp" "$HERE/JetParser.cpp" "$HERE/JetCodegen.cpp"
g++ -g -std=c++23 -o "$HERE/jetc" "$HERE/jetc.cpp" "$HERE/JetParser.cpp" "$HERE/JetCodegen.cpp" "$HERE/JetLint.cpp"
fi
echo "Compiling $INPUT -> $OUTNAME.compiled.cpp"
+1 -1
View File
@@ -30,7 +30,7 @@ STEM="$(basename "$OUTPUT" .jtc)"
if [ ! -x "$HERE/jetc" ]; then
echo "Building jetc..."
g++ -g -std=c++23 -o "$HERE/jetc" "$HERE/jetc.cpp" "$HERE/JetParser.cpp" "$HERE/JetCodegen.cpp"
g++ -g -std=c++23 -o "$HERE/jetc" "$HERE/jetc.cpp" "$HERE/JetParser.cpp" "$HERE/JetCodegen.cpp" "$HERE/JetLint.cpp"
fi
echo "Compiling $INPUT -> $STEM.compiled.cpp (shared mode)"
+13 -2
View File
@@ -1,5 +1,6 @@
#include "JetParser.h"
#include "JetCodegen.h"
#include "JetLint.h"
#include <fstream>
#include <sstream>
#include <iostream>
@@ -26,17 +27,27 @@ namespace {
int main(int argc, char **argv) {
bool shared = false;
bool lintSql = false;
bool strict = false;
std::vector<std::string> pos;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
if (a == "--shared") shared = true;
else if (a == "--lint-sql") lintSql = true;
else if (a == "--strict") strict = true;
else pos.push_back(a);
}
if (pos.size() < 2) {
if (lintSql && !pos.empty())
return jetc::lintSql(pos, strict, std::cout, std::cerr);
if (pos.size() < 2 || lintSql || strict) {
std::cerr << "usage: jetc [--shared] <input.jet> <output.cpp>" << std::endl;
std::cerr << " jetc --lint-sql [--strict] <file|directory>..." << std::endl;
std::cerr << " --shared emit a dlsym()-able entry point (see build-shared.sh)" << std::endl;
std::cerr << " instead of a standalone main()." << std::endl;
return 1;
std::cerr << " --lint-sql list every <sql> that pastes a variable into the statement" << std::endl;
std::cerr << " instead of using <bind> (exit 1 if any, 0 if none)." << std::endl;
std::cerr << " --strict with --lint-sql, also report row values ($[.column] etc.)." << std::endl;
return lintSql ? 2 : 1;
}
const std::string &inputPath = pos[0];
const std::string &outputPath = pos[1];
+128
View File
@@ -0,0 +1,128 @@
# Generates tests/testbind.jet and tests/testbind.expected (the .jet holds raw
# 0xBF and NUL bytes, so edit this rather than the .jet). Run from tests/:
# python3 gentestbind.py testbind.jet testbind.expected
import sys
out_jet, out_exp = sys.argv[1], sys.argv[2]
# (label, raw bytes, attribute quote)
values = [
("plain", b"hello", '"'),
("or-injection", b"x' or '1'='1", '"'),
("backslash-quote", b"\\'", '"'),
# A jet attribute can't end in a backslash (CoreUtils getTokenExclude
# reads it as escaping the closing quote), so this one is built in SQL.
("trailing-backslash", b"a\\", "concat('a', char(92))"),
("dashdash", b"-- ", '"'),
("semicolon", b"; drop table t; --", '"'),
("gbk-bf27", b"\xbf' or 1=1 -- ", '"'),
("double-quote", b'say "hi"', "'"),
("question", b"what?", '"'),
("nul", b"a\x00b", '"'),
("utf8", "héllo – ✓ 🎹".encode(), '"'),
]
J = []
E = []
w = J.append
w(b'#!../jet-2.0\n')
w(b'<jet filterblanklines="true" trimlines="true">\n')
w(b'<comment>\n'
b' End-to-end tests for <sql>/<bind> - see docs/design-sql-bound-parameters.md.\n'
b' Run by tests/runbindtests.sh against a real MySQL server; only TEMPORARY\n'
b' tables are used, so nothing outlives the connection. Compared byte-for-byte\n'
b' with tests/testbind.expected. Generated - contains raw 0xBF and NUL bytes.\n'
b'</comment>\n')
w(b'<mysql host="$[&JETTEST_DB_HOST]" database="$[&JETTEST_DB_NAME]" user="$[&JETTEST_DB_USER]" password="$[&JETTEST_DB_PASSWORD]">\n')
w(b'<sql>create temporary table bindtest (id int auto_increment primary key, s varbinary(255), n int, dec_v decimal(10,2), d date, dt datetime, b tinyint, t varchar(100) character set utf8mb4)</sql>\n')
def section(name, mode):
for label, raw, q in values:
if len(q) > 1:
w(b'<sql>select ' + q.encode() + b' as v</sql><ifrow><set name="v" value="$[.v]"></ifrow>\n')
else:
qb = q.encode()
w(b'<set name="v" value=' + qb + raw + qb + b'>\n')
w(b'<sql>insert into bindtest (s) values (?)<bind value="$[v]"></sql>\n')
w(b'<sql>select hex(s) as h from bindtest where id=last_insert_id()</sql>\n')
w(('%s %s: <ifrow>$[.h]</ifrow>\n' % (mode, label)).encode())
E.append('%s %s: %s' % (mode, label, raw.hex().upper()))
w(b'<comment> Injection strings and odd bytes come back byte-for-byte. </comment>\n')
section("roundtrip", "default")
w(b'<sql>set session sql_mode = concat(@@sql_mode, \',NO_BACKSLASH_ESCAPES\')</sql>\n')
section("roundtrip", "nbe")
w(b'<sql>set session sql_mode = replace(@@sql_mode, \'NO_BACKSLASH_ESCAPES\', \'\')</sql>\n')
tail = r'''<comment> Every type. </comment>
<set name="num" value="42">
<sql>insert into bindtest (n, dec_v, d, dt, b, t) values (?, ?, ?, ?, ?, ?)
<bind value="$[num]" type="int">
<bind value="-12.50" type="decimal">
<bind value="2026-10-23" type="date">
<bind value="2026-10-23 14:05" type="datetime">
<bind value="yes" type="bool">
<bind value="" null="empty">
</sql>
<sql>select n, dec_v, d, dt, b, t is null as tnull from bindtest where id=last_insert_id()</sql>
types: <ifrow>$[.n] $[.dec_v] $[.d] $[.dt] $[.b] $[.tnull]</ifrow>
<comment> ? inside literals, identifiers and comments is left alone. </comment>
<sql>select '?' as a, "?" as `b?`, ? as c /* ? */ -- ?
<bind value="bound">
</sql>
literals: <ifrow>$[.a] $[.b?] $[.c]</ifrow>
<comment> A query with no bind runs unchanged, even with a literal ?. </comment>
<sql>select concat('what', '?') as q</sql>
nobind: <ifrow>$[.q]</ifrow>
<comment> bind inside if inside sql. </comment>
<set name="flag" value="1">
<sql>select ? as x
<if value1="$[flag]" value2="1" type="eq"><bind value="from-if"></if>
</sql>
nested: <ifrow>$[.x]</ifrow>
<comment> ident with allow, order by. </comment>
<sql>insert into bindtest (n) values (5), (3), (9)</sql>
<set name="sort" value="N">
<set name="dir" value="desc">
<sql>select n from bindtest where n in (?, ?, ?) order by ? ?
<bind value="3" type="int"><bind value="5" type="int"><bind value="9" type="int">
<bind value="$[sort]" type="ident" allow="n,s">
<bind value="$[dir]" type="ident" allow="ASC,DESC">
</sql>
ident: <whilerow name="r">$[.n] </whilerow>
<comment> Result access on a bound query: whilerow, column names and counts. </comment>
<sql>select n, s from bindtest where n > ? order by n<bind value="4" type="int"></sql>
rows: $[.#] columns: $[.?#] first column: $[.?1] second column: $[.?2]
<comment> Errors - all catchable, none echo the value. </comment>
<try><sql>select ?, ?, ?<bind value="a"><bind value="b"></sql><catch name="err">mismatch: $[err]</try>
<try><sql>select ?<bind value="1 or 1=1" type="int"></sql><catch name="err">badint: $[err]</try>
<try><sql>select ?<bind value="s3cret" type="date"></sql><catch name="err">baddate: $[err]</try>
<try><sql>select ? from bindtest<bind value="password" type="ident" allow="n,s"></sql><catch name="err">badident: $[err]</try>
<try><bind value="x"><catch name="err">outside: $[err]</try>
<try><sql>select 1<bind></sql><catch name="err">novalue: $[err]</try>
<try><sql>select ?<bind value="x" type="blob"></sql><catch name="err">badtype: $[err]</try>
<try><sql>SET NAMES latin1</sql><catch name="err">setnames: $[err]</try>
<try><sql>set character_set_client = gbk</sql><catch name="err">setcharset: $[err]</try>
<sql>select @@character_set_client as cs</sql>
charset: <ifrow>$[.cs]</ifrow>
</mysql>
</jet>
'''
w(tail.encode())
E += [
"types: 42 -12.50 2026-10-23 2026-10-23 14:05:00 1 1",
"literals: ? ? bound",
"nobind: what?",
"nested: from-if",
"ident: 9 5 3",
"rows: 3 columns: 2 first column: n second column: s",
"mismatch: sql: 3 placeholders but 2 bind values",
"badint: bind 1: value is not a valid int.",
"baddate: bind 1: value is not a valid date (YYYY-MM-DD).",
"badident: bind 1: value is not in the allow list.",
"outside: bind must be inside sql.",
"novalue: bind must have a value.",
'badtype: bind 1: unknown type "blob".',
"setnames: sql: changing the connection character set is not allowed.",
"setcharset: sql: changing the connection character set is not allowed.",
"charset: utf8mb4",
]
open(out_jet, "wb").write(b"".join(J))
open(out_exp, "w").write("\n".join(E) + "\n")
+1
View File
@@ -0,0 +1 @@
lint-sql: 0 of 1 <sql> blocks paste values into the statement, in 0 of 1 files
+1
View File
@@ -0,0 +1 @@
<sql>select * from t where id=?<bind value="$[id]" type="int"></sql>
+2
View File
@@ -0,0 +1,2 @@
jetc: cannot open no-such-dir
lint-sql: 0 of 1 <sql> blocks paste values into the statement, in 0 of 1 files
+6
View File
@@ -0,0 +1,6 @@
site/kinds.page:1: <sql> pastes $[plain] (global), $[:form] (cgi), $[@sess] (session)
site/kinds.page:2: <sql> pastes $[&HTTP_HOST] (env), $[%kw] (keyword), $[!g] (global), #[loc] (local)
site/kinds.page:3: <sql> pastes $[late] (global)
site/kinds.page:6: <sql> pastes $[name$[ix]] (global)
site/uses.page:1: <showtable> (wraps sql) pastes $[_login_id] (global)
lint-sql: 5 of 11 <sql> blocks (and uses of tags that wrap <sql>) paste values into the statement, in 2 of 4 files (cgi 1, env 1, global 5, keyword 1, local 1, session 1)
+1
View File
@@ -0,0 +1 @@
<sql>select $[hidden]</sql>
+6
View File
@@ -0,0 +1,6 @@
<sql>select * from t where a='$[plain]' and b=$[:form] and c='$[@sess]'</sql>
<sql>select '$[&HTTP_HOST]', '$[%kw]', '$[!g]', '#[loc]'</sql>
<SQL sessionid="#[sid]">select 1
from t
where x=$[late] and y=$[late]</SQL>
<sql>select * from a where k=$[name$[ix]]</sql>
+1
View File
@@ -0,0 +1 @@
no queries here $[x]
+11
View File
@@ -0,0 +1,11 @@
<sql>select $[.col], $[projman.col], $[?1], $[#], $[?#] from t</sql>
<sql>select * from t where a=? and b=?
<bind value="$[email]">
<if value1="$[x]" value2="1"><bind value="$[y]" type="int"></if>
<set name="z" value="$[z]">
<comment> uses $[nothing] </comment>
</sql>
<sql>select '|>$[not_parsed]<|'</sql>
<sql sessionid="x"/>
<sqlx>$[not_sql]</sqlx>
$[outside_sql]
+4
View File
@@ -0,0 +1,4 @@
<tag name="showTable" keywords="sessionid">
<sql sessionid="#[sessionid]"><container></sql>
</tag>
<tag name="plain"><b><container></b></tag>
+3
View File
@@ -0,0 +1,3 @@
<showtable sessionid="1">select * from t where u=$[_login_id]</showtable>
<showtable>select * from t where u=$[.id]</showtable>
<plain>$[not_sql]</plain>
+8
View File
@@ -0,0 +1,8 @@
site/kinds.page:1: <sql> pastes $[plain] (global), $[:form] (cgi), $[@sess] (session)
site/kinds.page:2: <sql> pastes $[&HTTP_HOST] (env), $[%kw] (keyword), $[!g] (global), #[loc] (local)
site/kinds.page:3: <sql> pastes $[late] (global)
site/kinds.page:6: <sql> pastes $[name$[ix]] (global)
site/safe.page:1: <sql> pastes $[.col] (row), $[projman.col] (row), $[?1] (row), $[#] (row), $[?#] (row)
site/uses.page:1: <showtable> (wraps sql) pastes $[_login_id] (global)
site/uses.page:2: <showtable> (wraps sql) pastes $[.id] (row)
lint-sql: 7 of 11 <sql> blocks (and uses of tags that wrap <sql>) paste values into the statement, in 3 of 4 files (cgi 1, env 1, global 5, keyword 1, local 1, row 6, session 1)
+74
View File
@@ -0,0 +1,74 @@
#!/bin/bash
# Tests for <sql>/<bind> (docs/design-sql-bound-parameters.md, phase 1):
# 1. tests/sqlbind_test.cpp - unit tests for SqlBind.cpp (no MySQL needed)
# 2. tests/testbind.jet - end to end through jet-2.0 against a real MySQL
# server (TEMPORARY tables only), compared with
# tests/testbind.expected
# 3. jetc - <bind> is void in the compiler too, and a
# compiled page runs the same <sql>/<bind> code
#
# Build jet-2.0 first (./compile). The MySQL part needs:
# JETTEST_DB_USER, JETTEST_DB_PASSWORD (required, or it is skipped)
# JETTEST_DB_HOST (default localhost), JETTEST_DB_NAME (default test)
set -u
T="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JC="$(cd "$T/.." && pwd)"
CU="$JC/../CoreUtils"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
fail=0
echo "== unit tests (SqlBind) =="
g++ -g -std=c++23 -I"$CU" -I"$JC" "$T/sqlbind_test.cpp" "$JC/SqlBind.cpp" -L"$CU" -lCoreUtils -o "$WORK/sqlbind_test" || exit 1
"$WORK/sqlbind_test" || fail=1
echo "== end to end (jet-2.0 + MySQL) =="
if [ -z "${JETTEST_DB_USER:-}" ] || [ -z "${JETTEST_DB_PASSWORD:-}" ]; then
echo "SKIPPED: set JETTEST_DB_USER and JETTEST_DB_PASSWORD"
else
export JETTEST_DB_HOST="${JETTEST_DB_HOST:-localhost}" JETTEST_DB_NAME="${JETTEST_DB_NAME:-test}"
(cd "$T" && "$JC/jet-2.0" testbind.jet) > "$WORK/testbind.out" 2>&1
if diff -u "$T/testbind.expected" "$WORK/testbind.out"; then
echo "PASS ($(wc -l < "$T/testbind.expected") lines match)"
else
echo "FAIL"; fail=1
fi
fi
echo "== jetc =="
g++ -g -std=c++23 -o "$WORK/jetc" "$JC/jetc/jetc.cpp" "$JC/jetc/JetParser.cpp" "$JC/jetc/JetCodegen.cpp" "$JC/jetc/JetLint.cpp" || exit 1
# A bare <bind> must not swallow the content after it looking for </bind>.
printf 'A<sql>select ?<bind value="$[x]"></sql>B<bind value="y">C\n' > "$WORK/void.jet"
"$WORK/jetc" "$WORK/void.jet" "$WORK/void.cpp" >/dev/null || fail=1
if grep -q '<sql>select ?<bind value=\\"$\[x\]\\"></sql>' "$WORK/void.cpp" &&
grep -q '"<bind value=\\"y\\">"' "$WORK/void.cpp" &&
grep -q '"C\\n"' "$WORK/void.cpp"; then
echo "PASS (bind is void; sql span intact)"
else
echo "FAIL: unexpected codegen for bind"; grep -n 'interpretSpan\|out.write' "$WORK/void.cpp"; fail=1
fi
if [ -n "${JETTEST_DB_USER:-}" ] && [ -n "${JETTEST_DB_PASSWORD:-}" ]; then
# The whole end-to-end test again, compiled by jetc instead of interpreted.
# Drop the #! line, and the newline after </jet> (the interpreter stops
# at </jet>; a compiled page would emit it as text).
tail -n +2 "$T/testbind.jet" | head -c -1 > "$WORK/compiled.jet"
"$WORK/jetc" "$WORK/compiled.jet" "$WORK/compiled.cpp" >/dev/null || fail=1
objs=""
for f in "$JC"/*.cpp; do
[ "$(basename "$f")" = "jet-2.0.cpp" ] && continue
o="$WORK/$(basename "${f%.cpp}").o"
g++ -g -c -std=c++23 -I"$CU" -I"$JC" "$f" -o "$o" &
objs="$objs $o"
done
wait
g++ -g -std=c++23 -I"$CU" -I"$JC" "$WORK/compiled.cpp" $objs -L"$CU" -lCoreUtils -lmysqlclient -lssl -lcrypto -o "$WORK/compiled" || exit 1
(cd "$T" && "$WORK/compiled") > "$WORK/compiled.out" 2>&1
if diff -u "$T/testbind.expected" "$WORK/compiled.out"; then
echo "PASS (compiled page output matches)"
else
echo "FAIL (compiled page)"; fail=1
fi
fi
[ $fail = 0 ] && echo "ALL PASSED" || echo "FAILURES"
exit $fail
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
# Tests for jetc --lint-sql (docs/design-sql-bound-parameters.md, phase 2).
# Runs the lint over tests/lintsql/ and compares with the .expected files.
# Needs no database.
set -u
T="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JC="$(cd "$T/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
fail=0
g++ -g -std=c++23 -o "$WORK/jetc" "$JC/jetc/jetc.cpp" "$JC/jetc/JetParser.cpp" "$JC/jetc/JetCodegen.cpp" "$JC/jetc/JetLint.cpp" || exit 1
# check NAME EXPECTED_EXIT ARGS... - output is compared with lintsql/NAME.expected
check() {
local name="$1" want="$2"; shift 2
(cd "$T/lintsql" && "$WORK/jetc" --lint-sql "$@") > "$WORK/$name.out" 2>&1
local got=$?
if [ "$got" != "$want" ]; then
echo "FAIL $name: exit $got, expected $want"; fail=1
elif ! diff -u "$T/lintsql/$name.expected" "$WORK/$name.out"; then
echo "FAIL $name: output differs"; fail=1
else
echo "PASS $name"
fi
}
check site 1 site
check strict 1 --strict site
check clean 0 clean
check missing 2 clean no-such-dir
[ $fail = 0 ] && echo "ALL PASSED" || echo "FAILURES"
exit $fail
+146
View File
@@ -0,0 +1,146 @@
// Unit tests for SqlBind (the MySQL-free part of <sql>/<bind>) -
// see docs/design-sql-bound-parameters.md section 10.
// Built and run by tests/runbindtests.sh.
#include "SqlBind.h"
#include "Exception.h"
#include <iostream>
#include <string>
#include <vector>
using namespace jet;
static int failures = 0, passes = 0;
#define CHECK(cond) do { if(cond) ++passes; else { ++failures; std::cout << "FAIL line " << __LINE__ << ": " #cond << std::endl; } } while(0)
// A stand-in escaper (the real one is mysql_real_escape_string_quote).
static std::string esc(const std::string &s) {
std::string o;
for(char c : s) { if(c == '\'' || c == '\\') o += '\\'; o += c; }
return o;
}
static BoundValue bv(const std::string &value, const std::string &type = "", const std::string &nullMode = "",
bool hasAllow = false, const std::string &allow = "") {
return makeBoundValue(value, type, nullMode, hasAllow, allow, 1);
}
static bool throws(const std::string &value, const std::string &type, const std::string &nullMode = "",
bool hasAllow = false, const std::string &allow = "", std::string *msg = nullptr) {
try { bv(value, type, nullMode, hasAllow, allow); }
catch(coreutils::Exception &e) { if(msg) *msg = e.text; return true; }
return false;
}
static std::string bind(const std::string &q, std::vector<BoundValue> v, bool nbe = false) {
return bindPlaceholders(q, v, nbe, esc);
}
int main() {
// --- types: valid values ---
CHECK(bv("abc").kind == BoundValue::QUOTED && bv("abc").text == "abc");
CHECK(bv("abc", "string").kind == BoundValue::QUOTED);
CHECK(bv("", "string").kind == BoundValue::QUOTED && bv("").text == "");
CHECK(bv("42", "int").kind == BoundValue::BARE && bv("42", "int").text == "42");
CHECK(bv("-7", "INT").text == "-7");
CHECK(bv("1234567890123456789", "int").text == "1234567890123456789");
CHECK(bv("3.14", "decimal").text == "3.14");
CHECK(bv("-10", "decimal").text == "-10");
for(auto t : {"1", "true", "TRUE", "yes", "Yes"}) CHECK(bv(t, "bool").text == "1");
for(auto f : {"0", "false", "no", "NO"}) CHECK(bv(f, "bool").text == "0");
CHECK(bv("2026-10-23", "date").kind == BoundValue::QUOTED);
CHECK(bv("2026-10-23 14:05", "datetime").kind == BoundValue::QUOTED);
CHECK(bv("2026-10-23 23:59:59", "datetime").text == "2026-10-23 23:59:59");
CHECK(bv("price", "ident", "", true, "name, price ,created").text == "`price`");
CHECK(bv("PRICE", "ident", "", true, "name,price").text == "`price`"); // allow list spelling wins
CHECK(bv("desc", "ident", "", true, "ASC,DESC").text == "DESC");
CHECK(bv("asc", "ident", "", true, "ASC,DESC").kind == BoundValue::BARE);
CHECK(bv("we`ird", "ident", "", true, "we`ird").text == "`we``ird`");
// --- null="empty" ---
CHECK(bv("", "string", "empty").kind == BoundValue::SQLNULL);
CHECK(bv("", "int", "empty").kind == BoundValue::SQLNULL);
CHECK(bv("5", "int", "empty").text == "5");
CHECK(bv("x", "", "EMPTY").kind == BoundValue::QUOTED);
// --- types: invalid values throw ---
for(auto v : {"", "1 or 1=1", "1.5", "abc", "12345678901234567890", "-", " 1", "0x10", "1e5"})
CHECK(throws(v, "int"));
for(auto v : {"", "1.", ".5", "1.2.3", "1,5", "1;drop"}) CHECK(throws(v, "decimal"));
for(auto v : {"", "2", "on", "y"}) CHECK(throws(v, "bool"));
for(auto v : {"", "2026-13-01", "2026-00-10", "2026-01-32", "26-01-01", "2026/01/01", "2026-01-01'"})
CHECK(throws(v, "date"));
for(auto v : {"2026-01-01", "2026-01-01 24:00", "2026-01-01 12:60", "2026-01-01T12:00", "2026-01-01 12:00:61"})
CHECK(throws(v, "datetime"));
CHECK(throws("name; drop table x", "ident", "", true, "name,price"));
CHECK(throws("price", "ident")); // ident needs allow
CHECK(throws("x", "string", "", true, "x")); // allow only with ident
CHECK(throws("x", "blob")); // unknown type
CHECK(throws("x", "string", "always")); // bad null mode
CHECK(throws("", "int")); // empty is not an int without null="empty"
// error text never includes the value (it may be a password)
{
std::string msg;
CHECK(throws("s3cret-pw", "int", "", false, "", &msg));
CHECK(msg.find("s3cret-pw") == std::string::npos);
CHECK(msg.find("bind 1") != std::string::npos);
CHECK(throws("s3cret-pw", "ident", "", true, "a,b", &msg));
CHECK(msg.find("s3cret-pw") == std::string::npos);
}
// --- placeholder scanning: replaced in order ---
CHECK(bind("select ? , ?", {bv("a"), bv("1", "int")}) == "select 'a' , 1");
CHECK(bind("x=?", {bv("", "", "empty")}) == "x=NULL");
CHECK(bind("where email=? and status='ACTIVE'", {bv("x' or '1'='1")}) ==
"where email='x\\' or \\'1\\'=\\'1' and status='ACTIVE'");
// replacement text is never rescanned
CHECK(bind("a=? and b=?", {bv("?"), bv("?" "?")}) == "a='?' and b='?" "?'");
// --- ? inside literals, identifiers and comments is never replaced ---
CHECK(countPlaceholders("select '?', \"?\", `?` from t", false) == 0);
CHECK(countPlaceholders("select 1 -- ?\n, ?", false) == 1);
CHECK(countPlaceholders("select 1 # ?\n, ?", false) == 1);
CHECK(countPlaceholders("select /* ? */ ?", false) == 1);
CHECK(countPlaceholders("select /* ? \n ? */ 1", false) == 0);
CHECK(countPlaceholders("select 1--?", false) == 1); // "--" not followed by space is not a comment
CHECK(countPlaceholders("select 'it''s ?' , ?", false) == 1);
CHECK(countPlaceholders("select \"say \"\"?\"\"\" , ?", false) == 1);
CHECK(countPlaceholders("select `a``?` , ?", false) == 1);
CHECK(countPlaceholders("select 'a\\'?' , ?", false) == 1); // \' escapes the quote
// with NO_BACKSLASH_ESCAPES, 'a\' is a complete literal, so both ? count
CHECK(countPlaceholders("select 'a\\', ? , ?", true) == 2);
CHECK(countPlaceholders("select 'a\\', ? , ?", false) == 0);
CHECK(countPlaceholders("select ?", false) == 1);
CHECK(countPlaceholders("", false) == 0);
// --- count mismatch throws ---
{
bool threw = false;
try { bind("select ?, ?, ?", {bv("a"), bv("b")}); }
catch(coreutils::Exception &e) { threw = true; CHECK(e.text == "sql: 3 placeholders but 2 bind values"); }
CHECK(threw);
threw = false;
try { bind("select '?'", {bv("a")}); } catch(coreutils::Exception &) { threw = true; }
CHECK(threw);
}
// --- charset changes are refused ---
CHECK(isCharsetChange("SET NAMES latin1"));
CHECK(isCharsetChange(" set names 'gbk'"));
CHECK(isCharsetChange("/* x */ SET CHARACTER SET gbk"));
CHECK(isCharsetChange("set charset gbk"));
CHECK(isCharsetChange("set @a=1, names gbk"));
CHECK(isCharsetChange("set character_set_client = gbk"));
CHECK(isCharsetChange("SET @@session.character_set_connection=gbk"));
CHECK(isCharsetChange("set collation_connection = 'gbk_bin'"));
CHECK(!isCharsetChange("select names from t"));
CHECK(!isCharsetChange("update t set names='x'"));
CHECK(!isCharsetChange("set @names = 'names'"));
CHECK(!isCharsetChange("set session sql_mode = 'NO_BACKSLASH_ESCAPES'"));
CHECK(!isCharsetChange("set @x = 'set names gbk'"));
std::cout << passes << " passed, " << failures << " failed" << std::endl;
return failures == 0 ? 0 : 1;
}
+38
View File
@@ -0,0 +1,38 @@
default plain: 68656C6C6F
default or-injection: 7827206F72202731273D2731
default backslash-quote: 5C27
default trailing-backslash: 615C
default dashdash: 2D2D20
default semicolon: 3B2064726F70207461626C6520743B202D2D
default gbk-bf27: BF27206F7220313D31202D2D20
default double-quote: 7361792022686922
default question: 776861743F
default nul: 610062
default utf8: 68C3A96C6C6F20E2809320E29C9320F09F8EB9
nbe plain: 68656C6C6F
nbe or-injection: 7827206F72202731273D2731
nbe backslash-quote: 5C27
nbe trailing-backslash: 615C
nbe dashdash: 2D2D20
nbe semicolon: 3B2064726F70207461626C6520743B202D2D
nbe gbk-bf27: BF27206F7220313D31202D2D20
nbe double-quote: 7361792022686922
nbe question: 776861743F
nbe nul: 610062
nbe utf8: 68C3A96C6C6F20E2809320E29C9320F09F8EB9
types: 42 -12.50 2026-10-23 2026-10-23 14:05:00 1 1
literals: ? ? bound
nobind: what?
nested: from-if
ident: 9 5 3
rows: 3 columns: 2 first column: n second column: s
mismatch: sql: 3 placeholders but 2 bind values
badint: bind 1: value is not a valid int.
baddate: bind 1: value is not a valid date (YYYY-MM-DD).
badident: bind 1: value is not in the allow list.
outside: bind must be inside sql.
novalue: bind must have a value.
badtype: bind 1: unknown type "blob".
setnames: sql: changing the connection character set is not allowed.
setcharset: sql: changing the connection character set is not allowed.
charset: utf8mb4
Binary file not shown.