We are tasked with constructing an intent-based network policy compiler for service meshes.
The system should have:
- DSL (Domain Specific Language) for expressing network policies in terms of high-level intents.
- Conflict detection: detect conflicts between policies (e.g., allow vs deny, overlapping rules with different actions).
- Rollout controls: ability to roll out policies in a controlled manner (e.g., canary, phased rollout, rollback).
- Verification: after compilation and deployment, verify that the policies are enforced as intended.
We'll design a system that compiles high-level intents (written in a DSL) into low-level network policies (e.g., for Istio, Linkerd, etc.) and also handles the above concerns.
Steps:
-
DSL Design:
- We need a DSL that allows users to specify intents such as:
- Service A can communicate with Service B on port X.
- All services in namespace X can communicate with services in namespace Y except on port Z.
- Deny all traffic from external sources.
- The DSL should be expressive enough to capture common network policy intents and be convertible to the target mesh's policy language.
-
Compiler:
- Parse the DSL and convert to an intermediate representation (IR) that captures the intent (source, destination, ports, protocols, action (allow/deny), etc.).
- The compiler will also consider the existing policies and the target mesh's capabilities.
-
Conflict Detection:
- Before deploying, we need to check for conflicts. Conflicts can arise when:
a) Two policies have overlapping selectors but different actions (allow vs deny) on the same traffic.
b) More specific rules being overridden by less specific ones (depending on the policy model, e.g., default deny vs default allow).
- We'll need a way to rank the specificity of rules (e.g., by the number of matching criteria) and then determine the effective action.
- We can use a conflict detection algorithm that, given a set of policies (both new and existing) and a set of test traffic scenarios, predicts the effective action.
-
Rollout Controls:
- We want to be able to roll out policies in a controlled way. This might involve:
- Canary: apply the policy to a subset of services first and monitor.
- Phased: roll out by namespace, by service, or by percentage of traffic.
- Rollback: if something goes wrong, revert to the previous set of policies.
- We need a way to stage the policies and then progressively apply them, and also a mechanism to rollback.
-
Verification:
- After applying the policies, we need to verify that the intended policy is in effect.
- This can be done by:
- Injecting test traffic and observing if it is allowed/blocked as expected.
- Querying the mesh's policy enforcement status (if available).
- We can have a testing framework that runs a set of test cases against the deployed policies.
Implementation Plan:
We'll break down the system into modules:
-
DSL Parser and IR Generator:
- Define the grammar for the DSL (maybe using ANTLR or a simple parser if the DSL is simple).
- Generate an IR that is independent of the target mesh.
-
Policy Compiler:
- Takes the IR and compiles it to the target mesh's policy format (e.g., Istio AuthorizationPolicy, NetworkPolicy, etc.).
- Also, the compiler must handle the target mesh's specific model (e.g., Istio's hierarchical evaluation).
-
Conflict Analyzer:
- Works on the IR (or the compiled policies) to detect conflicts.
- We can define a set of conflict rules and then check for any violations.
-
Rollout Manager:
- Manages the lifecycle of policy deployment: staging, canary, phased, rollback.
- Might interact with a deployment system (like Kubernetes) to apply policies in stages.
-
Verifier:
- Runs tests against the deployed policies. The tests can be defined in the DSL as well (or a separate test DSL) and then executed.
-
Repository/State Management:
- We need to keep track of the current state of policies (what is deployed) and the desired state (what we want to deploy).
- This is necessary for rollback and for conflict detection (to consider currently deployed policies).
Let's think about the workflow:
- User writes policies in the DSL.
- System parses and generates IR.
- Conflict detection: check the new IR against the current state (IR of deployed policies) and other new policies (if batch deploying).
- If conflicts are found, report and abort.
- If no conflicts, compile to target mesh policies.
- Rollout: apply the compiled policies according to the rollout plan (e.g., canary to 10% of services, then 50%, then all).
- After each rollout step, run verification tests (or at the end) to ensure correctness.
- If verification fails, rollback to previous state.
We need to design the DSL. Let's propose a simple one:
Example:
policy "frontend-to-backend" {
source: service frontend
destination: service backend
ports: [80, 443]
action: allow
}
policy "deny-external" {
source: external
destination: service *
action: deny
}
We can also have more complex selectors (by labels, namespaces, etc.).
Now, for conflict detection:
Let's consider two policies:
Policy A: allow from frontend to backend on port 80.
Policy B: deny from frontend to backend on port 80.
These are conflicting because for the same traffic (frontend -> backend:80) we have both allow and deny.
But note: in a deny-by-default system, if we have an allow and a deny, the deny might override the allow? Or the order matters?
In Istio, for example, the evaluation is by specificity and then by order of creation? Actually, Istio uses a "first match" or "most specific match"?
We need to define the conflict resolution model of the target mesh. Let's assume we are targeting a mesh that uses a "first match" or "most specific match" and then a default deny.
We can define:
- Specificity: a rule is more specific if it has more matching criteria (e.g., specific port vs any port, specific source vs any source).
- If two rules have the same specificity, then the order (or priority) matters.
But note: our DSL doesn't specify order? We can assign an implicit order (e.g., by the order in the file) or let the user specify priority.
Alternatively, we can design the DSL to be declarative and then the compiler will assign priorities based on specificity and then on user-defined ordering (if same specificity).
However, for conflict detection, we want to flag when two rules with the same specificity have different actions? But if the user intended that, maybe it's not a conflict?
Actually, if two rules have the same specificity and different actions, then the effective action depends on the order (or priority) and if the user hasn't specified an order, it's ambiguous.
So we can require the user to specify a priority for rules that might conflict? Or we can assign priorities automatically based on the order of appearance and then flag if the user has two rules that overlap and have the same specificity and no explicit priority?
Alternatively, we can design the DSL to have a single policy that is the union of all rules, and then within that policy, we allow multiple rules with priorities? But then we are designing the DSL for a single policy?
Let's think: in Kubernetes NetworkPolicy, you have multiple policies and they are additive unless there is a deny? Actually, Kubernetes NetworkPolicy is a white-list (allow) only and any traffic not allowed by any policy is denied. So there is no conflict because you can only allow.
But in Istio, you can have both allow and deny. So we need to handle both.
Let's define the IR to have:
Rule {
selector: (source, destination, ports, protocols)
action: allow | deny
priority: integer (optional, if not set then we compute based on specificity and then order of appearance)
}
Then, when compiling, we assign priorities. For conflict detection, we can check:
For any given traffic pattern (a tuple of source, destination, port, protocol), if there are two rules that match and have different actions and the same priority, then that's a conflict.
But note: if one rule is more specific (priority higher) then the less specific one doesn't matter for that traffic.
So we can compute the effective action for a given traffic pattern by taking the rule with the highest priority that matches.
Then, conflict detection can be:
For every possible traffic pattern (or at least for every pattern that is matched by at least one rule) we compute the effective action by taking the highest priority rule.
But if there are two rules with the same highest priority and different actions, then we have a conflict.
However, note that the user might have intended to have multiple rules with the same priority? That would be ambiguous.
So we can define:
-
Rules with explicit priority: if two rules have the same explicit priority and they conflict (overlap and different actions), then it's a conflict.
-
Rules without explicit priority: we assign priority based on specificity (number of matching criteria) and then by the order in which they appear (earlier gets higher priority). Then we check for conflicts only among rules that end up with the same priority? But note: if two rules have the same specificity and same order? They can't because they are in the same file? But if we have multiple files, we need to define an order.
Alternatively, we can require the user to assign priorities to avoid ambiguity.
Let's simplify: in the DSL, we don't assign priorities. Instead, we design the compiler to assign priorities automatically in a deterministic way:
Step 1: Sort by specificity (more specific first). Specificity is defined by the number of non-wildcard fields in the selector.
Step 2: If same specificity, then by the order of appearance (earlier in the file gets higher priority).
Then, for conflict detection:
For every pair of rules that overlap (i.e., there exists a traffic pattern that matches both) and have different actions, check if they have the same priority. If yes, then conflict.
But note: if one rule is more specific, then for the traffic pattern that matches both, the more specific rule will have higher priority and thus the less specific rule won't be considered. So that's not a conflict.
So we only check for conflicts when two rules have the same priority and overlap and have different actions.
However, note that two rules might have the same priority but not exactly the same traffic pattern? They might overlap on some traffic but not on others? We need to check for every traffic pattern that is matched by both.
But note: if two rules have the same priority, then for any traffic that matches both, we have two actions. So we need to check for the existence of at least one traffic pattern that matches both and for which the actions are different.
How to compute that? We can treat each rule as a set of traffic patterns (a 4-tuple: source, destination, port, protocol). Then two rules conflict if:
(rule1.action != rule2.action) AND (rule1.selector ∩ rule2.selector != empty)
and they have the same priority.
But note: if rule1 and rule2 have the same priority and overlapping selectors and different actions, then for any traffic in the intersection, we have two rules with same priority and different actions -> conflict.
However, what if the user intended that the order of evaluation (by priority) would resolve it? But we assigned the same priority. So it's ambiguous.
So we flag that as a conflict.
But wait: what if the two rules are exactly the same (same selector and same action)? Then no conflict.
So the condition is:
same priority AND overlapping selectors AND different actions.
Now, how to compute if two selectors overlap? We can represent each selector as a set of constraints on the 4-tuple. Then two selectors overlap if there exists a 4-tuple that satisfies both.
This is a constraint satisfaction problem. But note: our selectors are typically:
source: can be a specific service, a set of services (by label), a namespace, or wildcard.
destination: same.
ports: a set of ports or a range, or wildcard.
protocol: TCP/UDP/ANY, etc.
We can try to normalize the selectors and then check for intersection. But this can be complex.
Alternatively, we can use a SAT solver or a simple algorithm for the specific fields.
Since our selectors are usually simple (wildcard or set of values), we can do:
For each field (source, destination, port, protocol) check if the set of allowed values for that field in rule1 and rule2 have an intersection. If for every field the intersection is non-empty, then the selectors overlap.
But note: the source and destination are sets of services (which are identified by names and namespaces). We can represent them as sets of fully qualified names (namespace/name). Then:
source1, source2: two sets of services. They overlap if there is at least one service that is in both sets? But note: the source in a rule is a set of sources (e.g., all services in namespace A). So we can compute the intersection of the two sets of sources.
Similarly for destination.
For ports: we have a set of ports (or a range). We can check if the two sets of ports intersect.
For protocol: usually a set (TCP, UDP, ANY). We can check if the two sets have common protocol.
Then, if for all four fields the intersection is non-empty, then the two selectors overlap.
However, note: the traffic pattern is a 4-tuple. So if we have a source that is in both source sets, a destination in both destination sets, a port in both port sets, and a protocol in both protocol sets, then that 4-tuple exists.
So we can compute:
overlap = (source1 ∩ source2 != empty) AND (destination1 ∩ destination2 != empty) AND (port1 ∩ port2 != empty) AND (protocol1 ∩ protocol2 != empty)
But wait: what if the source and destination sets are huge? We don't want to enumerate. We can use set operations on the constraints.
We can represent each field as a set of possible values. Then the intersection of two sets is non-empty if there is at least one value that is in both.
But note: the sets might be defined by wildcards or by ranges. We need to be able to compute intersection of two such sets.
For example:
source1: all services in namespace A.
source2: service B.
If service B is in namespace A, then they intersect.
So we need a way to represent and compute intersections for these set constraints.
This is getting complex. Maybe we can limit the DSL to have only explicit sets (no wildcards) and then we can compute intersections by set operations? But that would be limiting.
Alternatively, we can avoid computing the exact intersection and instead use a more symbolic approach.
Given the complexity, we might decide to only check for conflicts when the two rules are on the same set of selectors (or exactly the same) and then different actions? But that would miss conflicts where the selectors are different but still overlap.
So we need a way to check for overlapping selectors.
Let's define:
A selector is a predicate on a 4-tuple.
Two selectors overlap if there exists a 4-tuple that satisfies both.
We can use a SAT solver for this, but that might be overkill.
Alternatively, we can convert the selectors to a normal form (like CNF) and then check for satisfiability of the conjunction.
But note: our selectors are usually in disjunctive normal form? Actually, a rule's selector is a conjunction of conditions on each field.
selector = (source in S) AND (destination in D) AND (port in P) AND (protocol in Prot)
So two selectors:
s1: (source in S1) AND (destination in D1) AND (port in P1) AND (protocol in Prot1)
s2: (source in S2) AND (destination in D2) AND (port in P2) AND (protocol in Prot2)
Their conjunction is:
(source in S1 ∩ S2) AND (destination in D1 ∩ D2) AND (port in P1 ∩ P2) AND (protocol in Prot1 ∩ Prot2)
So they overlap if and only if:
(S1 ∩ S2 != empty) AND (D1 ∩ D2 != empty) AND (P1 ∩ P2 != empty) AND (Prot1 ∩ Prot2 != empty)
So we just need to compute the intersection of the sets for each field.
Therefore, we need to represent the sets for source, destination, port, protocol and be able to compute their intersection.
We can define:
SourceSet: can be a set of services (by name and namespace) or a set of namespaces (meaning all services in those namespaces) or a wildcard (all services).
But note: a wildcard for source means all services. Then the intersection of wildcard with any set is that set.
Similarly for destination.
For ports: we can have a set of numbers or ranges. We can compute the intersection of two port sets.
For protocol: a set of strings (like "TCP", "UDP", "ANY"). Intersection is straightforward.
So we can implement set operations for these types.
But note: the source and destination sets might be defined by labels. We need to expand them to actual services? That would require knowing the current state of the mesh (all services and their labels). So for conflict detection, we might need the current service inventory.
Alternatively, we can treat the source and destination as sets of service identifiers (namespace/name) and if the user specifies by label, we need to expand the label to the set of services that match. So we need a service catalog.
So the conflict detection module will need access to the service catalog (or at least the set of services and their labels) to expand the label-based selectors.
Without expansion, we cannot compute the intersection of two label-based selectors because we don't know which services they refer to.
So we must have the current state of the mesh (services, namespaces, labels) to expand the selectors.
Therefore, the conflict detection will be done against the current state.
Steps for conflict detection:
-
Expand all selectors (source, destination) using the service catalog. Convert each selector to a set of concrete service identifiers (namespace/name).
-
For each rule, we now have a set of sources (set of service identifiers), a set of destinations, a set of ports, and a set of protocols.
-
Then for every pair of rules (r1, r2) with the same priority (computed as above) and with different actions, check:
if (sources1 ∩ sources2 != empty) and (destinations1 ∩ destinations2 != empty) and (ports1 ∩ ports2 != empty) and (protocols1 ∩ protocols2 != empty)
then conflict.
-
Also, we might want to check for conflicts with existing deployed policies? Yes, we are checking the new batch of policies against each other and against the current state (which includes deployed policies). So we need to include the current state as a set of rules (with their priorities) when checking for conflicts.
But note: the current state might have been deployed with a different priority assignment? We need to know the priorities of the existing rules. So we must store the priority for each deployed rule? Or we can recompute the priority for existing rules using the same algorithm? But if the existing rules were defined with explicit priorities, we must use those.
So we need to store the rule's priority (either explicit or computed) in the state.
Alternatively, we can store the rules in the state with their original DSL and then when doing conflict detection, we re-parse and re-assign priorities? But that might be error-prone if the algorithm changes.
Let's store the compiled policy with the assigned priorities.
So the state is a set of rules (with their selectors expanded and priorities assigned).
When we want to deploy new policies, we:
- Parse the new DSL and generate IR (with rules without explicit priority?).
- Expand the selectors using the current service catalog (which might have changed?).
- Assign priorities to the new rules (using the same algorithm as before? but note: the existing rules already have priorities).
- Then, we take the union of existing rules (from state) and new rules and check for conflicts (as above).
But wait: the existing rules might have been assigned priorities in a different way? We need to have a consistent way to assign priorities.
So we define a priority assignment algorithm that is deterministic and based on the rule's specificity and order of appearance (in the combined set of existing and new?).
However, the existing rules were deployed without knowledge of the new ones. So if we re-assign priorities for all rules (existing and new) based on the combined set, we might change the effective behavior of existing rules.
Therefore, we cannot change the priorities of existing rules. We must keep their priorities fixed.
So for new rules, we assign priorities that are:
- If the user specified a priority, use that.
- Otherwise, assign a priority that is higher than any existing rule? But then the new rules would always override existing ones? That might be intended.
Alternatively, we can assign priorities to new rules in a way that they are inserted into the existing priority space. We can:
- Compute the priority of existing rules (if they don't have explicit priority, we have to know how they were assigned originally). But we don't have that information.
So we must require that all rules (existing and new) have explicit priorities? That would be cumbersome.
Another idea: we don't use priorities. Instead, we use a different conflict resolution model: the most specific rule wins, and if same specificity, then the one with the earlier creation time (or higher priority) wins? But then we need to store the creation time or priority.
Let's change the model: we assign each rule a specificity score (as before) and then if two rules have the same specificity, the one that was created later (or has a higher priority) wins? But then we need to decide the order of evaluation.
Actually, in Istio, you can set the priority field. So we can use that.
But for our own conflict detection, we can assume that the target mesh uses priority (and higher number means higher priority). Then:
- Existing rules have a priority (we store it).
- New rules without explicit priority get a priority that is one more than the maximum existing priority? But then they would all have the same priority? We can assign them incrementally.
Alternatively, we can assign priorities to new rules based on their specificity and then by the order of appearance in the new DSL. But then we have to merge with existing rules that might have been assigned without considering the new ones.
This is getting messy.
Let's step back.
We want to detect conflicts. We have two sets of rules: existing and new. We want to know if after applying the new rules, there will be any traffic pattern that is matched by two rules with the same priority and different actions.
But note: the existing rules already have priorities. The new rules will be assigned priorities (either explicit or by our algorithm). Then we have a combined set of rules with priorities.
Then we check for conflicts in the combined set.
The problem is: if we assign priorities to new rules in a way that is independent of the existing rules, we might get a conflict even if the existing rules had no conflicts among themselves? But that's okay because the new rules might conflict with existing ones.
So we need to assign priorities to new rules in a deterministic way that does not depend on the existing rules? But then the priority of a new rule might be the same as an existing rule? That could cause a conflict.
How about:
- Existing rules have explicit priorities (we store them).
- New rules without explicit priority are assigned a priority that is the maximum existing priority + 1 + index? But then all new rules would have priorities higher than existing? That might be intended.
But then if two new rules have the same specificity and same index? They would have different priorities (because we assign incrementally) so no conflict? But wait, we assign by index? Then they would have different priorities and thus no conflict.
However, what if the user wants to have two new rules with the same priority? They can set explicit priority.
So:
- For new rules without explicit priority, we assign priorities starting from (max_existing_priority + 1) and increment by 1 for each rule in the order they appear in the DSL.
- For new rules with explicit priority, we use that.
Then we check for conflicts in the combined set (existing + new) by:
For every pair of rules (r1, r2) in the combined set (r1 != r2) with the same priority and different actions, check if their selectors overlap.
But note: we are only checking pairwise. What if three rules have the same priority and two of them have the same action and one has a different action? Then the two with the same action don't conflict with each other, but each conflicts with the one with the different action? Actually, if we have:
Rule1: allow, priority 10, selector A
Rule2: allow, priority 10, selector B (A and B might overlap)
Rule3: deny, priority 10, selector C (C overlaps with A and B)
Then for traffic that matches A and C, we have two rules with same priority and different actions -> conflict.
Similarly for B and C.
So we need to check every pair.
This algorithm is O(n^2) in the number of rules. But typically the number of rules is small.
However, note: we are expanding the selectors to sets of services, which might be large. But we are only checking for non-empty intersection, so we can use set operations and short-circuit.
Steps for conflict detection:
Input: existing_rules (with priorities and expanded selectors), new_rules (with assigned priorities and expanded selectors)
combined_rules = existing_rules ∪ new_rules
For each pair (r1, r2) in combined_rules with r1.priority == r2.priority and r1.action != r2.action:
if (r1.sources ∩ r2.sources != empty) and
(r1.destinations ∩ r2.destinations != empty) and
(r1.ports ∩ r2.ports != empty) and
(r1.protocols ∩ r2.protocols != empty):
report conflict between r1 and r2.
But note: what if the two rules have the same priority and same action? Then no conflict even if they overlap? Actually, they don't conflict because they have the same action.
Also, what if the two rules have different priorities? Then the one with higher priority wins, so no conflict.
So the above condition is correct.
Now, for the rollout:
We have a set of new rules to deploy. We want to roll them out in a controlled way.
We can define:
RolloutPlan {
steps: [
{ percentage: 10, rules: [rule1, rule2, ...] }, // apply to 10% of the services (or 10% of the traffic?)
{ percentage: 50, ... },
{ percentage: 100, ... }
]
}
But how do we apply to a percentage of services? We need to partition the services (or traffic) and then apply the rules only to a subset.
Alternatively, we can use Istio's ability to apply policies to a subset of workloads by using labels and then gradually expand the label selector? But note: the rule's source and destination are already using selectors. We cannot change the selector per rollout step?
Or we can have the rule's selector include an additional label that we change? That seems hacky.
Alternatively, we can have multiple rules that are the same except for the selector? Then we can gradually expand the selector.
But note: the DSL rule has a fixed selector. We cannot change it per rollout step.
So maybe the rollout is not about changing the selector, but about applying the rule to a subset of the mesh (by namespace or by a label that we add to the rule's selector).
How about we allow the rollout to be defined by an additional condition on the rule? For example:
rule "frontend-to-backend" {
source: service frontend
destination: service backend
ports: [80]
action: allow
rollout: {
phase: 1 // or a percentage?
}
}
Then the compiler will generate multiple rules for each phase? But the rule's selector is fixed.
Alternatively, we can have the rollout be on the rule itself: we apply the rule to a percentage of the traffic by using Istio's ability to do percentage-based routing? But that's for routing, not for policy.
Actually, for network policies, we typically apply at the workload level. So we want to apply the policy to a subset of workloads.
So we can modify the rule's selector to include an additional label that we control. For example:
rule "frontend-to-backend" {
source: service frontend with label rollout=phase1
destination: service backend
...
}
Then we gradually change the label on the frontend service to include more instances? But that requires changing the service deployment.
Alternatively, we can have the rule's selector be dynamic and we change the selector per phase? That would require generating multiple rules.
Let's think of a different approach:
We can have the rollout plan define which rules to apply at each step. But the rules are fixed. So we can have:
Step1: apply rule1, rule2, ... but with a modified selector that only matches a subset of services.
How about we allow the rollout to change the selector? We can define:
rollout: {
type: "percentage"
value: 10
field: "source" // or "destination"
}
Then we would generate multiple rules where we restrict the source (or destination) to 10% of the services? But how to select 10%? Random? By label?
This is getting complicated.
Alternatively, we can do rollout at the namespace level. For example, apply the policy to namespace A first, then to namespace A and B, etc.
So we can have the rollout plan define a list of namespaces (or labels) to which the policy applies at each step.
Then we modify the rule's selector to include only the namespaces in the current rollout step? But the rule might already have a namespace in the selector.
We can define the rollout to be an additional filter on the rule's selector? For example:
rule "frontend-to-backend" {
source: service frontend
destination: service backend
...
rollout: {
steps: [
{ namespaces: ["ns1"] },
{ namespaces: ["ns1", "ns2"] },
...
]
}
}
Then at step 1, we apply the rule with an additional condition that the source namespace must be in ["ns1"]? But the source is already "frontend" which is a service in a specific namespace? So we are restricting by the namespace of the source? That might not be what we want.
Alternatively, we can have the rollout be a separate concept that is not part of the rule. The rollout plan would be:
RolloutPlan {
rules: [rule1, rule2, ...],
steps: [
{ filter: "namespace in [ns1]" }, // apply the rules only to traffic where the source namespace is in [ns1]? or destination?
]
}
But then we are changing the semantics of the rule per step? That might be confusing.
Given the complexity, maybe we leave the rollout as a separate concern and implement it by:
- Having a way to stage the rules (i.e., create them with a label that indicates they are in staging) and then gradually change the label on the workloads to match?
This is more of an implementation detail of the mesh.
Alternatively, we can design the compiler to output multiple versions of the same rule with different selectors for each rollout step? Then the user would define the rollout steps and the compiler would generate:
Step1: rule with selector S1
Step2: rule with selector S2 (which is a superset of S1)
Then we apply rule1 at step1, then at step2 we apply rule2 and delete rule1? But that would cause a gap where no rule applies? We want to gradually expand.
So we can:
At step1: apply rule with selector S1.
At step2: apply rule with selector S2 (and keep rule1? but then we have two rules with different selectors and same action? That's okay, but we might have conflicts if S1 and S2 overlap and have different actions? But they are the same action.
But note: if we have two rules with the same action and overlapping selectors, that's not a conflict.
So we can generate a set of rules for each rollout step that are cumulative? But then at step2 we have both rule1 (S1) and rule2 (S2). But S2 might be a superset of S1, so rule1 is redundant? But it doesn't cause a conflict.
However, if we want to rollback, we would remove the rules from the last step.
So the rollout plan would be:
Step1: apply rules with selectors for 10% of the services.
Step2: apply rules with selectors for 50% (and remove the 10% ones? or keep them?).
But if we keep the 10% ones, then the 50% ones and 10% ones together cover 50%? Actually, the 10% ones cover 10% and the 50% ones cover 50% (which includes the 10%?).
We want the rollout to be cumulative? Then at step2 we want to cover 50% of the services. We can have:
Step1: selector S1 (10% of services)
Step2: selector S2 (40% of services that are not in S1) and then we have both S1 and S2, so total 50%.
But then we need to compute S2 such that it doesn't overlap with S1? Actually, we want to expand, so S2 should be the next 40% (disjoint from S1). Then the union is 50%.
But how to choose disjoint sets? We can partition the services.
Alternatively, we can have a single rule with a selector that is a union of the sets for each step? But then we cannot rollback step by step.
Given the complexity, maybe we don't implement a sophisticated rollout in the compiler. Instead, we rely on the mesh's native rollout mechanisms (like Istio's ability to apply policies gradually by changing the selector on the workloads?).
Actually, Istio doesn't have a built-in gradual rollout for policies. So we have to do it by changing the policy's selector.
So we can design the DSL to allow the selector to be parameterized by a rollout phase? And then the compiler generates multiple policies with different selectors for each phase.
Example:
policy "frontend-to-backend" {
source: service frontend with label rollout=?
destination: service backend
...
rollout: {
phases: [
{ label: "phase1", percentage: 10 },
{ label: "phase2", percentage: 50 }
]
}
}
Then the compiler would generate two policies:
Phase1: source: service frontend with label rollout=phase1
Phase2: source: service frontend with label rollout=phase2
And then we would change the label on the frontend service to phase1, then phase2, etc.
But note: the service might not have such a label. We would have to add it.
Alternatively, we can use a node selector or something else.
Given the time, let's not overcomplicate the rollout. We'll assume that the rollout is done by the user by changing the labels on the services and then reapplying the same policy? But then the policy doesn't change.
Actually, the policy's selector doesn't change, but the set of services that match the selector changes because we change the labels on the services.
So we don't need to generate multiple policies. We just need one policy that selects services by a label that we control. Then we change the label on the services to include them in the policy.
So the rollout is external to the compiler. The compiler just generates a policy with a selector that uses a label that we can control.
Therefore, we might not need a rollout module in the compiler. Instead, we can have the user write the policy with a selector that uses a label that they will use for rollout.
Then the rollout is done by:
Step1: label a subset of services with the rollout label (e.g., rollout=canary).
Step2: apply the policy (which selects services with that label).
Step3: gradually label more services.
But note: the policy's selector might already have other conditions. We can combine:
source: service frontend with label app=frontend and label rollout=canary
Then we can change the rollout label.
So the compiler doesn't need to know about rollout. It just compiles the policy as written.
Then what about the rollout controls? Maybe we don't need them in the compiler? The user can do rollout by changing labels and then reapplying the policy? But reapplying the policy doesn't change because the policy is the same, but the set of services that match changes.
However, if the policy is already applied, changing the labels on the services will immediately change the set of services that the policy applies to? In Istio, the policy is evaluated at the proxy, and the proxy watches for changes in the services and labels. So if we change the label on a service, the policy will start to apply to that service.
So we don't need to reapply the policy. We just change the labels.
Therefore, the rollout is external to the compiler.
So we can skip the rollout module in the compiler and just focus on:
DSL -> IR -> Compile to target -> Conflict detection -> Verification.
But the requirement says "rollout controls". So we might need to provide a way to control the rollout. Maybe we can have a separate tool that manages the labels and applies the policy in steps? That tool would use the compiler to generate the policy, then manage the labels on the services.
Alternatively, we can design the compiler to output a set of policies for each rollout step? But then we need to know the rollout plan at compile time.
Given the complexity, let's assume that the rollout is managed by an external system that uses the compiler to generate the policy and then manages the labels on the services to control which services are subject to the policy.
So in the compiler, we don't handle rollout.
Now, verification:
We want to verify that the policy is enforced as intended.
We can have a test DSL that allows the user to write test cases:
test "frontend can talk to backend" {
source: frontend
destination: backend
port: 80
expected: allow
}
test "external cannot talk to backend" {
source: external
destination: backend
port: 80
expected: deny
}
Then, after deploying the policy, we run these tests by sending traffic (or simulating) and checking the outcome.
We need a way to inject traffic from the source to the destination and observe if it is allowed or denied.
This can be done by:
- Using a testing framework that can run in the cluster (e.g., using a pod that sends requests and checks responses).
- Or by querying the mesh's policy logs or metrics.
We can design a verifier that:
- Takes the test cases (in a DSL) and the current policy state.
- For each test case, determines the source and destination (which are services or external).
- If the source is a service, we might need to run a pod in that service's namespace to send traffic? Or use an existing pod?
- We can have a test runner that is deployed in the cluster and runs the tests.
Alternatively, we can use the mesh's ability to simulate traffic? Not all meshes have that.
Given the complexity, we can leave the verification as a separate component that uses the compiled policies to generate test plans and then executes them with a test runner.
So the compiler's output includes the compiled policies and also the test cases (if provided) in a format that the verifier can use.
Summary:
We'll design:
- A DSL for policies and tests.
- A compiler that:
* Parses the DSL and generates IR.
* Expands the selectors using the service catalog.
* Assigns priorities to rules (for new rules, if not specified, assign based on specificity and order, but also consider existing rules' priorities? We assign new rules priorities that are higher than existing? But then we might override existing rules? That might be intended.
Actually, we want to allow the user to control the priority. So we should require explicit priorities? Or we can assign priorities in a way that is consistent with the existing ones?
Let's change: we don't assign priorities automatically. Instead, we require the user to specify the priority in the DSL? But that is not user-friendly.
Alternatively, we can compute the priority based on the rule's specificity and then by the order in the combined set (existing and new). But then we are changing the priority of existing rules? We cannot.
So we must have the existing rules' priorities fixed.
Therefore, for new rules, we assign priorities that are:
if the rule has an explicit priority, use that.
else, assign a priority that is one more than the maximum existing priority? But then all new rules would have the same priority? We can assign incrementally.
But note: the existing rules might have gaps in priorities. We can assign new rules to fill the gaps? But that would be complex.
Let's do:
Let M = max priority among existing rules.
For new rules without explicit priority, assign priorities starting from M+1, in the order they appear.
Then, when we check for conflicts, we use the assigned priorities.
But note: if two new rules have the same specificity and we assign them consecutive priorities, then they won't conflict because they have different priorities? But what if the user intended them to have the same priority? They should set explicit priority.
So we are safe.
- Conflict detection: as described above.
- Compilation: convert the IR (with assigned priorities) to the target mesh's policy format.
- Output: the compiled policies and also a report of conflicts (if any).
- Verification: we can have a separate verifier that uses the test DSL and the compiled policies to run tests.
We'll ignore rollout in the compiler.
Now, let's design the DSL:
We'll use a simple grammar:
policy <name> {
source: <source_selector>
destination: <destination_selector>
ports: <port_list>
protocol: <protocol_list> // optional, default to any
action: allow | deny
priority: <integer> // optional
}
source_selector and destination_selector can be:
service <service_name> [in namespace <namespace>] [with label <key>=<value>]*
or
namespace <namespace> [with label <key>=<value>]*
or
external // for external sources/destinations
or
any // wildcard
But note: we might want to select by multiple services? We can have a list.
Alternatively, we can have:
source: [service1, service2, ...] or [namespace1, namespace2] or external or any.
Let's design:
source: (service <name> [in <namespace>] [with <label>=<value>])*
| namespace <name> [with <label>=<value>]*
| external
| any
But then we have a list? Actually, we want to match if the source is one of the services or namespaces? So it's an OR.
We can represent the source selector as a set of service selectors (each being a service or a namespace with optional labels) or external or any.
Similarly for destination.
Example:
source: service frontend in namespace default, service backend in namespace prod with label tier=backend
This means the source can be either the frontend service in default namespace OR the backend service in prod namespace with the label.
But note: the second one has a label condition. So we have two service selectors.
So the source selector is a list of service selectors (each of which can have namespace and labels) and also the special tokens external and any.
We can define:
service_selector: "service" service_name ["in" namespace] [("with" label)*]
source: (service_selector | "namespace" namespace_name [("with" label)*] | "external" | "any") ("," ...)*
But then we have to parse a list.
Alternatively, we can use:
source: selector1 | selector2 | ...
where each selector is one of the above.
Let's use a list separated by commas.
Example:
source: service frontend in namespace default, namespace prod with label app=backend
This means the source is either the frontend service in default namespace OR any service in the prod namespace with label app=backend.
We also have to handle the case of wildcard. We can say that if one of the selectors is "any", then it matches everything? But then if we have:
source: service frontend, any
that would match everything? Actually, it would match frontend and everything else? So it's the same as any? Then we can just use any.
But note: we might want to have multiple selectors that are not all-encompassing.
So we can treat "any" as a selector that matches every source. Then if the list contains "any", then the source matches any source.
Similarly for destination.
Now, for ports and protocol:
ports: <port> or <port>-<port> or list of these separated by commas.
protocol: "TCP", "UDP", "ANY" or list.
Example:
ports: 80, 443, 1000-2000
protocol: TCP, UDP
Now, for the test DSL:
test <name> {
source: <source_selector> // same as above? but we might want to specify a specific pod? or just a service?
destination: <destination_selector>
port: <port>
protocol: <protocol> // optional
expected: allow | deny
}
But note: the test might require that we have a pod that represents the source? We can assume that the source selector matches exactly one pod? Or we can run the test from a pod that is in the source namespace?
We might need to specify the source as a pod? Or we can run the test from a generic test pod that we deploy in the source namespace?
This is getting into the verifier implementation.
Given the time, we'll define the test DSL similarly to the policy, but without the action and priority.
We'll leave the verifier implementation details for later.
Now, let's outline the compiler modules:
-
Parser for the DSL (using ANTLR or a simple recursive descent). We'll define the grammar.
-
IR:
Policy {
name: string
rules: list
}
Rule {
id: string // generated
source: SourceSelector // which is a list of ServiceSelector or External or Any
destination: DestinationSelector
ports: PortSet
protocols: ProtocolSet
action: Allow | Deny
priority: int // assigned by the compiler
}
ServiceSelector {
service: string // service name
namespace: string? // if not specified, then any namespace? or the current namespace? We should require namespace for service?
labels: map<string, string> // optional
}
PortSet: we can represent as a set of integers and ranges.
ProtocolSet: set of strings.
-
ServiceCatalog: a struct that holds all services and their labels and namespaces.
-
ConflictDetector:
Input: list (with priorities and expanded selectors)
Output: list
Conflict: between two rules (by id) and the overlapping selectors? We can just report the rule ids.
-
Compiler:
- Parse the DSL to get Policy objects (with rules without priority if not specified).
- Expand the selectors using the ServiceCatalog.
- Assign priorities to the new rules (taking into account existing rules' priorities).
- Combine with existing rules (from state) and run ConflictDetector.
- If no conflicts, generate the target mesh policies.
-
StateManager:
- Stores the current set of deployed rules (with their IR and compiled form).
- Allows adding new rules (with conflict detection) and removing rules.
-
Verifier:
- Takes test DSL and the current state (or a set of policies) and runs tests.
Given the complexity, we might not implement all, but we can design the interfaces.
Let's write some code sketches in Go (or pseudocode) for the main components.
We'll assume we are targeting Istio, so we need to output Istio AuthorizationPolicy.
But note: Istio's AuthorizationPolicy has a different model: it is applied at the workload level and the rules are evaluated in order of priority.
We can map our Rule to an Istio rule.
Steps for compilation to Istio:
For each of our rules, we create an Istio rule with:
selector: the destination selector? Actually, Istio's AuthorizationPolicy is applied to a workload (by selector). So we have to apply the rule to the destination workload? But our rule has a source and destination.
In Istio, the AuthorizationPolicy applies to the workloads that match the selector (the destination). Then the rule's from and to fields specify the source and destination? Wait, the destination in our rule is the target of the traffic? But in Istio, the policy is applied to the destination workload, and then we specify the sources in the "from" field.
So:
Our rule's destination -> Istio's selector (the workload to which the policy is applied).
Our rule's source -> Istio's "from" field (which is a list of sources).
But note: our rule also has ports and protocols. In Istio, we can specify ports and protocols in the "to" field? Actually, the AuthorizationPolicy has:
from: list<Source>
to: list<Destination>
ports: list<string> // but note: the ports are in the "to" field? Actually, the "to" field can have a list of ports.
So:
Our rule's source -> Istio's from (which is a list of sources, each source has principals and/or namespaces and/or ipBlocks)
Our rule's destination -> Istio's selector (the workload selector) and also in the "to" field we can specify the ports? Actually, the "to" field in Istio is for the destination (which is the same as the workload?).
Wait, let's clarify:
In Istio, an AuthorizationPolicy is applied to a set of workloads (by label selector). Then for each rule in the policy, we specify:
from: the sources that are allowed to send requests to the workloads.
to: the operations (destination) which are on the workloads? Actually, the "to" field is for the destination service? But the policy is already applied to the destination workload. So the "to" field is for the ports and protocols?
According to Istio docs:
from: list of sources that the rule applies to.
to: list of destinations that the rule applies to. The destination is defined by a combination of host (service) and port? Or just port?
Actually, the "to" field is for the destination service (host) and port? But the policy is applied to a specific workload, so the host is that workload?
This is confusing.
Let's look at an example:
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: allow-viewer
namespace: default
spec:
selector:
matchLabels:
app: ratings
rules:
- from:
- source:
principals: ["cluster.local/ns/default/sa/bookinfo-ratings"]
to:
- operation:
methods: ["GET"]
paths: ["/info"]
ports: ["8080"]
Here, the policy is applied to workloads with label app=ratings. Then the rule says: allow requests from the specified principal to the operation (which is on the ratings workload) on port 8080 and with method GET and path /info.
So the "to" field is about the operation on the destination workload (which is the one selected by the selector). So the destination in our rule (which is the target service) is already the workload selected by the selector. Then our rule's port and protocol would go into the "to.operation.ports" and "to.operation.ports" might be a list of ports? Actually, the operation has ports.
But our rule doesn't have methods and paths. So we only care about ports and protocols? We can map:
Our rule's ports -> to.operation.ports
Our rule's protocol -> to.operation.ports? Actually, protocol is not in the operation? In Istio, the operation has ports, but the protocol is determined by the port? Or we can specify the protocol in the "to" field? Actually, the AuthorizationPolicy doesn't have a protocol field. It uses the port to determine the protocol? Or it's layer 7.
This is getting messy.
Given the complexity of mapping to Istio, and the fact that different meshes have different models, we might want to keep the compiler target-agnostic and then have a backend for each mesh.
But the requirement is for service meshes in general. So we design the IR and then have a backend for each mesh.
For now, we'll focus on the IR and conflict detection, and assume we have a backend that can convert our IR to the mesh's policy.
So we don't need to worry about the exact mapping for now.
Given the time, we'll stop the design here and provide a high-level architecture.
Architecture:
+----------------+ +----------------+ +----------------+
| DSL (policies) | --> | Parser | --> | IR |
+----------------+ +----------------+ +----------------+
|
v
+----------------+ +----------------+ +----------------+
| ServiceCatalog| <-- | ConflictDetector | <-- | StateManager |
+----------------+ +----------------+ +----------------+
|
v
+----------------+ +----------------+ +----------------+
| Target Mesh | <-- | Compiler | <-- | IR (with priorities)|
+----------------+ +----------------+ +----------------+
|
v
+----------------+ +----------------+ +----------------+
| Test Runner | <-- | Verifier | <-- | Test DSL |
+----------------+ +----------------+ +----------------+
Steps:
1. User writes policies in DSL.
2. Parser generates IR (without priorities for new rules).
3. ConflictDetector:
- Expands the selectors in the new IR using the ServiceCatalog.
- Fetches the current state (existing rules with priorities and expanded selectors) from StateManager.
- Assigns priorities to new rules (using the existing rules' max priority and then incrementing).
- Combines the existing and new rules.
- Checks for conflicts (same priority, different actions, overlapping selectors).
- If conflicts, return error.
4. If no conflicts, Compiler converts the combined IR (with new rules added) to the target mesh's policy format.
5. StateManager updates the state with the new rules (storing their IR and compiled form).
6. Verifier can run tests (from test DSL) against the current state.
For rollout: we don't handle in the compiler. The user can change the labels on the services to control which services match the selectors.
This is a high-level design. Implementation details would be extensive.
We'll now write some pseudocode for the conflict detection and priority assignment.
Pseudocode:
// Existing rules from state
existingRules = stateManager.GetRules() // each rule has: id, sourceSelectors (expanded), destSelectors (expanded), ports, protocols, action, priority
// New rules from DSL (without priority)
newRules = parser.Parse(dsl) // each rule has: sourceSelectors (not expanded), destSelectors (not expanded), ports, protocols, action
// Expand new rules using serviceCatalog
for rule in newRules:
rule.sourceSelectorsExpanded = expandSelectors(rule.sourceSelectors, serviceCatalog)
rule.destSelectorsExpanded = expandSelectors(rule.destSelectors, serviceCatalog)
// Assign priorities to new rules
maxExistingPriority = max(rule.priority for rule in existingRules)
for i, rule in enumerate(newRules):
if rule.priority is not set:
rule.priority = maxExistingPriority + 1 + i
// Combine
allRules = existingRules + newRules
// Conflict detection
conflicts = []
for i in range(len(allRules)):
for j in range(i+1, len(allRules)):
r1 = allRules[i]
r2 = allRules[j]
if r1.priority == r2.priority and r1.action != r2.action:
if selectorsOverlap(r1, r2):
conflicts.append((r1.id, r2.id))
if conflicts:
return conflicts
// Otherwise, proceed to compile and update state.
The function selectorsOverlap(r1, r2) checks:
(r1.sourceSelectorsExpanded ∩ r2.sourceSelectorsExpanded != empty) and
(r1.destSelectorsExpanded ∩ r2.destSelectorsExpanded != empty) and
(r1.ports ∩ r2.ports != empty) and
(r1.protocols ∩ r2.protocols != empty)
We assume that the expanded selectors are sets of service identifiers (for source and destination) and for ports and protocols we have sets of integers and strings respectively.
This is a simplification because the source and destination might be external or any. We have to handle that.
For external: we can treat it as a special service identifier, say "external".
For any: we can treat it as the set of all services? But then the intersection with any is the other set. So:
any ∩ X = X
external ∩ external = {external}
external ∩ any service = empty? because external is not a service.
So we have to define:
SourceSelectorExpanded: set of ServiceID (namespace/name) or "external" or "any"?
But note: "any" matches everything, so if one rule has source "any" and the other has source "service A", then they overlap? Because a traffic from service A would match both?
Rule1: source any -> matches any source.
Rule2: source service A -> matches only source A.
Then for traffic from A, both rules match.
So we need to represent "any" as the set of all possible sources (including external?). But note: our source selector can be external or any? Actually, we have separate tokens for external and any.
Let's define:
A traffic source can be:
- a service (with namespace and name)
- external (from outside the mesh)
Then "any" means any source (services and external).
So:
any = set of all services ∪ {external}
Then:
any ∩ X = X (if X is a subset of all sources)
So if one rule has source any and the other has source service A, then the intersection is service A (if service A is in the set of all services, which it is).
So they overlap.
Similarly for destination.
So we can represent:
SourceSet = set<ServiceID> ∪ {external} and we also have a special set "all" which is the union of all services and external.
Then "any" is represented by "all".
But note: we might have a rule that says source: external. That is just {external}.
So:
any (all) ∩ external = {external}
any ∩ service A = {service A}
So we can compute the intersection of two source sets:
If one of them is "all", then the intersection is the other set.
If both are sets of service IDs and external, then we take set intersection.
Similarly for destination.
Now, for ports and protocols, we have sets of ports (integers and ranges) and set of protocols.
We need to compute the intersection of two port sets. We can represent a port set as a list of intervals and then compute the intersection of two sets of intervals.
But note: the port sets might be large? Typically they are small.
We can do:
For two port sets P1 and P2, we can compute P1 ∩ P2 by:
For each port in P1, check if it is in P2? But if P1 is a range, we need to compute the intersection of the ranges.
We can represent a port set as a sorted list of disjoint intervals.
Then the intersection of two such lists can be computed by merging.
But for simplicity, we can assume that the port sets are small and we can expand them to individual ports? But if we have a range 1-65535, that's too many.
So we need an efficient way.
Alternatively, we can avoid expanding and just check for emptiness:
Two port sets intersect if there exists a port that is in both.
We can check by:
For each interval in P1, check if it overlaps with any interval in P2.
We can do:
Sort intervals by start.
Then use two pointers to find overlap.
Given the complexity, we might assume that the port sets are small enough to expand? But that's not safe.
Alternatively, we can represent the port set as a predicate and then check satisfiability? That's overkill.
Let's do a simple algorithm:
function intervalsOverlap(int1, int2):
return int1.start <= int2.end and int2.start <= int1.end
Then for two lists of intervals (sorted by start), we can iterate:
i=0, j=0
while i < len(P1) and j < len(P2):
if intervalsOverlap(P1[i], P2[j]):
return true
if P1[i].start < P2[j].start:
i++
else:
j++
return false
But note: the intervals in each set are disjoint and sorted. So this works.
For protocols, we can just do set intersection of the strings.
So the selectorsOverlap function:
def selectorsOverlap(r1, r2):
if not setIntersect(r1.sourceSet, r2.sourceSet): return false
if not setIntersect(r1.destSet, r2.destSet): return false
if not portSetsIntersect(r1.ports, r2.ports): return false
if not setIntersect(r1.protocols, r2.protocols): return false
return true
Where setIntersect for source and destination sets:
If one set is "all", then return the other set is non-empty? Actually, if one set is "all", then the intersection is the other set (if the other set is non-empty). But note: the other set might be empty? Then no intersection.
So:
if set1 == "all": return set2 is not empty
if set2 == "all": return set1 is not empty
else: return (set1 ∩ set2) is not empty
But note: our sourceSet and destSet are either "all" or a set of ServiceIDs and possibly "external".
So we can represent:
type SourceSet = struct {
all: bool
services: set<ServiceID>
external: bool // if true, then includes external
}
Then:
setIntersect(s1, s2):
if s1.all and s2.all: return true // because both are all, so there is at least one source (external or a service)
if s1.all: return s2.hasAny() // s2 has at least one element (service or external)
if s2.all: return s1.hasAny()
// both are not all
// check if there is a common service or if both have external
commonServices = s1.services ∩ s2.services
if commonServices not empty: return true
if s1.external and s2.external: return true
return false
Similarly for destination.
But note: what if s1.services is empty and s1.external is false? Then s1 has no sources? That shouldn't happen because a selector must match at least something? But it could be an empty set? Then it doesn't match any traffic.
So we have to handle empty sets.
Now, for the port set intersection:
We represent a port set as a list of intervals (each interval is [start, end] inclusive).
Then:
portSetsIntersect(P1, P2):
// assume P1 and P2 are sorted by start and disjoint within each set.
i=0, j=0
while i < len(P1) and j < len(P2):
if intervalsOverlap(P1[i], P2[j]):
return true
if P1[i].start < P2[j].start:
i++
else:
j++
return false
This is efficient.
Now, for the expansion of selectors:
We have a ServiceCatalog that knows:
- All services (namespace, name) and their labels.
For a source selector that is:
service <name> in <namespace> with labels...
We find all services that match:
name == given name, namespace == given namespace (if provided), and labels match.
If the namespace is not provided, we look for the service in all namespaces? But then we might get multiple? Actually, service names are unique within a namespace but not across namespaces. So if we don't specify namespace, we might get multiple services with the same name in different namespaces? That's possible.
So we have to return all services that match the name and labels and if namespace is provided, then only that namespace.
For a namespace selector:
namespace <name> with labels...
We return all services in that namespace that have the labels (if labels provided) or all services in that namespace.
Then the expanded source set is the set of all service IDs (namespace/name) that match, plus if the selector includes "external" then we add "external".
But note: the source selector can have multiple parts (OR). So we take the union.
Similarly for destination.
Now, for the test verifier:
We have test cases that specify:
source: (same selector as in policy)
destination: (same)
port: a specific port (or list? but test is for one traffic flow)
protocol: optional
expected: allow/deny
We need to run a test for each test case.
How to run:
We need to send traffic from a source that matches the source selector to a destination that matches the destination selector on the given port and protocol.
We can deploy a test runner pod in the cluster. The test runner will:
- For each test case:
* Determine a source pod that matches the source selector. If there are multiple, pick one? Or we might need to test all? But that could be many.
* Determine a destination pod that matches the destination selector.
* Send a request from the source pod to the destination pod on the given port and protocol.
* Check if the connection is established (or the request succeeds) and compare with expected.
But note: the test runner might not be in the same namespace as the source? We might need to run the test from the source pod? Or we can use the source pod's network namespace?
Alternatively, we can have the test runner run in the source pod's namespace and use the source pod's service account? But we need to run a process in the source pod.
We can use `kubectl exec` to run a command in the source pod? But that requires the test runner to have permissions.
Alternatively, we can have a generic test pod that we deploy in each namespace and then run the test from there? But then the source is that test pod, not the actual source service.
This is complex.
Given the time, we can assume that the test runner has the ability to run commands in any pod (with appropriate RBAC). Then:
For each test case:
sourcePod = findPodMatchingSourceSelector(sourceSelector)
destPod = findPodMatchingDestSelector(destSelector)
runCommandInPod(sourcePod, "curl http://<destPodIP>:<port>") // if protocol is TCP and port is 80, etc.
check the result (success/failure) against expected.
But note: the source selector might match multiple pods. We might need to test all? That could be too many. We can test a sample? Or we can assume that if the policy is applied at the workload level (by label), then all pods of the same workload have the same policy? So we can test one pod per workload.
But the source selector might match multiple workloads. We might need to test each workload? That could be many.
Alternatively, we can test the policy by sending traffic from a pod that is in the source namespace and has the source labels? But then we are not testing from the actual source service.
Given the complexity, we might leave the verifier as a future work.
Conclusion:
We have designed the main components. The implementation would be a significant effort.
We'll provide a high-level summary:
- DSL: as described.
- IR: as described.
- Conflict detection: by expanding selectors and checking for overlapping rules with same priority and different actions.
- Rollout: not handled by the compiler, but can be done by controlling the labels on the services.
- Verification: test DSL and a test runner that sends traffic and checks outcomes.
This is a good starting point for an intent-based network policy compiler for service meshes.
I'll design a comprehensive intent-based network policy compiler for service meshes with all requested features. Here's the complete architecture:
System Architecture
┌─────────────────────────────────────────────────────────────────┐
│ INTENT-BASED POLICY COMPILER │
├─────────────┬─────────────┬─────────────┬─────────────┬────────┤
│ DSL │ Conflict │ Rollout │ Verification │ Target │
│ Parser │ Detection │ Controller │ Engine │ Mesh │
│ & Normalizer│ Engine │ │ │ Adapter│
└─────────────┴─────────────┴─────────────┴─────────────┴────────┘
1. Domain-Specific Language (DSL)
Policy Intent Syntax
# High-level intent declaration
intent "frontend-backend-communication" {
description: "Frontend services can call backend APIs"
# Who can communicate
subject: {
services: ["frontend.*"] # regex pattern matching
namespaces: ["prod-*"]
principals: ["spiffe://cluster/ns/default/sa/frontend"]
}
# What they can access
target: {
services: ["backend-api", "payment-service"]
ports: [8080, 8443]
protocols: [TCP]
}
# Intent constraints
constraints: {
max_connections_per_second: 1000
required_encryption: true
allowed_time_window: "09:00-17:00"
compliance_tag: "pci-dss"
}
# Resolution preference
resolution: {
conflict_strategy: "deny-overrides" # or "allow-overrides", "specificity"
default_action: "deny"
}
# Rollout metadata
rollout: {
phase: "canary" # phased, canary, all-at-once
target_percentage: 25
metrics_threshold: 0.99 # 99% success rate required
auto_rollback: true
}
}
Advanced DSL Features
# Context-aware policies
intent "env-aware-policy" {
subject: {
services: ["service-a"]
environment: "production" # context: production/staging/dev
}
target: {
services: ["database-cluster"]
dynamic: {
when: "request.header['x-user-tier'] == 'premium'"
then: {
ports: [3306, 3307]
max_bandwidth: "1Gbps"
}
else: {
ports: [3306]
max_bandwidth: "100Mbps"
}
}
}
}
# Intent composition (reusability)
intent "base-microservice-policy" {
subject: { services: ["*"] }
target: { protocols: [TCP] }
constraints: { required_tls: true }
}
intent "my-service-policy" {
imports: ["base-microservice-policy"]
extends: {
subject: { services: ["my-service"] }
target: { services: ["redis", "*"] }
}
}
2. Conflict Detection Engine
Conflict Taxonomy
class ConflictType(Enum):
SEMANTIC = 1 # Allow vs Deny on same traffic
CAPACITY = 2 # Overlapping rate limits
COMPLIANCE = 3 # Contradicting compliance requirements
TOPOLOGY = 4 # Conflicting service dependencies
TEMPORAL = 5 # Time window overlaps with contradictions
RESOURCE = 6 # Contradictory resource constraints
class ConflictDetector:
def __init__(self, policy_registry, topology_graph):
self.registry = policy_registry # All active policies
self.topology = topology_graph # Service dependency graph
def detect_conflicts(self, new_intent: Intent) -> List[Conflict]:
conflicts = []
# 1. Expand intent to concrete rules
candidate_rules = self.expand_intent(new_intent)
# 2. Check against existing policies
for existing_intent in self.registry.get_active_intents():
existing_rules = self.expand_intent(existing_intent)
for candidate_rule in candidate_rules:
for existing_rule in existing_rules:
if self.rules_overlap(candidate_rule, existing_rule):
conflict = self.analyze_overlap(
candidate_rule, existing_rule, new_intent, existing_intent
)
if conflict:
conflicts.append(conflict)
# 3. Check internal consistency within new intent
internal_conflicts = self.check_intent_consistency(new_intent)
conflicts.extend(internal_conflicts)
# 4. Topology validation
topology_conflicts = self.validate_topology_constraints(new_intent)
conflicts.extend(topology_conflicts)
return self.deduplicate_conflicts(conflicts)
def rules_overlap(self, r1: Rule, r2: Rule) -> bool:
"""Check if two rules could match the same traffic"""
return (
self.sources_overlap(r1.sources, r2.sources) and
self.destinations_overlap(r1.destinations, r2.destinations) and
self.ports_overlap(r1.ports, r2.ports) and
self.protocols_overlap(r1.protocols, r2.protocols)
)
def analyze_overlap(self, r1, r2, intent1, intent2) -> Optional[Conflict]:
"""Determine conflict type and severity"""
# Semantic conflict (allow vs deny)
if r1.action != r2.action:
return Conflict(
type=ConflictType.SEMANTIC,
intents=[intent1.name, intent2.name],
description=f"Intent '{intent1.name}' {r1.action} conflicts with '{intent2.name}' {r2.action}",
severity="CRITICAL",
resolution_hint=self.suggest_resolution(r1, r2)
)
# Capacity conflict
if r1.max_connections and r2.max_connections:
combined = r1.max_connections + r2.max_connections
if combined > self.get_link_capacity(r1.destinations[0]):
return Conflict(...)
return None
Conflict Resolution Strategies
class ConflictResolver:
STRATEGIES = {
"deny-overrides": lambda conflicts: max(conflicts, key=lambda c: c.severity == "DENY"),
"allow-overrides": lambda conflicts: max(conflicts, key=lambda c: c.severity == "ALLOW"),
"specificity": lambda conflicts: max(conflicts, key=lambda c: c.rule_specificity),
"priority": lambda conflicts: max(conflicts, key=lambda c: c.intent_priority),
"latest": lambda conflicts: conflicts[-1] # Most recent wins
}
def resolve(self, conflicts: List[Conflict], strategy: str) -> List[Rule]:
"""Apply resolution strategy to conflicts"""
if strategy == "manual":
return self.require_human_intervention(conflicts)
resolved = []
grouped = self.group_by_overlap(conflicts)
for overlap_group in grouped:
winner = self.STRATEGIES[strategy](overlap_group)
resolved.append(winner.rule)
# Add compensating controls for rejected rules
for rule in overlap_group:
if rule != winner:
self.add_compensating_control(rule, winner)
return resolved
3. Rollout Controller
Phased Rollout Manager
class RolloutController:
def __init__(self, policy_compiler, mesh_adapter, metrics_collector):
self.compiler = policy_compiler
self.adapter = mesh_adapter
self.metrics = metrics_collector
self.rollout_state = {} # Track rollout progress
async def execute_rollout(self, intent: Intent, plan: RolloutPlan) -> RolloutResult:
"""Execute controlled rollout of policy"""
stages = self._calculate_stages(plan)
result = RolloutResult(status="IN_PROGRESS")
for stage in stages:
# 1. Compile stage-specific policies
stage_policies = self.compiler.compile_stage(intent, stage)
# 2. Apply to target subset
await self._apply_stage(stage_policies, stage)
# 3. Wait for stabilization
await self._wait_for_stabilization(stage.wait_time)
# 4. Verify metrics
metrics_ok = await self._verify_metrics(stage.verification_tests)
if not metrics_ok and plan.auto_rollback:
await self._rollback_to_previous_stage()
result.status = "FAILED"
result.failed_stage = stage
break
# 5. Update state
self.rollout_state[intent.name] = {
"current_stage": stage.id,
"applied_percentage": stage.target_percentage
}
# 6. Auto-advance or pause for manual approval
if stage.requires_approval and not plan.auto_advance:
await self._wait_for_manual_approval()
result.status = "COMPLETED"
return result
def _calculate_stages(self, plan: RolloutPlan) -> List[RolloutStage]:
"""Generate rollout stages based on strategy"""
if plan.strategy == "canary":
return [
RolloutStage(1, "canary", 5, ["namespace/canary-*"],
verification_tests=["latency", "error_rate"]),
RolloutStage(2, "canary", 25, ["namespace/*"],
verification_tests=["latency", "error_rate", "throughput"]),
RolloutStage(3, "full", 100, ["*"],
verification_tests=["all"])
]
# Additional strategies: blue-green, rolling, etc.
Safety Mechanisms
class SafetyMonitor:
def __init__(self, mesh_adapter, thresholds):
self.adapter = mesh_adapter
self.thresholds = thresholds
async def monitor_rollout(self, rollout_id: str):
"""Continuous monitoring during rollout"""
while True:
current_metrics = await self.adapter.get_system_metrics()
# Check SLOs
violations = []
for metric, threshold in self.thresholds.items():
if current_metrics[metric] > threshold.max_value:
violations.append(f"{metric} exceeded threshold")
if violations:
await self.trigger_emergency_rollback(rollout_id, violations)
break
await asyncio.sleep(30) # Check every 30 seconds
4. Verification Engine
Multi-Layer Verification
class VerificationEngine:
def __init__(self, mesh_adapter, test_engine, compliance_checker):
self.adapter = mesh_adapter
self.test_engine = test_engine
self.compliance = compliance_checker
async def verify_policy(self, compiled_policy: CompiledPolicy,
intent: Intent) -> VerificationReport:
"""Comprehensive verification of deployed policy"""
report = VerificationReport(intent.name)
# Layer 1: Syntax & Semantic Validation
syntax_ok = await self._validate_syntax(compiled_policy)
report.add_result("syntax_validation", syntax_ok)
# Layer 2: Control Plane Verification
control_plane_ok = await self._verify_control_plane(compiled_policy)
report.add_result("control_plane", control_plane_ok)
# Layer 3: Data Plane Testing (live traffic)
test_results = await self.test_engine.run_test_suite(
intent.test_cases or self._generate_default_tests(intent)
)
report.add_result("data_plane", test_results)
# Layer 4: Compliance Check
compliance_results = await self.compliance.check(
compiled_policy, intent.constraints.compliance_tag
)
report.add_result("compliance", compliance_results)
# Layer 5: Performance Impact
perf_impact = await self._measure_performance_impact(compiled_policy)
report.add_metric("performance_impact", perf_impact)
# Layer 6: Security Posture
security_score = await self._assess_security_posture(compiled_policy)
report.add_metric("security_score", security_score)
return report
async def _generate_default_tests(self, intent: Intent) -> List[TestCase]:
"""Generate test cases from intent"""
tests = []
# Positive test: expected allowed traffic
tests.append(TestCase(
name=f"{intent.name}-allow",
source=intent.subject.services[0],
destination=intent.target.services[0],
port=intent.target.ports[0],
expected="ALLOW",
description="Verify intended allowed traffic"
))
# Negative test: explicitly denied traffic
tests.append(TestCase(
name=f"{intent.name}-deny",
source="unauthorized-service",
destination=intent.target.services[0],
port=intent.target.ports[0],
expected="DENY",
description="Verify unauthorized traffic blocked"
))
# Port scan test
if len(intent.target.ports) > 1:
tests.append(TestCase(
name=f"{intent.name}-port-scan",
source=intent.subject.services[0],
destination=intent.target.services[0],
port=9999, # Unauthorized port
expected="DENY",
description="Verify port restrictions"
))
return tests
Chaos Testing Integration
class ChaosVerifier:
async def run_chaos_tests(self, policy_id: str):
"""Inject failures to verify resilience"""
chaos_tests = [
{"type": "pod_kill", "target": "backend-service", "expected": "circuit_breaker_triggered"},
{"type": "network_latency", "latency_ms": 500, "expected": "timeout_handling"},
{"type": "service_mesh_component_failure", "component": "istio-pilot"}
]
for test in chaos_tests:
await self.inject_chaos(test)
await asyncio.sleep(10) # Wait for propagation
# Verify policy still enforced
result = await self.verify_policy_enforcement(policy_id)
if not result:
raise ChaosTestFailure(f"Policy not enforced during {test['type']}")
5. Target Mesh Adapter Interface
class MeshAdapter(ABC):
"""Abstract adapter for different service meshes"""
@abstractmethod
def compile_policy(self, ir: IntermediateRepresentation) -> MeshPolicy:
"""Convert IR to mesh-specific policy"""
pass
@abstractmethod
async def deploy_policy(self, policy: MeshPolicy, phase: str = "all"):
"""Deploy policy to mesh with optional staging"""
pass
@abstractmethod
async def get_effective_policy(self,
source: ServiceIdentity,
destination: ServiceIdentity) -> EffectiveRule:
"""Query effective policy for given traffic pattern"""
pass
@abstractmethod
async def get_metrics(self) -> MeshMetrics:
"""Collect mesh metrics for verification"""
pass
@abstractmethod
async def rollback_policy(self, policy_id: str, to_version: str):
"""Rollback to previous policy version"""
pass
# Example: Istio Adapter
class IstioAdapter(MeshAdapter):
def compile_policy(self, ir: IR) -> IstioAuthorizationPolicy:
auth_policy = AuthorizationPolicy()
auth_policy.selector = self._build_selector(ir.destination)
for rule in ir.rules:
istio_rule = AuthorizationPolicyRule()
istio_rule.from_ = self._compile_sources(rule.sources)
istio_rule.to = self._compile_destinations(rule.destinations)
istio_rule.when = self._compile_constraints(rule.constraints)
auth_policy.rules.append(istio_rule)
return auth_policy
async def get_effective_policy(self, src, dst) -> EffectiveRule:
"""Use Istio's pilot debug endpoint"""
response = await self._pilot_debug_query(src, dst)
return self._parse_effective_rules(response)
6. Complete Workflow
class PolicyCompiler:
def __init__(self, dsl_parser, conflict_detector,
rollout_controller, verifier, mesh_adapter):
self.parser = dsl_parser
self.conflicts = conflict_detector
self.rollout = rollout_controller
self.verifier = verifier
self.adapter = mesh_adapter
async def compile_and_deploy(self, dsl_content: str,
rollout_plan: Optional[RolloutPlan] = None):
"""Main compilation and deployment pipeline"""
# Phase 1: Parse & Normalize
intent = self.parser.parse(dsl_content)
normalized = self.parser.normalize(intent)
# Phase 2: Conflict Detection
conflicts = self.conflicts.detect_conflicts(normalized)
if conflicts:
raise PolicyConflictError(f"Found {len(conflicts)} conflicts", conflicts)
# Phase 3: Compile to IR
ir = self.parser.generate_ir(normalized)
# Phase 4: Target Mesh Compilation
mesh_policy = self.adapter.compile_policy(ir)
# Phase 5: Rollout Execution
if rollout_plan:
result = await self.rollout.execute_rollout(intent, rollout_plan)
if result.status == "FAILED":
return result
else:
# Direct deployment
await self.adapter.deploy_policy(mesh_policy)
# Phase 6: Verification
verification = await self.verifier.verify_policy(mesh_policy, intent)
if not verification.passed:
await self.adapter.rollback_policy(mesh_policy.id, "previous")
raise VerificationError("Policy verification failed", verification)
# Phase 7: Update State & Notify
self.state.update_deployed_policy(intent.name, mesh_policy, verification)
self.notifier.send_success(intent.name, verification.summary)
return DeploymentResult(
intent=intent.name,
status="SUCCESS",
verification=verification,
policy_id=mesh_policy.id
)
7. Key Data Structures
@dataclass
class Intent:
name: str
description: str
subject: SubjectSelector
target: TargetSelector
constraints: PolicyConstraints
resolution: ResolutionPolicy
rollout: RolloutMetadata
test_cases: List[TestCase] = None
@dataclass
class SubjectSelector:
services: List[str] # Service name patterns
namespaces: List[str]
principals: List[str] # SPIFFE, JWT, etc.
ip_blocks: List[str]
custom_attributes: Dict[str, str]
@dataclass
class TargetSelector:
services: List[str]
ports: List[int]
protocols: List[str]
resource_type: str # "service", "database", "queue"
@dataclass
class PolicyConstraints:
max_connections_per_second: Optional[int]
max_requests_per_second: Optional[int]
required_encryption: bool
allowed_time_window: Optional[str] # CRON expression
compliance_tag: Optional[str]
data_classification: Optional[str] # "public", "confidential", "restricted"
@dataclass
class Conflict:
type: ConflictType
intents: List[str]
description: str
severity: str # "CRITICAL", "HIGH", "MEDIUM", "LOW"
conflicting_rules: List[Rule]
resolution_hint: str
@dataclass
class VerificationReport:
intent_name: str
passed: bool
results: Dict[str, VerificationResult]
metrics: Dict[str, float]
compliance_status: Dict[str, bool]
execution_time: float
timestamp: datetime
8. Implementation Considerations
Performance Optimizations
- Incremental Compilation: Cache compiled policies and only recompile changed intents
- Parallel Conflict Detection: Use work-stealing for large policy sets
- Selective Verification: Only re-verify affected services during rollout
- Policy Diffing: Compute minimal policy changes between versions
Safety Features
- Policy Dry-Run Mode: Simulate changes without applying
- Automatic Rollback Triggers:
- SLA violations (latency > 200ms, error rate > 1%)
- Policy coverage gap (allowed traffic not matching any rule)
- Compliance violation detection
- Change Advisory Board (CAB) Integration: Require approvals for high-risk changes
- Shadow Mode: Apply policies in monitoring-only mode first
Observability
metrics:
- policy_compilation_duration_seconds
- conflicts_detected_total
- rollout_stages_completed
- verification_success_rate
- effective_policy_coverage
- policy_change_frequency
logging:
structured_logs: true
log_levels:
compiler: INFO
conflict_detector: DEBUG
rollout: INFO
verification: DEBUG
tracing:
enabled: true
sampling_rate: 0.1
attributes:
- intent_name
- policy_id
- conflict_type
- rollout_stage
Storage & State Management
class PolicyStateStore:
def __init__(self, etcd_client):
self.etcd = etcd_client
async def store_policy_version(self, intent_name: str,
policy: CompiledPolicy,
verification: VerificationReport):
"""Immutable versioned storage"""
version = self._generate_version()
key = f"/policies/{intent_name}/versions/{version}"
data = {
"policy": policy.to_dict(),
"verification": verification.to_dict(),
"timestamp": datetime.utcnow().isoformat(),
"status": "DEPLOYED" if verification.passed else "FAILED"
}
await self.etcd.put(key, json.dumps(data))
await self.etcd.put(f"/policies/{intent_name}/current", version)
async def get_effective_policy(self, source: str, dest: str) -> List[Rule]:
"""Query effective policy for traffic pattern"""
# Use etcd prefix scan for all active policies
# Merge according to conflict resolution strategy
# Return ordered list of applicable rules
pass
9. Sample Compilation Pipeline
# User writes intent
cat > intent.yaml <<EOF
intent "api-gateway-to-backend" {
subject: { services: ["api-gateway"] }
target: { services: ["backend-*"], ports: [8080, 8443] }
constraints: { required_tls: true, max_rps: 10000 }
}
EOF
# Compile with conflict detection and canary rollout
policy-compiler compile \
--intent intent.yaml \
--mesh istio \
--rollout-strategy canary \
--target-percentage 25 \
--auto-rollback \
--dry-run # Show what would be deployed
# Output:
# ✓ Syntax valid
# ✓ No conflicts detected (checked against 47 existing intents)
# ✓ Compiled to 3 Istio AuthorizationPolicy resources
# ✓ Canary rollout plan generated:
# Stage 1 (25%): Apply to namespace/canary-*
# Stage 2 (50%): Apply to namespace/staging-*, canary-*
# Stage 3 (100%): Apply to all namespaces
# ⚠ Verification required: 12 test cases generated
#
# To deploy: policy-compiler deploy --intent intent.yaml --rollout-plan canary
# After deployment verification
policy-compiler verify --intent api-gateway-to-backend
# ✓ All 12 tests passed
# ✓ Compliance: PCI-DSS satisfied
# ✓ Performance impact: +2ms latency (within threshold)
# ✓ Security score: 94/100
10. Extensibility Points
- Custom Conflict Rules: Plugins for domain-specific conflict detection
- Mesh Adapters: Implement interface for Linkerd, Consul, AWS App Mesh, etc.
- Verification Probes: Custom test types (gRPC, HTTP/2, database queries)
- Rollout Strategies: Implement blue-green, rolling, ring-based rollout
- Compliance Frameworks: Pre-built mappings for SOC2, HIPAA, GDPR
- ML-Based Anomaly Detection: Learn normal traffic patterns and flag deviations
This design provides:
- Expressive DSL for high-level intents with rich constraints
- Comprehensive conflict detection across semantic, capacity, and compliance dimensions
- Safe rollouts with canary analysis and automatic rollback
- Multi-layer verification from syntax to live traffic testing
- Mesh-agnostic architecture with adapter pattern
- Production-ready with observability, safety guards, and state management
The system enables declarative network policy management while maintaining strict safety and compliance guarantees required in enterprise service mesh environments.