Skip to contentSkip to conversation

parser_json: support handle for rule positioning in JSON add rule

PATCH In review Alexandre Knecht 2 participants 4 messages Nov 6, 2025 – Nov 13, 2025 netfilter

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 parser_json: support handle for rule positioning in JSON add rule

This patch enables handle-based rule positioning for JSON commands by distinguishing between explicit and implicit "add" operations:

- Explicit commands ({"add": {"rule": ...}}) route through json_parse_cmd_replace, which converts the handle field to position, enabling rules to be inserted at specific locations
- Implicit commands ({"rule": ...} from export/import) continue using json_parse_cmd_add, which ignores handles for backward compatibility

The semantics are:
ADD with handle: inserts rule AFTER the specified handle
INSERT with handle: inserts rule BEFORE the specified handle

This maintains export/import compatibility while enabling programmatic rule positioning via the JSON API.

Includes comprehensive test cases covering:
- Multiple additions at the same handle position
- INSERT before handle
- Error handling for deleted handles
- Export/import compatibility (implicit adds ignore handles)

---
 src/parser_json.c                             |   7 +-
 .../0008rule_add_position_comprehensive_0     | 135 ++++++++++++++++++
 2 files changed, 139 insertions(+), 3 deletions(-)
 create mode 100755 tests/shell/testcases/json/0008rule_add_position_comprehensive_0
src/parser_json.c +4 -3
index 7b4f3384..b9b3bef0 100644
@@ -4045,7 +4045,8 @@ static struct cmd *json_parse_cmd_replace(struct json_ctx *ctx,
 		return NULL;
 	}
 
-	if ((op == CMD_INSERT || op == CMD_ADD) && h.handle.id) {
+	if (h.handle.id &&
+	    (op == CMD_INSERT || op == CMD_ADD || op == CMD_CREATE)) {
 		h.position.id = h.handle.id;
 		h.handle.id = 0;
 	}
@@ -4328,9 +4329,9 @@ static struct cmd *json_parse_cmd(struct json_ctx *ctx, json_t *root)
 		enum cmd_ops op;
 		struct cmd *(*cb)(struct json_ctx *ctx, json_t *, enum cmd_ops);
 	} parse_cb_table[] = {
-		{ "add", CMD_ADD, json_parse_cmd_add },
+		{ "add", CMD_ADD, json_parse_cmd_replace },
 		{ "replace", CMD_REPLACE, json_parse_cmd_replace },
-		{ "create", CMD_CREATE, json_parse_cmd_add },
+		{ "create", CMD_CREATE, json_parse_cmd_replace },
 		{ "insert", CMD_INSERT, json_parse_cmd_replace },
 		{ "delete", CMD_DELETE, json_parse_cmd_add },
 		{ "list", CMD_LIST, json_parse_cmd_list },
tests/shell/testcases/json/0008rule_add_position_comprehensive_0 new file +135 -0

135 lines not on this page · raw message

Signature · 1 line
2.51.0
reviewer
#1 lore raw
Quoted 14 lines · Alexandre Knecht

This patch enables handle-based rule positioning for JSON commands by distinguishing between explicit and implicit "add" operations:

- Explicit commands ({"add": {"rule": ...}}) route through json_parse_cmd_replace, which converts the handle field to position, enabling rules to be inserted at specific locations
- Implicit commands ({"rule": ...} from export/import) continue using json_parse_cmd_add, which ignores handles for backward compatibility

The semantics are:
ADD with handle: inserts rule AFTER the specified handle
INSERT with handle: inserts rule BEFORE the specified handle

Quoted 9 lines

This maintains export/import compatibility while enabling programmatic rule positioning via the JSON API.

Includes comprehensive test cases covering:
- Multiple additions at the same handle position
- INSERT before handle
- Error handling for deleted handles
- Export/import compatibility (implicit adds ignore handles)

Fixes fb557b5546084 ("JSON: Sort out rule position and handles in general")
Quoted 26 lines
---
 src/parser_json.c                             |   7 +-
 .../0008rule_add_position_comprehensive_0     | 135 ++++++++++++++++++
 2 files changed, 139 insertions(+), 3 deletions(-)
 create mode 100755 tests/shell/testcases/json/0008rule_add_position_comprehensive_0
src/parser_json.c +2 -1
index 7b4f3384..b9b3bef0 100644
@@ -4045,7 +4045,8 @@ static struct cmd *json_parse_cmd_replace(struct json_ctx *ctx,
 		return NULL;
 	}
 
-	if ((op == CMD_INSERT || op == CMD_ADD) && h.handle.id) {
+	if (h.handle.id &&
+	    (op == CMD_INSERT || op == CMD_ADD || op == CMD_CREATE)) {
 		h.position.id = h.handle.id;
 		h.handle.id = 0;
 	}
@@ -4328,9 +4329,9 @@ static struct cmd *json_parse_cmd(struct json_ctx *ctx, json_t *root)
 		enum cmd_ops op;

src/parser_json.c static struct cmd *json_parse_cmd(struct json_ctx *ctx, json_t *root) · line 4337

Quoted 10 lines
src/parser_json.c +2 -2
 		struct cmd *(*cb)(struct json_ctx *ctx, json_t *, enum cmd_ops);
 	} parse_cb_table[] = {
-		{ "add", CMD_ADD, json_parse_cmd_add },
+		{ "add", CMD_ADD, json_parse_cmd_replace },
 		{ "replace", CMD_REPLACE, json_parse_cmd_replace },
-		{ "create", CMD_CREATE, json_parse_cmd_add },
+		{ "create", CMD_CREATE, json_parse_cmd_replace },
 		{ "insert", CMD_INSERT, json_parse_cmd_replace },
 		{ "delete", CMD_DELETE, json_parse_cmd_add },
 		{ "list", CMD_LIST, json_parse_cmd_list },

Doesn't this break "add" and "create" for all ruleset items other than rules? Looks like the quick fix I suggested does not work at all, sorry.

Cheers, Phil

#2 lore raw

Hi Phil,

Before submitting v4 for JSON handle positioning, I wanted to share the design approach and get your feedback on whether it looks sound.

After your feedback on v3, I realized routing commands through json_parse_cmd_replace doesn't work for non-rule objects. I've taken a different approach that I believe addresses all the requirements cleanly.

# Design Overview

The core challenge is distinguishing between two formats that both call json_parse_cmd_add:

- Explicit format: {"add": {"rule": ...}} - handle should control positioning
- Implicit format: {"rule": ...} (export/import) - handle must be ignored for portability

Solution: Use a context flag (CTX_F_IMPLICIT) to mark implicit format.

## Implementation Details

1. New Context Flag

#define CTX_F_IMPLICIT (1 << 10) /* implicit add (export/import format) */

Why bit 10?
- Next sequential bit after CTX_F_COLLAPSED (bit 9)
- Follows existing flag numbering convention

Why a flag instead of a function parameter?
- Follows existing pattern (json_parse_flagged_expr at lines 1747-1754)
- Keeps function signatures unchanged (less invasive)
- Properly scoped and restored (no state leakage)
- Localized to parser_json.c (doesn't leak outside JSON parsing)

2. Set Flag in Implicit Fallback

At line 4373, where we handle implicit format:

/* to accept 'list ruleset' output 1:1, try add command */ {
uint32_t old_flags = ctx->flags;
struct cmd *cmd;

ctx->flags |= CTX_F_IMPLICIT;
cmd = json_parse_cmd_add(ctx, root, CMD_ADD);
ctx->flags = old_flags; // Restore after parsing

return cmd;
}

Design choice: Save and restore pattern ensures the flag doesn't leak to subsequent commands.

3. Check Flag in Rule Handler

In json_parse_cmd_add_rule at line 3211:

/* For explicit add/insert/create commands, handle is used for positioning.
* Convert handle to position for proper rule placement.
* Skip this for implicit adds (export/import format).
*/
if (!(ctx->flags & CTX_F_IMPLICIT) &&
!json_unpack(root, "{s:I}", "handle", &h.handle.id)) {
if (op == CMD_INSERT || op == CMD_ADD || op == CMD_CREATE) { h.position.id = h.handle.id;
h.handle.id = 0;
}
}

Why this location?
- Only affects rule objects (tables, chains, sets unaffected)
- Preserves existing command routing (no changes to dispatch table)
- Single check covers ADD, INSERT, and CREATE

4. Expression Flag Mask (Discovered Issue)

During testing, I discovered that setting CTX_F_IMPLICIT broke expression parsing with errors like:
Error: Expression type payload not allowed in context ()

Root cause: Expression validation at line 1732:
if ((cb_tbl[i].flags & ctx->flags) != ctx->flags) { json_error(ctx, "Expression type %s not allowed in context (%s)."); return NULL;
}

This check assumes ALL bits in ctx->flags are expression context flags. When CTX_F_IMPLICIT (a command-level flag) is set, the validation fails because expression callbacks don't include this flag in their allowed flags.

Solution: Introduce a mask to separate flag types:

/* Mask for flags that affect expression parsing context */ #define CTX_F_EXPR_MASK (CTX_F_RHS | CTX_F_STMT | CTX_F_PRIMARY | CTX_F_DTYPE | \
CTX_F_SET_RHS | CTX_F_MANGLE | CTX_F_SES | CTX_F_MAP | \
CTX_F_CONCAT)

Then filter before validation:
expr_flags = ctx->flags & CTX_F_EXPR_MASK; // Only expression flags if ((cb_tbl[i].flags & expr_flags) != expr_flags) {

Why this is necessary:
- Expression context flags (bits 0-8): control which expressions are allowed where
- Command-level flags (bits 9-10): control command processing, not expression validity
- The mask documents this separation clearly

Note: This is actually a latent issue that would also affect CTX_F_COLLAPSED if it ever remained set during expression parsing. Currently it doesn't because it's only set when returning early (line 3460).

## Performance Considerations

Flag check overhead:
- Single bitwise AND operation: ctx->flags & CTX_F_IMPLICIT
- Same cost as existing checks (CTX_F_RHS, CTX_F_STMT, etc.)
- No measurable performance impact

Memory:
- No additional allocations
- Single uint32_t flag bit

## Testing

Created two comprehensive tests:

Test 0007 (159 lines): All object types with all operations
- Covers: table, chain, rule, set, counter, quota
- Operations: add, insert, delete, replace, create
- Purpose: Ensure non-rule objects work correctly (addresses your v3 concern)

Test 0008 (83 lines): Handle positioning semantics
- ADD with handle → positions AFTER (verifies rule order)
- INSERT with handle → positions BEFORE (verifies rule order)
- Implicit format ignores handles (no error on non-existent handle)

Edge cases tested:
- Multiple rules at same handle position
- Mixed explicit/implicit in same JSON
- Complex expressions (payload, meta, ct) in implicit format
- Export/import round-trips
- Non-existent handles in implicit format (correctly ignored)

## Alternative Designs Considered

Option 1: Separate flag fields
struct json_ctx {
uint32_t expr_flags; // Expression context uint32_t command_flags; // Command processing
...
};
- Pros: Cleaner separation, no mask needed
- Cons: ~50 line refactoring, changes struct layout
- Decision: Too large for this feature, could be follow-up

Option 2: Pass boolean parameter
json_parse_cmd_add_rule(..., bool implicit)
- Pros: Very explicit
- Cons: Changes function signatures, needs threading through multiple layers
- Decision: More invasive than flag approach

Option 3: Use different CMD_OPS value
enum cmd_ops {
...
CMD_ADD_IMPLICIT,
};
- Pros: Type-safe distinction
- Cons: Mixing semantic (ADD) with format (implicit), affects all switch statements
- Decision: Implicit vs explicit is a parsing concern, not a command operation

Questions for Review

1. Flag approach: Does using CTX_F_IMPLICIT seem reasonable, or would you prefer one of the alternatives?
2. Expression mask: Is CTX_F_EXPR_MASK acceptable as a fix, or should I refactor to separate expr_flags and command_flags entirely?
3. Test coverage: Are tests 0007 and 0008 sufficient, or should I add more edge cases?

Ready to submit if design is approved !

I have the complete patch ready to send if this approach looks good to you.

Thanks for your time reviewing this!

Best regards,Alexandre

reviewer
#3 lore raw

Hi Alexandre,

Quoted 2 lines · Alexandre Knecht

Before submitting v4 for JSON handle positioning, I wanted to share the design approach and get your feedback on whether it looks sound.

Sorry for the late reply!

[...]

Quoted 6 lines

Questions for Review

1. Flag approach: Does using CTX_F_IMPLICIT seem reasonable, or would you prefer one of the alternatives?
2. Expression mask: Is CTX_F_EXPR_MASK acceptable as a fix, or should I refactor to separate expr_flags and command_flags entirely?

Yes, CTX_F_IMPLICIT is a good idea and CTX_F_EXPR_MASK the easiest option to avoid misinterpretation of the new flag bit.

Quoted 2 lines

3. Test coverage: Are tests 0007 and 0008 sufficient, or should I add more edge cases?

They seem more than enough to me. Extending tests to cover for newly discovered cases is also not a big deal, so no worries here.

Quoted 3 lines

Ready to submit if design is approved !

I have the complete patch ready to send if this approach looks good to you.

Cool, looking forward to your patch!

Thanks, Phil