Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor(region): replace ISO region hierarchy with generic attested labels
Antonio Ojeab96cd2dc2517
diff --git a/api/datalog.go b/api/datalog.goindex 6e3be2ec..bbcc4495 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -198,16 +198,17 @@ const (// Example Datalog: service("mcp", "calculator")FactService = "service"- // FactRegion is the control-plane-attested jurisdiction of the token's node,- // following the hierarchical model of region.go. The control plane mints one- // fact per hierarchy level (RegionPrefixes), so a requirement is a single- // exact match: a node attested as "EU-DE" carries region("EU") and- // region("EU-DE"), satisfying `check if region("EU")` but never a finer- // requirement it cannot guarantee. Distinct from LabelRegion, the- // unauthenticated gossip routing hint.- // Contains: biscuit.String(regionPrefix)- // Example Datalog: check if region("EU")- FactRegion = "region"+ // FactLabel is a control-plane-attested key=value label on the token's+ // node (see api/labels.go). The control plane mints one fact per+ // declared label, so a requirement is a single exact match: a node+ // attested with region="us-east-1" carries label("region", "us-east-1"),+ // satisfying `check if label("region", "us-east-1")` only — composition+ // across values is left entirely to the operator (attest as many labels+ // as needed). Distinct from LabelRegion, the unauthenticated gossip+ // routing hint.+ // Contains: biscuit.String(key), biscuit.String(value)+ // Example Datalog: check if label("region", "us-east-1")+ FactLabel = "label"// FactTime defines the current system time injected during evaluation.// Contains: biscuit.Date(currentTime)@@ -431,36 +432,51 @@ func BuildTargetDatalogFact(targetStr string) biscuit.Fact {}}}-// RegionFacts materializes a region claim as one Datalog fact per hierarchy-// level (see FactRegion and RegionPrefixes). An empty region returns nil.-func RegionFacts(region string) []biscuit.Fact {- prefixes := RegionPrefixes(region)- if len(prefixes) == 0 {+// LabelFacts materializes a label set as one Datalog fact per key=value+// pair (see FactLabel). Keys are sorted for deterministic fact ordering. An+// empty set returns nil.+func LabelFacts(labels map[string]string) []biscuit.Fact {+ if len(labels) == 0 {return nil}- facts := make([]biscuit.Fact, 0, len(prefixes))- for _, p := range prefixes {+ keys := make([]string, 0, len(labels))+ for k := range labels {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ facts := make([]biscuit.Fact, 0, len(labels))+ for _, k := range keys {facts = append(facts, biscuit.Fact{Predicate: biscuit.Predicate{- Name: FactRegion,- IDs: []biscuit.Term{biscuit.String(p)},+ Name: FactLabel,+ IDs: []biscuit.Term{biscuit.String(k), biscuit.String(labels[k])},}})}return facts}-// RegionCheck compiles required regions (canonical, pre-validated with-// ValidateRegion) into a single fail-closed check satisfied when the token-// carries any of them: `check if region("EU") or region("NA-US")`.-func RegionCheck(required []string) (biscuit.Check, error) {+// LabelCheck compiles a required label set (canonical, pre-validated with+// ValidateLabels) into a single fail-closed check satisfied when the token+// carries any of them: `check if label("region", "us-east-1") or+// label("team", "platform")`.+func LabelCheck(required map[string]string) (biscuit.Check, error) {if len(required) == 0 {- return biscuit.Check{}, fmt.Errorf("no required regions")+ return biscuit.Check{}, fmt.Errorf("no required labels")+ }+ keys := make([]string, 0, len(required))+ for k := range required {+ keys = append(keys, k)}+ sort.Strings(keys)clauses := make([]string, 0, len(required))- for _, r := range required {- if err := ValidateRegion(r); err != nil {+ for _, k := range keys {+ if err := ValidateLabelKey(k); err != nil {+ return biscuit.Check{}, err+ }+ v := required[k]+ if err := ValidateLabelValue(v); err != nil {return biscuit.Check{}, err}- clauses = append(clauses, fmt.Sprintf("%s(%q)", FactRegion, NormalizeRegion(r)))+ clauses = append(clauses, fmt.Sprintf("%s(%q, %q)", FactLabel, k, v))}return parser.FromStringCheck("check if " + strings.Join(clauses, " or "))}diff --git a/api/datalog_test.go b/api/datalog_test.goindex d2781793..f7fe7c91 100644--- a/api/datalog_test.go+++ b/api/datalog_test.go@@ -557,40 +557,40 @@ func TestBuildTargetDatalogFacts(t *testing.T) {}}-func TestRegionFactsAndCheck(t *testing.T) {+func TestLabelFactsAndCheck(t *testing.T) {pub, priv := makeKeyPair(t)- if facts := RegionFacts(""); facts != nil {- t.Errorf("RegionFacts(\"\") = %v, want nil", facts)+ if facts := LabelFacts(nil); facts != nil {+ t.Errorf("LabelFacts(nil) = %v, want nil", facts)}- if _, err := RegionCheck(nil); err == nil {- t.Error("RegionCheck(nil): expected error, got nil")+ if _, err := LabelCheck(nil); err == nil {+ t.Error("LabelCheck(nil): expected error, got nil")}- if _, err := RegionCheck([]string{"MARS"}); err == nil {- t.Error("RegionCheck(MARS): expected error, got nil")+ if _, err := LabelCheck(map[string]string{"region": "bad,value"}); err == nil {+ t.Error("LabelCheck(invalid value): expected error, got nil")}tests := []struct {name string- claimed string // minted into the token via RegionFacts- required []string+ claimed map[string]string // minted into the token via LabelFacts+ required map[string]stringexpectAllow bool}{- {"finer claim satisfies coarser requirement", "EU-DE-BY", []string{"EU"}, true},- {"exact level match", "EU-DE", []string{"EU-DE"}, true},- {"any-of requirement", "NA-US", []string{"EU", "NA-US"}, true},- {"lowercase requirement is normalized", "EU-DE", []string{"eu"}, true},- {"coarser claim never satisfies finer requirement", "EU", []string{"EU-DE"}, false},- {"disjoint region", "NA-US", []string{"EU"}, false},- {"unattested token fails closed", "", []string{"EU"}, false},+ {"exact match", map[string]string{"region": "us-east-1"}, map[string]string{"region": "us-east-1"}, true},+ {"any-of requirement", map[string]string{"region": "us-east-1"}, map[string]string{"region": "eu", "team": "us-east-1"}, false},+ {"any-of requirement matches one key", map[string]string{"region": "us-east-1", "team": "platform"}, map[string]string{"region": "eu", "team": "platform"}, true},+ {"case-sensitive value mismatch", map[string]string{"region": "us-east-1"}, map[string]string{"region": "US-EAST-1"}, false},+ {"no built-in hierarchy: coarser requirement does not match a finer claim", map[string]string{"region": "us-east-1"}, map[string]string{"region": "us"}, false},+ {"disjoint labels", map[string]string{"region": "us-east-1"}, map[string]string{"region": "eu-west-1"}, false},+ {"unattested token fails closed", nil, map[string]string{"region": "us-east-1"}, false},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {builder := biscuit.NewBuilder(priv)- for _, fact := range RegionFacts(tt.claimed) {+ for _, fact := range LabelFacts(tt.claimed) {if err := builder.AddAuthorityFact(fact); err != nil {- t.Fatalf("failed to add region fact: %v", err)+ t.Fatalf("failed to add label fact: %v", err)}}tok, err := builder.Build()@@ -602,9 +602,9 @@ func TestRegionFactsAndCheck(t *testing.T) {if err != nil {t.Fatalf("failed to create authorizer: %v", err)}- check, err := RegionCheck(tt.required)+ check, err := LabelCheck(tt.required)if err != nil {- t.Fatalf("RegionCheck(%v): %v", tt.required, err)+ t.Fatalf("LabelCheck(%v): %v", tt.required, err)}authorizer.AddCheck(check)authorizer.AddPolicy(AllowIfTruePolicy)diff --git a/api/labels.go b/api/labels.gonew file mode 100644index 00000000..4bb1c249--- /dev/null+++ b/api/labels.go@@ -0,0 +1,77 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package api++import (+ "fmt"+ "regexp"+ "strings"+)++// Labels are free-form, control-plane-attested key=value metadata a node's+// identity carries (e.g. region="us-east-1", team="platform"). Cloud+// providers, on-prem operators, and countries all name things differently,+// so SAM imposes no taxonomy or hierarchy on keys or values: composition+// (e.g. attesting both a precise and a coarser value so a coarser+// requirement also matches) is entirely up to the operator. Matching is+// exact and case-sensitive on both key and value (see LabelCheck).+//+// Well-known keys (e.g. LabelRegion) are just conventions; SAM does not+// validate or interpret their values beyond ValidateLabelValue.++// labelKeySyntax bounds label keys to a safe, portable charset.+var labelKeySyntax = regexp.MustCompile(`^[a-zA-Z0-9_.-]{1,63}$`)++// maxLabelValueLen bounds label values defensively; well within any+// realistic cloud region/zone or on-prem naming convention.+const maxLabelValueLen = 255++// ValidateLabelKey checks that a label key is well-formed: 1-63 characters+// from [a-zA-Z0-9_.-].+func ValidateLabelKey(key string) error {+ if !labelKeySyntax.MatchString(key) {+ return fmt.Errorf("invalid label key %q: must be 1-63 chars of [a-zA-Z0-9_.-]", key)+ }+ return nil+}++// ValidateLabelValue checks that a label value is well-formed: non-empty,+// bounded length, and free of characters that collide with the wire-format+// separators (comma-separated key=value pairs) or control characters.+func ValidateLabelValue(value string) error {+ if value == "" {+ return fmt.Errorf("label value must not be empty")+ }+ if len(value) > maxLabelValueLen {+ return fmt.Errorf("label value %q exceeds %d characters", value, maxLabelValueLen)+ }+ if strings.ContainsAny(value, ",=\n\r\t") {+ return fmt.Errorf("label value %q must not contain ',', '=', or control characters", value)+ }+ return nil+}++// ValidateLabels checks every key and value in a label set.+func ValidateLabels(labels map[string]string) error {+ for k, v := range labels {+ if err := ValidateLabelKey(k); err != nil {+ return err+ }+ if err := ValidateLabelValue(v); err != nil {+ return err+ }+ }+ return nil+}diff --git a/api/labels_test.go b/api/labels_test.gonew file mode 100644index 00000000..9f2e8027--- /dev/null+++ b/api/labels_test.go@@ -0,0 +1,67 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package api++import (+ "strings"+ "testing"+)++func TestValidateLabelKey(t *testing.T) {+ valid := []string{"region", "team", "cloud-region", "on_prem.zone", "A1"}+ for _, k := range valid {+ if err := ValidateLabelKey(k); err != nil {+ t.Errorf("ValidateLabelKey(%q): unexpected error: %v", k, err)+ }+ }++ invalid := []string{"", "has space", "has,comma", "has=equals", strings.Repeat("a", 64)}+ for _, k := range invalid {+ if err := ValidateLabelKey(k); err == nil {+ t.Errorf("ValidateLabelKey(%q): expected error, got nil", k)+ }+ }+}++func TestValidateLabelValue(t *testing.T) {+ valid := []string{"us-east-1", "EU-DE", "office-berlin", "rack.3", "123"}+ for _, v := range valid {+ if err := ValidateLabelValue(v); err != nil {+ t.Errorf("ValidateLabelValue(%q): unexpected error: %v", v, err)+ }+ }++ invalid := []string{"", "has,comma", "has=equals", "has\ttab", strings.Repeat("a", maxLabelValueLen+1)}+ for _, v := range invalid {+ if err := ValidateLabelValue(v); err == nil {+ t.Errorf("ValidateLabelValue(%q): expected error, got nil", v)+ }+ }+}++func TestValidateLabels(t *testing.T) {+ if err := ValidateLabels(nil); err != nil {+ t.Errorf("ValidateLabels(nil): unexpected error: %v", err)+ }+ if err := ValidateLabels(map[string]string{"region": "us-east-1", "team": "platform"}); err != nil {+ t.Errorf("ValidateLabels(valid): unexpected error: %v", err)+ }+ if err := ValidateLabels(map[string]string{"region": ""}); err == nil {+ t.Error("ValidateLabels(empty value): expected error, got nil")+ }+ if err := ValidateLabels(map[string]string{"bad key!": "v"}); err == nil {+ t.Error("ValidateLabels(bad key): expected error, got nil")+ }+}diff --git a/api/network.go b/api/network.goindex 2832b7d9..5daa0e6a 100644--- a/api/network.go+++ b/api/network.go@@ -109,17 +109,17 @@ const (// between a root path "/" and an empty path "".HeaderSamNoTrailingSlash = "X-Sam-No-Trailing-Slash"- // HeaderSamRequiredRegion constrains an inference request on the sidecar's- // OpenAI-compatible endpoints (/v1/*) to providers whose declared region is- // in the comma-separated list of continent codes (see ValidateRegion);- // invalid codes are rejected with HTTP 400. It can only narrow what mesh- // policy allows, never widen it. Absent means any region permitted by- // policy.+ // HeaderSamRequiredLabels constrains an inference request on the sidecar's+ // OpenAI-compatible endpoints (/v1/*) to providers attested with any of a+ // comma-separated list of "key=value" label requirements (see+ // api/labels.go and LabelCheck); invalid entries are rejected with HTTP+ // 400. It can only narrow what mesh policy allows, never widen it. Absent+ // means any provider permitted by policy.//// Reserved as part of the sidecar contract; enforced by the provider- // scorer. Region declarations are routing hints until attested via the+ // scorer. Label declarations are routing hints until attested via the// node's Biscuit (see LabelRegion).- HeaderSamRequiredRegion = "X-Sam-Required-Region"+ HeaderSamRequiredLabels = "X-Sam-Required-Labels")// ============================================================================@@ -132,12 +132,12 @@ const (// lives in the package that owns the behavior.const (- // LabelRegion is the operator-declared jurisdiction of a node, as a- // continent code validated by ValidateRegion (e.g. "EU"). It is carried in- // ServiceAnnounce messages as a routing hint. Absent means the node makes- // no region claim, and consumers with a region requirement will never- // select it. Operator-declared labels always take precedence over- // runtime-derived values.+ // LabelRegion is the operator-declared jurisdiction of a node, a+ // free-form value (e.g. "us-east-1", "EU-DE"); see api/labels.go. It is+ // carried in ServiceAnnounce messages as a routing hint. Absent means+ // the node makes no region claim, and consumers with a region+ // requirement will never select it. Operator-declared labels always+ // take precedence over runtime-derived values.LabelRegion = "region")diff --git a/api/region.go b/api/region.godeleted file mode 100644index 2fd6f568..00000000--- a/api/region.go+++ /dev/null@@ -1,144 +0,0 @@-// Copyright 2026 Google LLC-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package api--import (- "fmt"- "regexp"- "sort"- "strings"-)--// Region claims are hierarchical: CONTINENT[-COUNTRY[-ZONE]].-//-// - CONTINENT: two-letter continent code (seven-continent model, as used-// by geolocation databases): AF, AN, AS, EU, NA, OC, SA.-// - COUNTRY: ISO 3166-1 alpha-2 code, validated to belong to the claimed-// continent (transcontinental countries follow common-// geolocation-database convention, e.g. RU->EU, TR->AS, CY->EU).-// - ZONE: reserved extension for ISO 3166-2 subdivision codes (the part-// after the country prefix, e.g. "BY" in DE-BY); syntax-validated only.-//-// Examples: "EU", "EU-DE", "EU-DE-BY", "NA-US", "NA-US-CA".-//-// Matching is hierarchical and fail-closed: requiring "EU" matches a-// provider claiming "EU-DE"; requiring "EU-DE" does NOT match a provider-// claiming only "EU" (a coarser claim cannot guarantee the finer scope).-// The set is closed and validated: anything else is rejected at the boundary-// that receives it — node startup for --region, HTTP 400 for-// X-Sam-Required-Region, and dropped announcements on the gossip layer.-var continentNames = map[string]string{- "AF": "Africa",- "AN": "Antarctica",- "AS": "Asia",- "EU": "Europe",- "NA": "North America",- "OC": "Oceania",- "SA": "South America",-}--// countryContinent maps ISO 3166-1 alpha-2 codes to their continent.-var countryContinent = map[string]string{}--func init() {- byContinent := map[string]string{- "AF": "AO BF BI BJ BW CD CF CG CI CM CV DJ DZ EG EH ER ET GA GH GM GN GQ GW KE KM LR LS LY MA MG ML MR MU MW MZ NA NE NG RE RW SC SD SH SL SN SO SS ST SZ TD TG TN TZ UG YT ZA ZM ZW",- "AN": "AQ BV GS HM TF",- "AS": "AE AF AM AZ BD BH BN BT CN GE HK ID IL IN IO IQ IR JO JP KG KH KP KR KW KZ LA LB LK MM MN MO MV MY NP OM PH PK PS QA SA SG SY TH TJ TL TM TR TW UZ VN YE",- "EU": "AD AL AT AX BA BE BG BY CH CY CZ DE DK EE ES FI FO FR GB GG GI GR HR HU IE IM IS IT JE LI LT LU LV MC MD ME MK MT NL NO PL PT RO RS RU SE SI SJ SK SM UA VA",- "NA": "AG AI AW BB BL BM BQ BS BZ CA CR CU CW DM DO GD GL GP GT HN HT JM KN KY LC MF MQ MS MX NI PA PM PR SV SX TC TT UM US VC VG VI",- "OC": "AS AU CC CK CX FJ FM GU KI MH MP NC NF NR NU NZ PF PG PN PW SB TK TO TV VU WF WS",- "SA": "AR BO BR CL CO EC FK GF GY PE PY SR UY VE",- }- for continent, list := range byContinent {- for _, cc := range strings.Fields(list) {- countryContinent[cc] = continent- }- }-}--// zoneSyntax is the ISO 3166-2 subdivision code part (after the country-// prefix): one to three letters or digits.-var zoneSyntax = regexp.MustCompile(`^[A-Z0-9]{1,3}$`)--// NormalizeRegion canonicalizes a region claim for comparison: uppercase,-// surrounding whitespace ignored. Every boundary that emits or matches a-// region value must apply it.-func NormalizeRegion(s string) string {- return strings.ToUpper(strings.TrimSpace(s))-}--// ValidateRegion checks that s (after normalization) is a well-formed region-// claim per the CONTINENT[-COUNTRY[-ZONE]] hierarchy. The empty string is-// not valid: callers decide whether an absent claim is allowed.-func ValidateRegion(s string) error {- parts := strings.Split(NormalizeRegion(s), "-")- if len(parts) > 3 {- return fmt.Errorf("invalid region %q: at most CONTINENT-COUNTRY-ZONE", s)- }- if _, ok := continentNames[parts[0]]; !ok {- return fmt.Errorf("invalid region %q: continent must be one of %s", s, strings.Join(ContinentCodes(), ", "))- }- if len(parts) >= 2 {- continent, ok := countryContinent[parts[1]]- if !ok {- return fmt.Errorf("invalid region %q: %q is not an ISO 3166-1 alpha-2 country code", s, parts[1])- }- if continent != parts[0] {- return fmt.Errorf("invalid region %q: country %s belongs to continent %s", s, parts[1], continent)- }- }- if len(parts) == 3 && !zoneSyntax.MatchString(parts[2]) {- return fmt.Errorf("invalid region %q: zone must be 1-3 letters or digits (ISO 3166-2)", s)- }- return nil-}--// RegionMatches reports whether a provider's claimed region satisfies a-// required region: exact match or the claim is a finer scope within the-// requirement. A claim coarser than the requirement never matches.-// Both values must be in canonical form (NormalizeRegion).-func RegionMatches(required, claimed string) bool {- return claimed == required || strings.HasPrefix(claimed, required+"-")-}--// RegionPrefixes returns the hierarchy prefix closure of a region claim in-// canonical form, coarsest first: "EU-DE-BY" -> ["EU", "EU-DE", "EU-DE-BY"].-// Materializing every level lets policies match a requirement with a single-// exact fact lookup (see FactRegion) while keeping RegionMatches semantics:-// a finer claim carries its coarser prefixes, a coarser claim never gains-// finer ones. The empty string returns nil.-func RegionPrefixes(s string) []string {- s = NormalizeRegion(s)- if s == "" {- return nil- }- parts := strings.Split(s, "-")- out := make([]string, 0, len(parts))- for i := range parts {- out = append(out, strings.Join(parts[:i+1], "-"))- }- return out-}--// ContinentCodes returns the valid continent codes, sorted.-func ContinentCodes() []string {- codes := make([]string, 0, len(continentNames))- for c := range continentNames {- codes = append(codes, c)- }- sort.Strings(codes)- return codes-}diff --git a/api/region_test.go b/api/region_test.godeleted file mode 100644index 753addc1..00000000--- a/api/region_test.go+++ /dev/null@@ -1,97 +0,0 @@-// Copyright 2026 Google LLC-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package api--import "testing"--func TestValidateRegion(t *testing.T) {- valid := []string{- "EU", "eu", " Eu ", // continent, any case- "EU-DE", "NA-US", "AS-JP", "EU-RU", "AS-TR", // countries in their continent- "EU-DE-BY", "NA-US-CA", "NA-US-123", // zone extension, syntax only- }- for _, s := range valid {- if err := ValidateRegion(s); err != nil {- t.Errorf("ValidateRegion(%q): unexpected error: %v", s, err)- }- }-- invalid := []string{- "", // absent is the caller's decision, not a valid claim- "MARS", "X", "EUR", // not a continent code- "EU-XX", // not an ISO 3166-1 country- "EU-US", "NA-DE", // country outside its continent- "US", // country without its continent prefix- "EU-DE-TOOLONG", // zone syntax violation- "EU-DE-BY-1", // too many segments- "EU_DE", "EU DE", // wrong separator- }- for _, s := range invalid {- if err := ValidateRegion(s); err == nil {- t.Errorf("ValidateRegion(%q): expected error, got nil", s)- }- }-}--func TestRegionMatches(t *testing.T) {- tests := []struct {- required, claimed string- want bool- }{- {"EU", "EU", true},- {"EU", "EU-DE", true}, // finer claim satisfies coarser requirement- {"EU", "EU-DE-BY", true}, // transitively- {"EU-DE", "EU-DE-BY", true}, // zone within required country- {"EU-DE", "EU", false}, // coarser claim never satisfies finer requirement- {"EU-DE", "EU-FR", false},- {"EU", "NA", false},- {"EU", "", false}, // unlabeled never matches- }- for _, tt := range tests {- if got := RegionMatches(tt.required, tt.claimed); got != tt.want {- t.Errorf("RegionMatches(%q, %q) = %v, want %v", tt.required, tt.claimed, got, tt.want)- }- }-}--func TestNormalizeRegion(t *testing.T) {- if got := NormalizeRegion(" eu-de "); got != "EU-DE" {- t.Errorf("NormalizeRegion: got %q, want EU-DE", got)- }-}--func TestRegionPrefixes(t *testing.T) {- tests := []struct {- in string- want []string- }{- {"", nil},- {"EU", []string{"EU"}},- {"eu-de", []string{"EU", "EU-DE"}}, // normalized- {"EU-DE-BY", []string{"EU", "EU-DE", "EU-DE-BY"}},- }- for _, tt := range tests {- got := RegionPrefixes(tt.in)- if len(got) != len(tt.want) {- t.Errorf("RegionPrefixes(%q) = %v, want %v", tt.in, got, tt.want)- continue- }- for i := range got {- if got[i] != tt.want[i] {- t.Errorf("RegionPrefixes(%q)[%d] = %q, want %q", tt.in, i, got[i], tt.want[i])- }- }- }-}diff --git a/api/sam.pb.go b/api/sam.pb.goindex e3bdc292..0aadd3f3 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -379,11 +379,11 @@ type EnrollRequest struct {PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`PublicKey []byte `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`RequestedRole string `protobuf:"bytes,4,opt,name=requested_role,json=requestedRole,proto3" json:"requested_role,omitempty"`- // Operator-declared region claim (CONTINENT[-COUNTRY[-ZONE]], see- // api/region.go). Validated fail-closed by the control plane and, once- // attested by the enrollment flow's gates, minted as signed region()- // facts in the biscuit. Empty means no claim.- Region string `protobuf:"bytes,5,opt,name=region,proto3" json:"region,omitempty"`+ // Operator-declared labels (e.g. key "region", see api/labels.go).+ // Validated fail-closed by the control plane and, once attested by the+ // enrollment flow's gates, minted as signed label() facts in the+ // biscuit. Empty means no claims.+ Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -446,11 +446,11 @@ func (x *EnrollRequest) GetRequestedRole() string {return ""}-func (x *EnrollRequest) GetRegion() string {+func (x *EnrollRequest) GetLabels() map[string]string {if x != nil {- return x.Region+ return x.Labels}- return ""+ return nil}type EnrollResponse struct {@@ -579,9 +579,9 @@ type BootstrapEnrollRequest struct {PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`PublicKey []byte `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`RequestedRole string `protobuf:"bytes,4,opt,name=requested_role,json=requestedRole,proto3" json:"requested_role,omitempty"`- // Operator-declared region claim; the admin approving the enrollment- // attests it (see EnrollRequest.region).- Region string `protobuf:"bytes,5,opt,name=region,proto3" json:"region,omitempty"`+ // Operator-declared labels; the admin approving the enrollment attests+ // them (see EnrollRequest.labels).+ Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -644,11 +644,11 @@ func (x *BootstrapEnrollRequest) GetRequestedRole() string {return ""}-func (x *BootstrapEnrollRequest) GetRegion() string {+func (x *BootstrapEnrollRequest) GetLabels() map[string]string {if x != nil {- return x.Region+ return x.Labels}- return ""+ return nil}type BootstrapEnrollResponse struct {@@ -1912,14 +1912,17 @@ const file_api_sam_proto_rawDesc = "" +"\n" +"\x06BANNED\x10\x00\x12\x10\n" +"\fKEY_ROTATION\x10\x01\x12\x11\n" +- "\rPOLICY_UPDATE\x10\x02\"\x98\x01\n" ++ "\rPOLICY_UPDATE\x10\x02\"\xf6\x01\n" +"\rEnrollRequest\x12\x10\n" +"\x03jwt\x18\x01 \x01(\tR\x03jwt\x12\x17\n" +"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +"\n" +"public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +- "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\x12\x16\n" +- "\x06region\x18\x05 \x01(\tR\x06region\"\xde\x01\n" ++ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\x129\n" ++ "\x06labels\x18\x05 \x03(\v2!.sam.v1.EnrollRequest.LabelsEntryR\x06labels\x1a9\n" ++ "\vLabelsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xde\x01\n" +"\x0eEnrollResponse\x12#\n" +"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +"\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x127\n" +@@ -1929,14 +1932,17 @@ const file_api_sam_proto_rawDesc = "" +"expiration\x18\x05 \x01(\x03R\n" +"expiration\"2\n" +"\x17EnrollmentStatusRequest\x12\x17\n" +- "\apeer_id\x18\x01 \x01(\tR\x06peerId\"\xb8\x01\n" ++ "\apeer_id\x18\x01 \x01(\tR\x06peerId\"\x9f\x02\n" +"\x16BootstrapEnrollRequest\x12'\n" +"\x0fbootstrap_token\x18\x01 \x01(\tR\x0ebootstrapToken\x12\x17\n" +"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +"\n" +"public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +- "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\x12\x16\n" +- "\x06region\x18\x05 \x01(\tR\x06region\"\xcd\x02\n" ++ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\x12B\n" ++ "\x06labels\x18\x05 \x03(\v2*.sam.v1.BootstrapEnrollRequest.LabelsEntryR\x06labels\x1a9\n" ++ "\vLabelsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xcd\x02\n" +"\x17BootstrapEnrollResponse\x120\n" +"\x06status\x18\x01 \x01(\x0e2\x18.sam.v1.EnrollmentStatusR\x06status\x12#\n" +"\rbiscuit_token\x18\x02 \x01(\fR\fbiscuitToken\x122\n" +@@ -2055,7 +2061,7 @@ func file_api_sam_proto_rawDescGZIP() []byte {}var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 3)-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 29)+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 31)var file_api_sam_proto_goTypes = []any{(EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus(ServiceType)(0), // 1: sam.v1.ServiceType@@ -2087,27 +2093,31 @@ var file_api_sam_proto_goTypes = []any{(*TokenRefreshResponse)(nil), // 27: sam.v1.TokenRefreshResponse(*TokenRevokeRequest)(nil), // 28: sam.v1.TokenRevokeRequest(*TokenRevokeResponse)(nil), // 29: sam.v1.TokenRevokeResponse- nil, // 30: sam.v1.CommandBackend.EnvEntry- nil, // 31: sam.v1.ServiceAnnounce.LabelsEntry+ nil, // 30: sam.v1.EnrollRequest.LabelsEntry+ nil, // 31: sam.v1.BootstrapEnrollRequest.LabelsEntry+ nil, // 32: sam.v1.CommandBackend.EnvEntry+ nil, // 33: sam.v1.ServiceAnnounce.LabelsEntry}var file_api_sam_proto_depIdxs = []int32{2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type- 0, // 1: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus- 1, // 2: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType- 30, // 3: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry- 11, // 4: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo- 12, // 5: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend- 1, // 6: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType- 31, // 7: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry- 19, // 8: sam.v1.PolicyConfigGetResponse.roles:type_name -> sam.v1.PolicyRole- 20, // 9: sam.v1.PolicyConfigGetResponse.bindings:type_name -> sam.v1.PolicyBinding- 19, // 10: sam.v1.PolicyConfigUpdateRequest.roles:type_name -> sam.v1.PolicyRole- 20, // 11: sam.v1.PolicyConfigUpdateRequest.bindings:type_name -> sam.v1.PolicyBinding- 12, // [12:12] is the sub-list for method output_type- 12, // [12:12] is the sub-list for method input_type- 12, // [12:12] is the sub-list for extension type_name- 12, // [12:12] is the sub-list for extension extendee- 0, // [0:12] is the sub-list for field type_name+ 30, // 1: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry+ 31, // 2: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry+ 0, // 3: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus+ 1, // 4: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType+ 32, // 5: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry+ 11, // 6: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo+ 12, // 7: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend+ 1, // 8: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType+ 33, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry+ 19, // 10: sam.v1.PolicyConfigGetResponse.roles:type_name -> sam.v1.PolicyRole+ 20, // 11: sam.v1.PolicyConfigGetResponse.bindings:type_name -> sam.v1.PolicyBinding+ 19, // 12: sam.v1.PolicyConfigUpdateRequest.roles:type_name -> sam.v1.PolicyRole+ 20, // 13: sam.v1.PolicyConfigUpdateRequest.bindings:type_name -> sam.v1.PolicyBinding+ 14, // [14:14] is the sub-list for method output_type+ 14, // [14:14] is the sub-list for method input_type+ 14, // [14:14] is the sub-list for extension type_name+ 14, // [14:14] is the sub-list for extension extendee+ 0, // [0:14] is the sub-list for field type_name}func init() { file_api_sam_proto_init() }@@ -2125,7 +2135,7 @@ func file_api_sam_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),NumEnums: 3,- NumMessages: 29,+ NumMessages: 31,NumExtensions: 0,NumServices: 0,},diff --git a/api/sam.proto b/api/sam.protoindex 8c21e23e..ed0d869c 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -49,11 +49,11 @@ message EnrollRequest {string peer_id = 2;bytes public_key = 3;string requested_role = 4;- // Operator-declared region claim (CONTINENT[-COUNTRY[-ZONE]], see- // api/region.go). Validated fail-closed by the control plane and, once- // attested by the enrollment flow's gates, minted as signed region()- // facts in the biscuit. Empty means no claim.- string region = 5;+ // Operator-declared labels (e.g. key "region", see api/labels.go).+ // Validated fail-closed by the control plane and, once attested by the+ // enrollment flow's gates, minted as signed label() facts in the+ // biscuit. Empty means no claims.+ map<string, string> labels = 5;}message EnrollResponse {@@ -80,9 +80,9 @@ message BootstrapEnrollRequest {string peer_id = 2;bytes public_key = 3;string requested_role = 4;- // Operator-declared region claim; the admin approving the enrollment- // attests it (see EnrollRequest.region).- string region = 5;+ // Operator-declared labels; the admin approving the enrollment attests+ // them (see EnrollRequest.labels).+ map<string, string> labels = 5;}message BootstrapEnrollResponse {diff --git a/api/validation.go b/api/validation.goindex 4ccd0a16..bd8b879c 100644--- a/api/validation.go+++ b/api/validation.go@@ -44,11 +44,6 @@ func ValidateServiceAnnounce(a *ServiceAnnounce) error {return fmt.Errorf("invalid label %q", k)}}- if region, ok := a.GetLabels()[LabelRegion]; ok {- if err := ValidateRegion(region); err != nil {- return err- }- }if a.GetTimestamp() <= 0 {return fmt.Errorf("missing timestamp")}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex 8d827fd7..dfedae7f 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -83,7 +83,7 @@ var (apiTokenPathFlag stringbootstrapTokenPathFlag stringclientSecretPathFlag string- regionFlag string+ labelsFlag stringtlsCertFlag stringtlsKeyFlag stringtlsCAFlag string@@ -120,6 +120,27 @@ func resolveDaemonSecret(name, path, envVar string) string {return secret}+// parseLabelsFlag parses a comma-separated "key=value" list (see+// api/labels.go) into a label map; an empty string means no claims.+func parseLabelsFlag(s string) (map[string]string, error) {+ if s == "" {+ return nil, nil+ }+ labels := make(map[string]string)+ for _, part := range strings.Split(s, ",") {+ part = strings.TrimSpace(part)+ if part == "" {+ continue+ }+ k, v, ok := strings.Cut(part, "=")+ if !ok {+ return nil, fmt.Errorf("invalid label %q: expected key=value", part)+ }+ labels[strings.TrimSpace(k)] = strings.TrimSpace(v)+ }+ return labels, nil+}+func main() {rootCmd := &cobra.Command{Use: "sam-node",@@ -156,6 +177,10 @@ func main() {if jwtFlag != "" {logger.Warn("--jwt passes a secret on the command line; prefer --jwt-path")}+ labels, err := parseLabelsFlag(labelsFlag)+ if err != nil {+ logger.Fatalf("Invalid --labels: %v", err)+ }store, err := node.NewStore(resolveDataDir())if err != nil {@@ -265,7 +290,7 @@ func main() {AutoRelayBackoff: autoRelayBackoffFlag,RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,- Region: regionFlag,+ Labels: labels,PolicySyncInterval: policySyncIntervalFlag,DHTProviderAddrTTL: dhtProviderAddrTTLFlag,DHTMaxRecordAge: dhtMaxRecordAgeFlag,@@ -331,7 +356,7 @@ func main() {AutoRelayBackoff: autoRelayBackoffFlag,RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,- Region: regionFlag,+ Labels: labels,PolicySyncInterval: policySyncIntervalFlag,DHTProviderAddrTTL: dhtProviderAddrTTLFlag,DHTMaxRecordAge: dhtMaxRecordAgeFlag,@@ -394,7 +419,7 @@ func main() {AutoRelayBackoff: autoRelayBackoffFlag,RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,- Region: regionFlag,+ Labels: labels,PolicySyncInterval: policySyncIntervalFlag,})if err != nil {@@ -541,6 +566,11 @@ func main() {}}+ labels, err := parseLabelsFlag(labelsFlag)+ if err != nil {+ logger.Fatalf("Invalid --labels: %v", err)+ }+priv := node.GetOrGenerateKey(store)meshNode, err := node.NewSamNode(node.Options{PrivKey: priv,@@ -560,7 +590,7 @@ func main() {AutoRelayBackoff: 3 * time.Second,RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,- Region: regionFlag,+ Labels: labels,PolicySyncInterval: policySyncIntervalFlag,})if err != nil {@@ -619,7 +649,7 @@ func main() {joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")joinCmd.Flags().StringVar(&bootstrapTokenPathFlag, "bootstrap-token-path", "", "Path to file containing the bootstrap token (recommended over --bootstrap-token)")runCmd.Flags().StringVar(&apiTokenPathFlag, "api-token-path", "", "Path to file containing the static Bearer token for API authorization (or env SAM_API_TOKEN)")- runCmd.Flags().StringVar(®ionFlag, "region", "", "Operator-declared region of this node: CONTINENT[-COUNTRY[-ZONE]] per ISO 3166 (e.g. \"EU\", \"EU-DE\", \"NA-US-CA\"); empty means no claim")+ runCmd.Flags().StringVar(&labelsFlag, "labels", "", "Operator-declared key=value labels of this node, comma-separated (e.g. \"region=us-east-1,team=platform\"); empty means no claims")runCmd.Flags().StringVar(&tlsCertFlag, "tls-cert", "", "Path to TLS certificate for sidecar API")runCmd.Flags().StringVar(&tlsKeyFlag, "tls-key", "", "Path to TLS key for sidecar API")runCmd.Flags().StringVar(&tlsCAFlag, "tls-ca", "", "Path to TLS CA for sidecar API mTLS")diff --git a/internal/controlplane/policy_scale_test.go b/internal/controlplane/policy_scale_test.goindex 658f2d0e..3dc277c9 100644--- a/internal/controlplane/policy_scale_test.go+++ b/internal/controlplane/policy_scale_test.go@@ -114,7 +114,7 @@ func TestPolicyScale(t *testing.T) {}start = time.Now()- biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), roleNames, roles, "")+ biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), roleNames, roles, nil)mintDur := time.Since(start)if err != nil {t.Fatalf("mint failed at n=%d: %v", n, err)@@ -200,7 +200,7 @@ func TestPolicyScaleSetEncoding(t *testing.T) {claims := jwt.MapClaims{}start := time.Now()- biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), []string{"bulk-role"}, roles, "")+ biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), []string{"bulk-role"}, roles, nil)mintDur := time.Since(start)if err != nil {t.Fatalf("mint failed at n=%d exact entries: %v", n, err)@@ -319,7 +319,7 @@ func TestPolicyScaleManyRoles(t *testing.T) {claims := jwt.MapClaims{}start := time.Now()- biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), roleNames, roles, "")+ biscuitBytes, _, err := identity.MintBiscuitToken(priv, claims, nil, nodePeer, time.Now().Add(time.Hour), roleNames, roles, nil)mintDur := time.Since(start)if err != nil {t.Fatalf("mint failed at n=%d matched roles: %v", n, err)diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 3126fa51..845e88f1 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -448,14 +448,11 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {return}- // Fail closed on malformed region claims; canonical form is what gets- // attested into the biscuit and persisted for refreshes.- region := api.NormalizeRegion(req.Region)- if region != "" {- if err := api.ValidateRegion(region); err != nil {- http.Error(w, "Invalid region: "+err.Error(), http.StatusBadRequest)- return- }+ // Fail closed on malformed labels; they get attested into the biscuit+ // and persisted for refreshes.+ if err := api.ValidateLabels(req.Labels); err != nil {+ http.Error(w, "Invalid labels: "+err.Error(), http.StatusBadRequest)+ return}policyRoles, bindings, err := s.store.GetMeshPolicy(ctx)@@ -495,7 +492,7 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {// Mint tokenbiscuitExpiry := time.Now().Add(api.BiscuitTokenTTL)- biscuitData, _, err := identity.MintBiscuitToken(privKey, claims, token, pID, biscuitExpiry, finalRoles, policyRoles, region)+ biscuitData, _, err := identity.MintBiscuitToken(privKey, claims, token, pID, biscuitExpiry, finalRoles, policyRoles, req.Labels)if err != nil {logger.Errorw("Biscuit minting failed", "peer_id", req.PeerId, "error", err)http.Error(w, "Failed to mint biscuit: "+err.Error(), http.StatusForbidden)@@ -520,7 +517,7 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {Role: primaryRole,EnrollmentType: "OIDC",ClaimsJSON: string(claimsBytes),- Region: region,+ Labels: req.Labels,EnrolledAt: time.Now(),ExpiresAt: sessionExpiresAt,}@@ -711,7 +708,7 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {finalRoles := []string{nodeRecord.Role}finalRoles = append(finalRoles, customAccessRoles...)- bBytes, _, err := identity.MintBiscuitToken(privKey, claims, nil, pID, biscuitExpiry, finalRoles, policyRoles, nodeRecord.Region)+ bBytes, _, err := identity.MintBiscuitToken(privKey, claims, nil, pID, biscuitExpiry, finalRoles, policyRoles, nodeRecord.Labels)if err != nil {logger.Errorf("Failed to mint refreshed token for node %s: %v", nodeRecord.PeerID, err)http.Error(w, "Internal server error", http.StatusInternalServerError)@@ -720,7 +717,7 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {biscuitBytes = bBytes} else {// Bootstrap node- bBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, nodeRecord.Role, biscuitExpiry, policyRoles, nodeRecord.Region)+ bBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, nodeRecord.Role, biscuitExpiry, policyRoles, nodeRecord.Labels)if err != nil {logger.Errorf("Failed to mint refreshed token for node %s: %v", nodeRecord.PeerID, err)http.Error(w, "Internal server error", http.StatusInternalServerError)@@ -1113,12 +1110,9 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {return}- region := api.NormalizeRegion(req.Region)- if region != "" {- if err := api.ValidateRegion(region); err != nil {- s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Invalid region: "+err.Error())- return- }+ if err := api.ValidateLabels(req.Labels); err != nil {+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Invalid labels: "+err.Error())+ return}pID, err := peer.Decode(req.PeerId)@@ -1160,7 +1154,7 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {PublicKey: req.PublicKey,TokenID: tokenRecord.ID,Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING,- Region: region,+ Labels: req.Labels,CreatedAt: time.Now(),}@@ -1182,7 +1176,7 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {http.Error(w, "Internal server error", http.StatusInternalServerError)return}- biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(api.BiscuitTokenTTL), policyRoles, region)+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(api.BiscuitTokenTTL), policyRoles, req.Labels)if err != nil {logger.Errorf("Failed to mint bootstrap biscuit: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)@@ -1207,7 +1201,7 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {Biscuit: biscuitBytes,Role: tokenRecord.Role,EnrollmentType: "BOOTSTRAP",- Region: region,+ Labels: req.Labels,EnrolledAt: time.Now(),ExpiresAt: time.Time{},}@@ -1532,9 +1526,9 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Requhttp.Error(w, "Internal server error", http.StatusInternalServerError)return}- // Admin approval is the attestation of the operator-declared region+ // Admin approval is the attestation of the operator-declared labels// recorded on the pending request.- biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(api.BiscuitTokenTTL), policyRoles, enrollReq.Region)+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(api.BiscuitTokenTTL), policyRoles, enrollReq.Labels)if err != nil {logger.Errorf("Failed to mint bootstrap biscuit: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)@@ -1554,7 +1548,7 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.RequBiscuit: biscuitBytes,Role: tokenRecord.Role,EnrollmentType: "BOOTSTRAP",- Region: enrollReq.Region,+ Labels: enrollReq.Labels,EnrolledAt: time.Now(),ExpiresAt: time.Time{},}diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex 7e389092..48cab2ff 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -32,20 +32,20 @@ import ()// MintBiscuitToken generates a signed Biscuit token for a peer with policy rules based on JWT claims.-// region is the control-plane-attested region claim (canonical, pre-validated); empty means no claim.-func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID, biscuitExpiry time.Time, roles []string, policyRoles []*api.PolicyRole, region string) ([]byte, []string, error) {+// labels are control-plane-attested key=value claims (canonical, pre-validated); empty means no claims.+func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID, biscuitExpiry time.Time, roles []string, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, []string, error) {if claims == nil {return nil, nil, fmt.Errorf("claims cannot be nil")}- biscuitBytes, err := mintBiscuit(signingKey, remotePeer, roles, biscuitExpiry, claims, policyRoles, region)+ biscuitBytes, err := mintBiscuit(signingKey, remotePeer, roles, biscuitExpiry, claims, policyRoles, labels)if err != nil {return nil, nil, err}return biscuitBytes, roles, nil}-func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, region string) ([]byte, error) {+func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, error) {builder := biscuit.NewBuilder(signingKey)addedFacts := make(map[string]bool)addFact := func(fact biscuit.Fact) error {@@ -81,11 +81,11 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []strireturn nil, fmt.Errorf("failed to add client_peer_id fact: %w", err)}- // One signed fact per hierarchy level so a requirement is a single exact- // match (see api.FactRegion).- for _, fact := range api.RegionFacts(region) {+ // One signed fact per declared label so a requirement is a single exact+ // match (see api.FactLabel).+ for _, fact := range api.LabelFacts(labels) {if err := addFact(fact); err != nil {- return nil, fmt.Errorf("failed to add region fact: %w", err)+ return nil, fmt.Errorf("failed to add label fact: %w", err)}}@@ -343,9 +343,9 @@ func toStringSlice(val any) []string {}// MintBootstrapBiscuitToken generates a signed Biscuit token for a peer using a bootstrap role.-// region is the control-plane-attested region claim (canonical, pre-validated); empty means no claim.-func MintBootstrapBiscuitToken(signingKey ed25519.PrivateKey, remotePeer peer.ID, role string, expiration time.Time, policyRoles []*api.PolicyRole, region string) ([]byte, error) {- return mintBiscuit(signingKey, remotePeer, []string{role}, expiration, nil, policyRoles, region)+// labels are control-plane-attested key=value claims (canonical, pre-validated); empty means no claims.+func MintBootstrapBiscuitToken(signingKey ed25519.PrivateKey, remotePeer peer.ID, role string, expiration time.Time, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, error) {+ return mintBiscuit(signingKey, remotePeer, []string{role}, expiration, nil, policyRoles, labels)}// VerifyAndExtractPeerID checks that the biscuit is signed by one of the trusted keys and returns the peer ID.diff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.goindex 0e8a3081..caf89bd7 100644--- a/internal/identity/biscuit_test.go+++ b/internal/identity/biscuit_test.go@@ -71,7 +71,7 @@ func TestVerifyBiscuit_Expiration(t *testing.T) {"roles": []any{"admin"},}- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin"}, nil, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin"}, nil, nil)if err != nil {t.Fatalf("MintBiscuitToken failed: %v", err)}@@ -112,7 +112,7 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) {"groups": []any{"beta-testers", "engineering"},}- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, nil, nil, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, nil, nil, nil)if err != nil {t.Fatalf("Failed to mint biscuit: %v", err)}@@ -202,7 +202,7 @@ func TestVerifyBiscuit_Concurrent(t *testing.T) {"roles": []any{"admin"},}- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin"}, nil, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin"}, nil, nil)if err != nil {t.Fatalf("MintBiscuitToken failed: %v", err)}@@ -250,7 +250,7 @@ func TestMintBiscuitToken(t *testing.T) {"groups": []any{"group1", "group2"},"roles": []any{"admin", "user"},}- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin", "user"}, nil, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"admin", "user"}, nil, nil)if err != nil {t.Fatal(err)}@@ -349,7 +349,7 @@ func TestMintBiscuitToken_VariousClaimsTypes(t *testing.T) {claims["groups"] = tt.groupsClaim}- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, tt.expectedRoles, nil, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, tt.expectedRoles, nil, nil)if err != nil {t.Fatalf("MintBiscuitToken failed: %v", err)}@@ -428,7 +428,7 @@ func TestMintBiscuitToken_WithPolicyRoles(t *testing.T) {}t.Run("Mint with matching policy role", func(t *testing.T) {- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"data-scientist"}, policyRoles, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"data-scientist"}, policyRoles, nil)if err != nil {t.Fatalf("MintBiscuitToken failed: %v", err)}@@ -457,7 +457,7 @@ func TestMintBiscuitToken_WithPolicyRoles(t *testing.T) {})t.Run("Mint with unmapped role when policy exists", func(t *testing.T) {- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"unmapped-role"}, policyRoles, "")+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, token.Expiry, []string{"unmapped-role"}, policyRoles, nil)if err != nil {t.Fatalf("MintBiscuitToken failed: %v", err)}@@ -484,14 +484,15 @@ func TestMintBiscuitToken_WithPolicyRoles(t *testing.T) {})}-func TestMintBiscuitToken_RegionFacts(t *testing.T) {+func TestMintBiscuitToken_LabelFacts(t *testing.T) {pub, priv, err := ed25519.GenerateKey(rand.Reader)if err != nil {t.Fatal(err)}dummyPeer := peer.ID("dummy-peer-region")- biscuitData, err := MintBootstrapBiscuitToken(priv, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, "EU-DE-BY")+ labels := map[string]string{"region": "eu-de", "team": "platform"}+ biscuitData, err := MintBootstrapBiscuitToken(priv, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, labels)if err != nil {t.Fatalf("MintBootstrapBiscuitToken failed: %v", err)}@@ -500,27 +501,27 @@ func TestMintBiscuitToken_RegionFacts(t *testing.T) {t.Fatalf("Unmarshal biscuit failed: %v", err)}- // Every hierarchy level is present as its own fact.- for _, region := range []string{"EU", "EU-DE", "EU-DE-BY"} {+ // Every declared label is present as its own fact.+ for k, v := range labels {authorizer, err := b.Authorizer(pub)if err != nil {t.Fatalf("Authorizer failed: %v", err)}authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{- {Body: []biscuit.Predicate{{Name: api.FactRegion, IDs: []biscuit.Term{biscuit.String(region)}}}},+ {Body: []biscuit.Predicate{{Name: api.FactLabel, IDs: []biscuit.Term{biscuit.String(k), biscuit.String(v)}}}},}})authorizer.AddPolicy(api.AllowIfTruePolicy)if err := authorizer.Authorize(); err != nil {- t.Errorf("expected region(%q) fact, got error: %v", region, err)+ t.Errorf("expected label(%q, %q) fact, got error: %v", k, v, err)}}- // No region facts when minted without a claim.- noRegionData, err := MintBootstrapBiscuitToken(priv, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, "")+ // No label facts when minted without any claims.+ noLabelsData, err := MintBootstrapBiscuitToken(priv, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, nil)if err != nil {t.Fatalf("MintBootstrapBiscuitToken failed: %v", err)}- b2, err := biscuit.Unmarshal(noRegionData)+ b2, err := biscuit.Unmarshal(noLabelsData)if err != nil {t.Fatalf("Unmarshal biscuit failed: %v", err)}@@ -529,11 +530,11 @@ func TestMintBiscuitToken_RegionFacts(t *testing.T) {t.Fatalf("Authorizer failed: %v", err)}authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{- {Body: []biscuit.Predicate{{Name: api.FactRegion, IDs: []biscuit.Term{biscuit.Variable("r")}}}},+ {Body: []biscuit.Predicate{{Name: api.FactLabel, IDs: []biscuit.Term{biscuit.Variable("k"), biscuit.Variable("v")}}}},}})authorizer.AddPolicy(api.AllowIfTruePolicy)if err := authorizer.Authorize(); err == nil {- t.Error("expected no region facts for an unclaimed region, but check passed")+ t.Error("expected no label facts for an unclaimed node, but check passed")}}@@ -556,7 +557,7 @@ func TestVerifyAndExtractPeerID_MultipleTrustedKeys(t *testing.T) {t.Fatal(err)}- biscuitData, err := MintBootstrapBiscuitToken(priv2, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, "")+ biscuitData, err := MintBootstrapBiscuitToken(priv2, dummyPeer, api.RoleNode, time.Now().Add(1*time.Hour), nil, nil)if err != nil {t.Fatalf("MintBootstrapBiscuitToken failed: %v", err)}diff --git a/internal/node/discovery/discovery_test.go b/internal/node/discovery/discovery_test.goindex cd6a2a43..47fd2c24 100644--- a/internal/node/discovery/discovery_test.go+++ b/internal/node/discovery/discovery_test.go@@ -279,11 +279,8 @@ func TestValidateServiceAnnounceCaps(t *testing.T) {{"oversized label", func(a *api.ServiceAnnounce) {a.Labels = map[string]string{"k": string(make([]byte, api.MaxAnnounceStringLen+1))}}, true},- {"invalid region label", func(a *api.ServiceAnnounce) {- a.Labels = map[string]string{api.LabelRegion: "mars"}- }, true},- {"valid region label", func(a *api.ServiceAnnounce) {- a.Labels = map[string]string{api.LabelRegion: "EU-DE"}+ {"free-form region label", func(a *api.ServiceAnnounce) {+ a.Labels = map[string]string{api.LabelRegion: "us-east-1"}}, false},}for _, tt := range tests {diff --git a/internal/node/discovery_source.go b/internal/node/discovery_source.goindex fc33bbaa..dfe8d54e 100644--- a/internal/node/discovery_source.go+++ b/internal/node/discovery_source.go@@ -47,10 +47,7 @@ func capKeys(keys []string) []string {// discoverySource builds gossip announcements from the registered services:// inference services announce model IDs, MCP services announce tool names.func (n *SamNode) discoverySource() []discovery.Announcement {- var labels map[string]string- if n.config.Region != "" { // normalized and validated at startup- labels = map[string]string{api.LabelRegion: n.config.Region}- }+ labels := n.config.Labels // validated at startupvar out []discovery.Announcementfor _, info := range n.services.List(api.ServiceType_SERVICE_TYPE_UNSPECIFIED) {svc, ok := n.services.Get(info.GetName())diff --git a/internal/node/enroll.go b/internal/node/enroll.goindex a0b96e16..e5cddc6b 100644--- a/internal/node/enroll.go+++ b/internal/node/enroll.go@@ -71,7 +71,7 @@ func (n *SamNode) Enroll(ctx context.Context, controlPlaneURL string, jwt stringPeerId: n.Host.ID().String(),PublicKey: pubBytes,RequestedRole: n.config.RequiredRole,- Region: n.config.Region, // normalized and validated at startup+ Labels: n.config.Labels, // validated at startup}data, err := proto.Marshal(req)if err != nil {@@ -198,7 +198,7 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, bPeerId: n.Host.ID().String(),PublicKey: pubBytes,RequestedRole: n.config.RequiredRole,- Region: n.config.Region, // normalized and validated at startup+ Labels: n.config.Labels, // validated at startup}data, err := proto.Marshal(req)if err != nil {diff --git a/internal/node/region_gate.go b/internal/node/labels_gate.gosimilarity index 65%rename from internal/node/region_gate.gorename to internal/node/labels_gate.goindex 2964c518..4d02c343 100644--- a/internal/node/region_gate.go+++ b/internal/node/labels_gate.go@@ -18,7 +18,7 @@ import ("context""crypto/ed25519""fmt"- "strings"+ "sort""time""github.com/biscuit-auth/biscuit-go/v2"@@ -30,50 +30,65 @@ import ("google.golang.org/protobuf/proto")-// The region gate is the consumer-side enforcement point for region+// The label gate is the consumer-side enforcement point for label// requirements: gossip labels only rank providers, this gate verifies the-// provider's control-plane-attested region() facts (api.FactRegion) before+// provider's control-plane-attested label() facts (api.FactLabel) before// any request data leaves this node. Fail-closed: a provider that returns no// biscuit or lacks a matching fact is rejected.const (- regionGateCacheSize = 1024- // regionGateTTL bounds how long a positive verification verdict is+ labelGateCacheSize = 1024+ // labelGateTTL bounds how long a positive verification verdict is// reused before the provider's biscuit is fetched and checked again.- regionGateTTL = 5 * time.Minute- // regionGateDialTimeout bounds the biscuit-fetch handshake.- regionGateDialTimeout = 10 * time.Second+ labelGateTTL = 5 * time.Minute+ // labelGateDialTimeout bounds the biscuit-fetch handshake.+ labelGateDialTimeout = 10 * time.Second)-// VerifyPeerRegions ensures the peer holds a control-plane-attested region-// satisfying any of the required regions (canonical, pre-validated). A nil-// requirement passes without network traffic. Positive verdicts are cached.-func (n *SamNode) VerifyPeerRegions(ctx context.Context, peerID peer.ID, required []string) error {+// labelGateKey builds a deterministic cache key from a required label set.+func labelGateKey(peerID peer.ID, required map[string]string) string {+ keys := make([]string, 0, len(required))+ for k := range required {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ key := peerID.String()+ for _, k := range keys {+ key += "|" + k + "=" + required[k]+ }+ return key+}++// VerifyPeerLabels ensures the peer holds control-plane-attested labels+// satisfying any of the required key=value pairs (canonical, pre-validated).+// A nil/empty requirement passes without network traffic. Positive verdicts+// are cached.+func (n *SamNode) VerifyPeerLabels(ctx context.Context, peerID peer.ID, required map[string]string) error {if len(required) == 0 {return nil}- key := peerID.String() + "|" + strings.Join(required, ",")- if until, ok := n.peerRegionGate.Get(key); ok && time.Now().Before(until) {+ key := labelGateKey(peerID, required)+ if until, ok := n.peerLabelGate.Get(key); ok && time.Now().Before(until) {return nil}providerBiscuit, err := n.fetchPeerBiscuit(ctx, peerID)if err != nil {- return fmt.Errorf("provider %s region unverifiable: %w", peerID, err)+ return fmt.Errorf("provider %s labels unverifiable: %w", peerID, err)}- if err := n.checkPeerRegions(providerBiscuit, peerID, required); err != nil {+ if err := n.checkPeerLabels(providerBiscuit, peerID, required); err != nil {return err}- n.peerRegionGate.Add(key, time.Now().Add(regionGateTTL))+ n.peerLabelGate.Add(key, time.Now().Add(labelGateTTL))return nil}-// checkPeerRegions verifies the provider's biscuit (control-plane signature,-// expiry, binding to peerID) and evaluates the compiled region requirement+// checkPeerLabels verifies the provider's biscuit (control-plane signature,+// expiry, binding to peerID) and evaluates the compiled label requirement// against its attested facts.-func (n *SamNode) checkPeerRegions(providerBiscuit []byte, peerID peer.ID, required []string) error {+func (n *SamNode) checkPeerLabels(providerBiscuit []byte, peerID peer.ID, required map[string]string) error {if len(providerBiscuit) == 0 {- return fmt.Errorf("provider %s returned no identity biscuit; cannot attest required region %v", peerID, required)+ return fmt.Errorf("provider %s returned no identity biscuit; cannot attest required labels %v", peerID, required)}n.keysMu.RLock()@@ -99,14 +114,14 @@ func (n *SamNode) checkPeerRegions(providerBiscuit []byte, peerID peer.ID, requiif err != nil {return fmt.Errorf("provider %s authorizer instantiation failed: %w", peerID, err)}- check, err := api.RegionCheck(required)+ check, err := api.LabelCheck(required)if err != nil {return err}authorizer.AddCheck(check)authorizer.AddPolicy(api.AllowIfTruePolicy)if err := authorizer.Authorize(); err != nil {- return fmt.Errorf("provider %s has no attested region matching %v: %w", peerID, required, err)+ return fmt.Errorf("provider %s has no attested label matching %v: %w", peerID, required, err)}return nil}@@ -119,14 +134,14 @@ func (n *SamNode) fetchPeerBiscuit(ctx context.Context, peerID peer.ID) ([]byte,return nil, fmt.Errorf("missing node identity")}- dialCtx, cancel := context.WithTimeout(ctx, regionGateDialTimeout)+ dialCtx, cancel := context.WithTimeout(ctx, labelGateDialTimeout)defer cancel()s, err := n.Host.NewStream(dialCtx, peerID, api.AuthProtocolID)if err != nil {return nil, fmt.Errorf("failed to open auth stream: %w", err)}defer func() { _ = s.Close() }()- _ = s.SetDeadline(time.Now().Add(regionGateDialTimeout))+ _ = s.SetDeadline(time.Now().Add(labelGateDialTimeout))authBytes, err := proto.Marshal(&api.AuthFrame{Biscuit: ourBiscuit})if err != nil {diff --git a/internal/node/region_gate_test.go b/internal/node/labels_gate_test.gosimilarity index 55%rename from internal/node/region_gate_test.gorename to internal/node/labels_gate_test.goindex 079d8009..972283e6 100644--- a/internal/node/region_gate_test.go+++ b/internal/node/labels_gate_test.go@@ -24,7 +24,7 @@ import ("github.com/libp2p/go-libp2p/core/peer")-func TestCheckPeerRegions(t *testing.T) {+func TestCheckPeerLabels(t *testing.T) {cpPub, cpPriv, err := ed25519.GenerateKey(nil)if err != nil {t.Fatal(err)@@ -38,9 +38,9 @@ func TestCheckPeerRegions(t *testing.T) {providerPeer := peer.ID("provider-peer-id")expiry := time.Now().Add(time.Hour)- mint := func(key ed25519.PrivateKey, p peer.ID, region string) []byte {+ mint := func(key ed25519.PrivateKey, p peer.ID, labels map[string]string) []byte {t.Helper()- b, err := identity.MintBootstrapBiscuitToken(key, p, api.RoleNode, expiry, nil, region)+ b, err := identity.MintBootstrapBiscuitToken(key, p, api.RoleNode, expiry, nil, labels)if err != nil {t.Fatalf("mint: %v", err)}@@ -55,23 +55,22 @@ func TestCheckPeerRegions(t *testing.T) {tests := []struct {name stringbiscuit []byte- required []string+ required map[string]stringexpectErr bool}{- {"finer claim satisfies coarser requirement", mint(cpPriv, providerPeer, "EU-DE"), []string{"EU"}, false},- {"exact match", mint(cpPriv, providerPeer, "EU-DE"), []string{"EU-DE"}, false},- {"any-of requirement", mint(cpPriv, providerPeer, "NA-US"), []string{"EU", "NA-US"}, false},- {"coarser claim fails finer requirement", mint(cpPriv, providerPeer, "EU"), []string{"EU-DE"}, true},- {"disjoint region fails", mint(cpPriv, providerPeer, "NA-US"), []string{"EU"}, true},- {"unattested token fails closed", mint(cpPriv, providerPeer, ""), []string{"EU"}, true},- {"empty biscuit fails closed", nil, []string{"EU"}, true},- {"untrusted signer fails", mint(otherPriv, providerPeer, "EU-DE"), []string{"EU"}, true},- {"token bound to another peer fails", mint(cpPriv, peer.ID("other-peer"), "EU-DE"), []string{"EU"}, true},+ {"exact match", mint(cpPriv, providerPeer, map[string]string{"region": "us-east-1"}), map[string]string{"region": "us-east-1"}, false},+ {"any-of requirement matches one key", mint(cpPriv, providerPeer, map[string]string{"region": "na-us", "team": "platform"}), map[string]string{"region": "eu", "team": "platform"}, false},+ {"no built-in hierarchy: coarser requirement fails a finer claim", mint(cpPriv, providerPeer, map[string]string{"region": "us-east-1"}), map[string]string{"region": "us"}, true},+ {"disjoint labels fail", mint(cpPriv, providerPeer, map[string]string{"region": "na-us"}), map[string]string{"region": "eu"}, true},+ {"unattested token fails closed", mint(cpPriv, providerPeer, nil), map[string]string{"region": "eu"}, true},+ {"empty biscuit fails closed", nil, map[string]string{"region": "eu"}, true},+ {"untrusted signer fails", mint(otherPriv, providerPeer, map[string]string{"region": "eu"}), map[string]string{"region": "eu"}, true},+ {"token bound to another peer fails", mint(cpPriv, peer.ID("other-peer"), map[string]string{"region": "eu"}), map[string]string{"region": "eu"}, true},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- err := node.checkPeerRegions(tt.biscuit, providerPeer, tt.required)+ err := node.checkPeerLabels(tt.biscuit, providerPeer, tt.required)if tt.expectErr && err == nil {t.Error("expected error, got nil")} else if !tt.expectErr && err != nil {@@ -82,7 +81,7 @@ func TestCheckPeerRegions(t *testing.T) {t.Run("no trusted keys fails closed", func(t *testing.T) {bare := &SamNode{BiscuitTimeout: 500 * time.Millisecond}- if err := bare.checkPeerRegions(mint(cpPriv, providerPeer, "EU"), providerPeer, []string{"EU"}); err == nil {+ if err := bare.checkPeerLabels(mint(cpPriv, providerPeer, map[string]string{"region": "eu"}), providerPeer, map[string]string{"region": "eu"}); err == nil {t.Error("expected error, got nil")}})diff --git a/internal/node/mcp.go b/internal/node/mcp.goindex 2ff0721d..8714bfdb 100644--- a/internal/node/mcp.go+++ b/internal/node/mcp.go@@ -113,7 +113,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {// Add the find_remote_tools tool.mcp.AddTool(mcpServer, &mcp.Tool{Name: "find_remote_tools",- Description: "Discover MCP tools available on hosted services across the mesh. Returns name + description per tool, plus the provider's region claim when known. Optionally narrow by peer_id, service_name, or tool_name (exact tool name; fastest — served from mesh announcements when available). intent is reserved for future ranking and is accepted-but-ignored.",+ Description: "Discover MCP tools available on hosted services across the mesh. Returns name + description per tool, plus the provider's region label when known. Optionally narrow by peer_id, service_name, or tool_name (exact tool name; fastest — served from mesh announcements when available). intent is reserved for future ranking and is accepted-but-ignored.",}, node.handleFindRemoteTools)// Add the describe_remote_tool tool.@@ -227,7 +227,10 @@ func NewMCPHandler(node *SamNode) http.Handler {}// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.-func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolName string, params any) (*mcp.CallToolResult, error) {+// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.+// requiredLabels, when non-empty, fail-closed verifies the peer's control-plane-attested+// labels (see checkPeerLabels) before the tool is invoked; nil means no requirement.+func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolName string, params any, requiredLabels map[string]string) (*mcp.CallToolResult, error) {var res *mcp.CallToolResultvar err errormaxRetries := 3@@ -237,7 +240,7 @@ func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolNamen.preparePeerAddrs(ctx, targetPeer)for i := 0; i < maxRetries; i++ {- res, err = n.callMCPToolOnce(ctx, targetPeer, toolName, params)+ res, err = n.callMCPToolOnce(ctx, targetPeer, toolName, params, requiredLabels)if err == nil {return res, nil}@@ -264,7 +267,7 @@ func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolName// (find_remote_tools) can hide forbidden services instead of leaking their names.var ErrAuthRejected = errors.New("auth rejected")-func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, targetService string) (*mcp.ClientSession, func(), error) {+func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, targetService string, requiredLabels map[string]string) (*mcp.ClientSession, func(), error) {// Open streamlogger.Debugf("Dialing %s for MCP...\n", targetPeer)// For discovery, we want a fast failure, but for tool calls, we can wait a bit. We'll use the context's deadline,@@ -353,6 +356,13 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tarreturn nil, nil, fmt.Errorf("%w by %s: %s", ErrAuthRejected, targetPeer, resp.Error)}+ if len(requiredLabels) > 0 {+ if err := n.checkPeerLabels(resp.Biscuit, targetPeer, requiredLabels); err != nil {+ cleanup()+ return nil, nil, err+ }+ }+// Handoff to SDK using custom transporttransport := NewStreamTransport(s)mcpClient := mcp.NewClient(&mcp.Implementation{Name: "sam-node-mcp-client", Version: "0.1.0"}, nil)@@ -371,13 +381,13 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tarreturn session, fullCleanup, nil}-func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolName string, params any) (*mcp.CallToolResult, error) {+func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolName string, params any, requiredLabels map[string]string) (*mcp.CallToolResult, error) {targetService, originalToolName, err := api.SplitToolName(toolName)if err != nil {return nil, err}- session, cleanup, err := n.ConnectMCPSession(ctx, targetPeer, targetService)+ session, cleanup, err := n.ConnectMCPSession(ctx, targetPeer, targetService, requiredLabels)if err != nil {return nil, err}@@ -403,7 +413,7 @@ func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolNfunc (n *SamNode) fetchRemoteServiceCatalog(ctx context.Context, peerID peer.ID, typeStr string) ([]*api.ServiceInfo, error) {n.preparePeerAddrs(ctx, peerID)- session, cleanup, err := n.ConnectMCPSession(ctx, peerID, "system://"+api.CatalogTarget)+ session, cleanup, err := n.ConnectMCPSession(ctx, peerID, "system://"+api.CatalogTarget, nil)if err != nil {return nil, err}diff --git a/internal/node/mcp_discovery_test.go b/internal/node/mcp_discovery_test.goindex f58b1b50..76320c5a 100644--- a/internal/node/mcp_discovery_test.go+++ b/internal/node/mcp_discovery_test.go@@ -72,8 +72,7 @@ func (f *fakeToolService) Tools(_ context.Context) ([]string, error) {func TestDiscoverySource(t *testing.T) {node := &SamNode{services: NewServiceRegistry(&fakeDHT{}),- // Region arrives normalized and validated from Options.Default/Validate.- config: Options{Region: "EU"},+ config: Options{Labels: map[string]string{api.LabelRegion: "EU"}},}ctx := context.Background()diff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.goindex 146252cd..335ce390 100644--- a/internal/node/mcp_handlers.go+++ b/internal/node/mcp_handlers.go@@ -225,9 +225,10 @@ func (n *SamNode) handleGetMeshInfo(ctx context.Context, req *mcp.CallToolReques// input_schema (use describe_remote_tool to fetch it). Earlier revisions// took a stringified JSON blob here; that footgun is gone.type CallRemoteToolParams struct {- PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`- ToolName string `json:"tool_name" jsonschema:"The name of the server to call"`- Arguments map[string]any `json:"arguments,omitempty" jsonschema:"Server arguments as a JSON object whose keys match the target server's input_schema. Call describe_remote_tool first to learn the schema."`+ PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`+ ToolName string `json:"tool_name" jsonschema:"The name of the server to call"`+ Arguments map[string]any `json:"arguments,omitempty" jsonschema:"Server arguments as a JSON object whose keys match the target server's input_schema. Call describe_remote_tool first to learn the schema."`+ RequiredLabels string `json:"required_labels,omitempty" jsonschema:"Comma-separated key=value pairs (e.g. 'region=us-east-1,team=platform'). Fails closed: the call is rejected unless the peer attests any one of them. Empty means no requirement."`}// handleCallRemoteTool implements the call_remote_tool tool.@@ -237,7 +238,11 @@ func (n *SamNode) handleCallRemoteTool(ctx context.Context, req *mcp.CallToolReqif err != nil {return nil, nil, err}- res, err := n.CallMCPTool(ctx, targetPeer, params.ToolName, params.Arguments)+ requiredLabels, err := parseRequiredLabels(params.RequiredLabels)+ if err != nil {+ return nil, nil, fmt.Errorf("invalid required_labels: %w", err)+ }+ res, err := n.CallMCPTool(ctx, targetPeer, params.ToolName, params.Arguments, requiredLabels)if err != nil {return nil, nil, err}@@ -464,7 +469,7 @@ func (n *SamNode) fetchRemoteToolCatalogue(ctx context.Context, targetPeer peer.}n.preparePeerAddrs(ctx, targetPeer)- session, cleanup, err := n.ConnectMCPSession(ctx, targetPeer, connectService)+ session, cleanup, err := n.ConnectMCPSession(ctx, targetPeer, connectService, nil)if err != nil {if errors.Is(err, ErrAuthRejected) {// Not authorized for this service: omit it entirely rather than@@ -606,7 +611,7 @@ func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToo}n.preparePeerAddrs(ctx, pid)- session, cleanup, err := n.ConnectMCPSession(ctx, pid, serviceName)+ session, cleanup, err := n.ConnectMCPSession(ctx, pid, serviceName, nil)if err != nil {return nil, nil, err}diff --git a/internal/node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.goindex 5392f004..c861e3ec 100644--- a/internal/node/mcp_handlers_test.go+++ b/internal/node/mcp_handlers_test.go@@ -16,6 +16,7 @@ import ("github.com/biscuit-auth/biscuit-go/v2""github.com/google/sam/api"+ "github.com/google/sam/internal/identity""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer""github.com/modelcontextprotocol/go-sdk/mcp"@@ -515,6 +516,67 @@ func TestFetchRemoteToolCatalogue_AuthRejectedHidden(t *testing.T) {}}+func TestCallMCPTool_LabelEnforcement(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ nodeA, cleanupA := startBareNode(t, ctx)+ defer cleanupA()+ nodeB, cleanupB := startBareNode(t, ctx)+ defer cleanupB()++ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeB.Host.ID(), Addrs: nodeB.Host.Addrs()}); err != nil {+ t.Fatalf("connect: %v", err)+ }++ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("gen root key: %v", err)+ }++ // nodeA authenticates to nodeB as an unrestricted caller.+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {+ t.Fatalf("buildAndSaveBiscuit: %v", err)+ }+ nodeB.keysMu.Lock()+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeB.keysMu.Unlock()++ // nodeB's own identity is control-plane-attested with region=eu-de; nodeA+ // must trust the same root to verify it.+ nodeBIdentity, err := identity.MintBootstrapBiscuitToken(rootPriv, nodeB.Host.ID(), api.RoleNode, time.Now().Add(time.Hour), nil, map[string]string{"region": "eu-de"})+ if err != nil {+ t.Fatalf("mint nodeB identity: %v", err)+ }+ nodeB.SetIdentityCache(nodeBIdentity)+ nodeA.keysMu.Lock()+ nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeA.keysMu.Unlock()++ hostedSrv := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{+ {Name: "review_pr", Description: "Run a code review", InputSchema: map[string]any{"type": "object"}},+ }))+ defer hostedSrv.Close()++ if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},+ }); err != nil {+ t.Fatalf("RegisterService: %v", err)+ }+ defer func() { _ = nodeB.UnregisterService(ctx, "code-reviewer") }()++ // A required label that nodeB's attestation satisfies (exact match).+ if _, err := nodeA.CallMCPTool(ctx, nodeB.Host.ID(), "mcp://code-reviewer/review_pr", map[string]any{}, map[string]string{"region": "eu-de"}); err != nil {+ t.Fatalf("CallMCPTool with satisfied label requirement should succeed: %v", err)+ }++ // A required label that nodeB's attestation does not satisfy: fail closed.+ if _, err := nodeA.CallMCPTool(ctx, nodeB.Host.ID(), "mcp://code-reviewer/review_pr", map[string]any{}, map[string]string{"region": "na-us"}); err == nil {+ t.Fatal("CallMCPTool with a non-matching label requirement must fail")+ }+}+func TestNewMCPHandler_RegistersFindRemoteTools(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.goindex 9f56e28e..7f53f6ef 100644--- a/internal/node/middleware_test.go+++ b/internal/node/middleware_test.go@@ -586,8 +586,8 @@ func TestWithBiscuitAuth_MutualBiscuit(t *testing.T) {t.Fatal(err)}- // Server identity: control-plane-minted with an attested region.- serverIdentity, err := identity.MintBootstrapBiscuitToken(priv, serverPeer, api.RoleNode, time.Now().Add(time.Hour), nil, "EU-DE")+ // Server identity: control-plane-minted with an attested label.+ serverIdentity, err := identity.MintBootstrapBiscuitToken(priv, serverPeer, api.RoleNode, time.Now().Add(time.Hour), nil, map[string]string{"region": "eu-de"})if err != nil {t.Fatal(err)}@@ -633,12 +633,12 @@ func TestWithBiscuitAuth_MutualBiscuit(t *testing.T) {t.Error("mutual auth response must carry the server's identity biscuit")}- // The returned biscuit satisfies the consumer-side region gate.- if err := node.checkPeerRegions(resp.Biscuit, serverPeer, []string{"EU"}); err != nil {- t.Errorf("region gate rejected the mutual-auth biscuit: %v", err)+ // The returned biscuit satisfies the consumer-side label gate.+ if err := node.checkPeerLabels(resp.Biscuit, serverPeer, map[string]string{"region": "eu-de"}); err != nil {+ t.Errorf("label gate rejected the mutual-auth biscuit: %v", err)}- if err := node.checkPeerRegions(resp.Biscuit, serverPeer, []string{"NA"}); err == nil {- t.Error("region gate must reject a non-matching requirement")+ if err := node.checkPeerLabels(resp.Biscuit, serverPeer, map[string]string{"region": "na-us"}); err == nil {+ t.Error("label gate must reject a non-matching requirement")}<-done}diff --git a/internal/node/node.go b/internal/node/node.goindex 89790866..fe26b24a 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -136,7 +136,7 @@ type SamNode struct {mu sync.MutexLocalPolicy *NodeConfigCompleterevokedPeers *lru.Cache[string, int64]- peerRegionGate *lru.Cache[string, time.Time]+ peerLabelGate *lru.Cache[string, time.Time]authPeers sync.MaptrustedKeys []TrustedKeykeysMu sync.RWMutex@@ -264,9 +264,9 @@ func NewSamNode(cfg Options) (*SamNode, error) {if err != nil {return nil, fmt.Errorf("failed to create revocation cache: %w", err)}- node.peerRegionGate, err = lru.New[string, time.Time](regionGateCacheSize)+ node.peerLabelGate, err = lru.New[string, time.Time](labelGateCacheSize)if err != nil {- return nil, fmt.Errorf("failed to create region gate cache: %w", err)+ return nil, fmt.Errorf("failed to create label gate cache: %w", err)}return node, nildiff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.goindex efe78bda..fee4c635 100644--- a/internal/node/openai_facade.go+++ b/internal/node/openai_facade.go@@ -51,12 +51,12 @@ type modelLister interface {}// modelProvider locates one service able to serve a model.-// An empty peerID means the service runs on this node. region and active+// An empty peerID means the service runs on this node. labels and active// are known only for gossip-observed providers; zero values mean unknown.type modelProvider struct {peerID stringservice string- region string+ labels map[string]stringactive uint32}@@ -75,17 +75,17 @@ type openAIFacade struct {// and interest registration so announcements start flowing for a model.viewProviders func(model string) []modelProviderensureInterest func(model string)- // Scorer seams (may be nil): revocation check and this node's region.+ // Scorer seams (may be nil): revocation check and this node's labels.isRevoked func(peerID string) bool- localRegion func() string- // peerRegion resolves a peer's gossip-observed region label for providers+ localLabels func() map[string]string+ // peerLabels resolves a peer's gossip-observed labels for providers// discovered via the registry probe, which carries no labels.- peerRegion func(peerID string) string- // Region gate seam (may be nil = enforcement unavailable, fail closed+ peerLabels func(peerID string) map[string]string+ // Label gate seam (may be nil = enforcement unavailable, fail closed// when a requirement exists): verifies the provider's- // control-plane-attested region facts before any request data is sent- // (see region_gate.go).- verifyPeerRegions func(ctx context.Context, peerID string, required []string) error+ // control-plane-attested labels before any request data is sent+ // (see labels_gate.go).+ verifyPeerLabels func(ctx context.Context, peerID string, required map[string]string) errorttl time.Durationmu sync.Mutex@@ -126,7 +126,7 @@ func newOpenAIFacade(node *SamNode, egress http.Handler) *openAIFacade {out = append(out, modelProvider{peerID: p.PeerID,service: p.Service,- region: p.Labels[api.LabelRegion],+ labels: p.Labels,active: p.Load.ActiveRequests,})}@@ -140,19 +140,19 @@ func newOpenAIFacade(node *SamNode, egress http.Handler) *openAIFacade {isRevoked: func(peerID string) bool {return node.revokedPeers != nil && node.revokedPeers.Contains(peerID)},- localRegion: func() string { return node.config.Region },- peerRegion: func(peerID string) string {+ localLabels: func() map[string]string { return node.config.Labels },+ peerLabels: func(peerID string) map[string]string {if node.Discovery == nil {- return ""+ return nil}- return node.Discovery.PeerLabels(peerID)[api.LabelRegion]+ return node.Discovery.PeerLabels(peerID)},- verifyPeerRegions: func(ctx context.Context, peerID string, required []string) error {+ verifyPeerLabels: func(ctx context.Context, peerID string, required map[string]string) error {pid, err := peer.Decode(peerID)if err != nil {return fmt.Errorf("invalid peer ID %q: %w", peerID, err)}- return node.VerifyPeerRegions(ctx, pid, required)+ return node.VerifyPeerLabels(ctx, pid, required)},}}@@ -359,7 +359,7 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)return}- requiredRegions, err := parseRequiredRegions(r.Header.Get(api.HeaderSamRequiredRegion))+ requiredLabels, err := parseRequiredLabels(r.Header.Get(api.HeaderSamRequiredLabels))if err != nil {writeOpenAIError(w, http.StatusBadRequest, "invalid_request", err.Error())return@@ -372,7 +372,7 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)return}- ranked := f.rankProviders(providers, requiredRegions)+ ranked := f.rankProviders(providers, requiredLabels)if len(ranked) == 0 {recordFacadeRejection(reasonNoEligible)writeOpenAIError(w, http.StatusServiceUnavailable, "no_eligible_provider",@@ -383,10 +383,10 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)// The gate already stripped the credential it consumed; a surviving// Authorization header is the destination backend's own credential and// passes through, mirroring the egress path. X-Sam-Authentication is- // local-only, and the region requirement is an instruction to this+ // local-only, and the label requirement is an instruction to this// sidecar, not to the provider.r.Header.Del(api.HeaderSamAuthentication)- r.Header.Del(api.HeaderSamRequiredRegion)+ r.Header.Del(api.HeaderSamRequiredLabels)maxAttempts := min(3, len(ranked))for i := range maxAttempts {@@ -402,22 +402,22 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)if p.peerID == "" {f.serveLocal(aw, attempt, p.service)} else {- // Labels ranked this provider; the region gate is the enforcement+ // Labels ranked this provider; the label gate is the enforcement// point: the provider's biscuit must attest the requirement before// the request body leaves this node.- if len(requiredRegions) > 0 {- if f.verifyPeerRegions == nil {- recordFacadeRejection(reasonRegionUnattested)- writeOpenAIError(w, http.StatusServiceUnavailable, "region_unattested",- "region enforcement is unavailable on this node")+ if len(requiredLabels) > 0 {+ if f.verifyPeerLabels == nil {+ recordFacadeRejection(reasonLabelUnattested)+ writeOpenAIError(w, http.StatusServiceUnavailable, "label_unattested",+ "label enforcement is unavailable on this node")return}// No backoff on failure: the verdict is requirement-scoped,// the provider stays eligible for unconstrained requests.- if err := f.verifyPeerRegions(r.Context(), p.peerID, requiredRegions); err != nil {- recordFacadeRejection(reasonRegionUnattested)- logger.Warnf("[OpenAIFacade] provider peer=%q service=%q failed region attestation for %v: %v; trying next",- p.peerID, p.service, requiredRegions, err)+ if err := f.verifyPeerLabels(r.Context(), p.peerID, requiredLabels); err != nil {+ recordFacadeRejection(reasonLabelUnattested)+ logger.Warnf("[OpenAIFacade] provider peer=%q service=%q failed label attestation for %v: %v; trying next",+ p.peerID, p.service, requiredLabels, err)continue}}diff --git a/internal/node/openai_facade_test.go b/internal/node/openai_facade_test.goindex d0991ff2..ede3d50b 100644--- a/internal/node/openai_facade_test.go+++ b/internal/node/openai_facade_test.go@@ -384,8 +384,8 @@ func TestFacade_EmptyRegistryIsNotCached(t *testing.T) {func TestRankProviders(t *testing.T) {local := modelProvider{service: "local-llm"}- remoteEU := modelProvider{peerID: "peerEU", service: "srv", region: "EU-DE", active: 5}- remoteUS := modelProvider{peerID: "peerUS", service: "srv", region: "NA-US", active: 0}+ remoteEU := modelProvider{peerID: "peerEU", service: "srv", labels: map[string]string{"region": "eu-de"}, active: 5}+ remoteUS := modelProvider{peerID: "peerUS", service: "srv", labels: map[string]string{"region": "na-us"}, active: 0}remoteNoLabel := modelProvider{peerID: "peerX", service: "srv", active: 1}t.Run("locals first, remotes by ascending load", func(t *testing.T) {@@ -396,29 +396,29 @@ func TestRankProviders(t *testing.T) {}})- t.Run("region requirement is fail-closed and hierarchical", func(t *testing.T) {+ t.Run("label requirement is fail-closed and exact", func(t *testing.T) {f := newTestFacade()- // Requiring the continent matches the finer country claim and drops- // the known-mismatched remote. The unlabeled remote survives ranking- // (the region gate attests it before any bytes are sent); the+ // Requiring region=eu-de matches the exact claim and drops the+ // known-mismatched remote. The unlabeled remote survives ranking+ // (the label gate attests it before any bytes are sent); the// unlabeled local has no gate and stays excluded.- got := f.rankProviders([]modelProvider{remoteEU, remoteUS, remoteNoLabel, local}, []string{"EU"})+ got := f.rankProviders([]modelProvider{remoteEU, remoteUS, remoteNoLabel, local}, map[string]string{"region": "eu-de"})if len(got) != 2 || got[0].peerID != "peerX" || got[1].peerID != "peerEU" {- t.Fatalf("unexpected ranking under region requirement: %+v", got)+ t.Fatalf("unexpected ranking under label requirement: %+v", got)}- // A finer requirement never matches a coarser claim.- coarse := modelProvider{peerID: "peerEU2", service: "srv", region: "EU"}- if got := f.rankProviders([]modelProvider{coarse}, []string{"EU-DE"}); len(got) != 0 {- t.Fatalf("coarse claim must not satisfy finer requirement: %+v", got)+ // No built-in hierarchy: a coarser claim never matches a finer requirement.+ coarse := modelProvider{peerID: "peerEU2", service: "srv", labels: map[string]string{"region": "eu"}}+ if got := f.rankProviders([]modelProvider{coarse}, map[string]string{"region": "eu-de"}); len(got) != 0 {+ t.Fatalf("coarse claim must not satisfy a more specific requirement: %+v", got)}})- t.Run("local matches its declared region", func(t *testing.T) {+ t.Run("local matches its declared label", func(t *testing.T) {f := newTestFacade()- f.localRegion = func() string { return "EU" }- got := f.rankProviders([]modelProvider{local, remoteUS}, []string{"EU"})+ f.localLabels = func() map[string]string { return map[string]string{"region": "eu"} }+ got := f.rankProviders([]modelProvider{local, remoteUS}, map[string]string{"region": "eu"})if len(got) != 1 || got[0].service != "local-llm" {- t.Fatalf("local with matching region should survive: %+v", got)+ t.Fatalf("local with matching label should survive: %+v", got)}})@@ -459,31 +459,38 @@ func TestRankProviders(t *testing.T) {})}-func TestParseRequiredRegions(t *testing.T) {- if got, err := parseRequiredRegions(""); got != nil || err != nil {+func TestParseRequiredLabels(t *testing.T) {+ if got, err := parseRequiredLabels(""); got != nil || err != nil {t.Errorf("empty header: got %v, %v; want nil, nil", got, err)}- got, err := parseRequiredRegions(" eu , na-us ,,")- if err != nil || len(got) != 2 || got[0] != "EU" || got[1] != "NA-US" {- t.Errorf("parse should normalize regions: got %v, %v", got, err)+ got, err := parseRequiredLabels(" region=eu , team=platform ,,")+ if err != nil || len(got) != 2 || got["region"] != "eu" || got["team"] != "platform" {+ t.Errorf("parse should split key=value pairs: got %v, %v", got, err)}- if _, err := parseRequiredRegions("mars"); err == nil {- t.Error("invalid region code must be rejected")+ if _, err := parseRequiredLabels("noequals"); err == nil {+ t.Error("entry without '=' must be rejected")}- if _, err := parseRequiredRegions("EU-US"); err == nil {- t.Error("country outside its continent must be rejected")+ if _, err := parseRequiredLabels("bad key!=v"); err == nil {+ t.Error("invalid label key must be rejected")}}-func TestRankProviders_RegionMatchIsCaseInsensitive(t *testing.T) {+func TestRankProviders_LabelMatchIsExactAndCaseSensitive(t *testing.T) {f := newTestFacade()- provider := modelProvider{peerID: "peerEU", service: "srv", region: "eu-de"}- required, err := parseRequiredRegions("Eu")+ provider := modelProvider{peerID: "peerEU", service: "srv", labels: map[string]string{"region": "eu-de"}}+ required, err := parseRequiredLabels("region=eu-de")if err != nil {- t.Fatalf("parseRequiredRegions: %v", err)+ t.Fatalf("parseRequiredLabels: %v", err)}if got := f.rankProviders([]modelProvider{provider}, required); len(got) != 1 {- t.Errorf("region match must be canonical (eu-de vs Eu): got %+v", got)+ t.Errorf("exact label match should survive: got %+v", got)+ }+ requiredWrongCase, err := parseRequiredLabels("region=EU-DE")+ if err != nil {+ t.Fatalf("parseRequiredLabels: %v", err)+ }+ if got := f.rankProviders([]modelProvider{provider}, requiredWrongCase); len(got) != 0 {+ t.Errorf("label match is case-sensitive: got %+v", got)}}@@ -552,76 +559,76 @@ func TestFacade_Completions_AllProvidersFail(t *testing.T) {}}-func TestFacade_Completions_RegionRequirement(t *testing.T) {+func TestFacade_Completions_LabelRequirement(t *testing.T) {f := newTestFacade()f.viewProviders = func(model string) []modelProvider {return []modelProvider{- {peerID: "peerEU", service: "srvEU", region: "EU-DE"},- {peerID: "peerUS", service: "srvUS", region: "NA-US"},+ {peerID: "peerEU", service: "srvEU", labels: map[string]string{"region": "eu-de"}},+ {peerID: "peerUS", service: "srvUS", labels: map[string]string{"region": "na-us"}},}}var attested [][2]string- f.verifyPeerRegions = func(_ context.Context, peerID string, required []string) error {- attested = append(attested, [2]string{peerID, strings.Join(required, ",")})+ f.verifyPeerLabels = func(_ context.Context, peerID string, required map[string]string) error {+ attested = append(attested, [2]string{peerID, required["region"]})return nil}- var gotPath, gotRegionHeader string+ var gotPath, gotLabelsHeader stringf.forward = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotPath = r.URL.Path- gotRegionHeader = r.Header.Get(api.HeaderSamRequiredRegion)+ gotLabelsHeader = r.Header.Get(api.HeaderSamRequiredLabels)})req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))- req.Header.Set(api.HeaderSamRequiredRegion, "EU")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=eu-de")rec := httptest.NewRecorder()f.handleCompletions(rec, req)if want := "/sam/peerEU/inference/srvEU/v1/chat/completions"; gotPath != want {t.Errorf("forwarded path: got %q, want %q", gotPath, want)}- if gotRegionHeader != "" {- t.Errorf("%s must not travel to the provider, got %q", api.HeaderSamRequiredRegion, gotRegionHeader)+ if gotLabelsHeader != "" {+ t.Errorf("%s must not travel to the provider, got %q", api.HeaderSamRequiredLabels, gotLabelsHeader)}- if len(attested) != 1 || attested[0] != [2]string{"peerEU", "EU"} {- t.Errorf("expected one attestation for peerEU/EU, got %v", attested)+ if len(attested) != 1 || attested[0] != [2]string{"peerEU", "eu-de"} {+ t.Errorf("expected one attestation for peerEU/eu-de, got %v", attested)}- // No provider satisfies the requirement (valid code, no claimant).+ // No provider satisfies the requirement (valid entry, no claimant).req = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))- req.Header.Set(api.HeaderSamRequiredRegion, "OC")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=oc")rec = httptest.NewRecorder()f.handleCompletions(rec, req)if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "no_eligible_provider") {- t.Errorf("unsatisfiable region: got status %d, body %s", rec.Code, rec.Body.String())+ t.Errorf("unsatisfiable label: got status %d, body %s", rec.Code, rec.Body.String())}- // Invalid region codes are rejected outright.+ // Malformed label entries are rejected outright.req = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))- req.Header.Set(api.HeaderSamRequiredRegion, "mars")+ req.Header.Set(api.HeaderSamRequiredLabels, "noequals")rec = httptest.NewRecorder()f.handleCompletions(rec, req)if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_request") {- t.Errorf("invalid region: got status %d, body %s", rec.Code, rec.Body.String())+ t.Errorf("invalid label: got status %d, body %s", rec.Code, rec.Body.String())}}-func TestFacade_Completions_RegionAttestation(t *testing.T) {- newRegionFacade := func() *openAIFacade {+func TestFacade_Completions_LabelAttestation(t *testing.T) {+ newLabelFacade := func() *openAIFacade {f := newTestFacade()f.viewProviders = func(model string) []modelProvider {return []modelProvider{- {peerID: "peerEU1", service: "srv1", region: "EU-DE", active: 1},- {peerID: "peerEU2", service: "srv2", region: "EU-FR", active: 2},+ {peerID: "peerEU1", service: "srv1", labels: map[string]string{"region": "eu-de"}, active: 1},+ {peerID: "peerEU2", service: "srv2", labels: map[string]string{"region": "eu-de"}, active: 2},}}return f}t.Run("unattested provider is skipped, attested one serves", func(t *testing.T) {- f := newRegionFacade()- f.verifyPeerRegions = func(_ context.Context, peerID string, _ []string) error {+ f := newLabelFacade()+ f.verifyPeerLabels = func(_ context.Context, peerID string, _ map[string]string) error {if peerID == "peerEU1" {- return fmt.Errorf("no attested region")+ return fmt.Errorf("no attested label")}return nil}@@ -631,7 +638,7 @@ func TestFacade_Completions_RegionAttestation(t *testing.T) {})req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))- req.Header.Set(api.HeaderSamRequiredRegion, "EU")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=eu-de")rec := httptest.NewRecorder()f.handleCompletions(rec, req)@@ -641,24 +648,24 @@ func TestFacade_Completions_RegionAttestation(t *testing.T) {})t.Run("requirement with enforcement unavailable fails closed", func(t *testing.T) {- f := newRegionFacade() // verifyPeerRegions deliberately nil+ f := newLabelFacade() // verifyPeerLabels deliberately nilf.forward = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {t.Error("request must not be forwarded without attestation")})req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))- req.Header.Set(api.HeaderSamRequiredRegion, "EU")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=eu-de")rec := httptest.NewRecorder()f.handleCompletions(rec, req)- if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "region_unattested") {+ if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "label_unattested") {t.Errorf("got status %d, body %s", rec.Code, rec.Body.String())}})t.Run("no requirement never attests", func(t *testing.T) {- f := newRegionFacade()- f.verifyPeerRegions = func(_ context.Context, _ string, _ []string) error {+ f := newLabelFacade()+ f.verifyPeerLabels = func(_ context.Context, _ string, _ map[string]string) error {t.Error("attestation must not run without a requirement")return nil}diff --git a/internal/node/openai_scorer.go b/internal/node/openai_scorer.goindex a5a34999..686f157a 100644--- a/internal/node/openai_scorer.go+++ b/internal/node/openai_scorer.go@@ -15,6 +15,7 @@package nodeimport (+ "fmt""net/http""sort""strings"@@ -30,38 +31,49 @@ const providerBackoff = 15 * time.Secondconst (reasonPeerRevoked = "peer_revoked"reasonProviderBackoff = "provider_backoff"- reasonRegionMismatch = "region_mismatch"- reasonRegionUnattested = "region_unattested"+ reasonLabelMismatch = "label_mismatch"+ reasonLabelUnattested = "label_unattested"reasonNoEligible = "no_eligible_provider"reasonAttemptsExceeded = "attempts_exceeded")-// parseRequiredRegions splits the X-Sam-Required-Region header value into-// canonical continent codes; any invalid code rejects the whole request.-func parseRequiredRegions(h string) ([]string, error) {+// parseRequiredLabels splits the X-Sam-Required-Labels header value+// (comma-separated "key=value" pairs) into a label map; any malformed entry+// rejects the whole request.+func parseRequiredLabels(h string) (map[string]string, error) {if h == "" {return nil, nil}- var out []string+ var out map[string]stringfor _, part := range strings.Split(h, ",") {- p := api.NormalizeRegion(part)- if p == "" {+ part = strings.TrimSpace(part)+ if part == "" {continue}- if err := api.ValidateRegion(p); err != nil {+ k, v, ok := strings.Cut(part, "=")+ if !ok {+ return nil, fmt.Errorf("invalid label %q: expected key=value", part)+ }+ k, v = strings.TrimSpace(k), strings.TrimSpace(v)+ if err := api.ValidateLabelKey(k); err != nil {+ return nil, err+ }+ if err := api.ValidateLabelValue(v); err != nil {return nil, err}- out = append(out, p)+ if out == nil {+ out = make(map[string]string)+ }+ out[k] = v}return out, nil}-// regionAllowed reports whether a provider's claim satisfies any required-// region (hierarchical, see api.RegionMatches).-func regionAllowed(required []string, claimed string) bool {- claimed = api.NormalizeRegion(claimed)- for _, req := range required {- if api.RegionMatches(req, claimed) {+// labelsAllowed reports whether a provider's claimed labels satisfy any+// required key=value pair (exact match).+func labelsAllowed(required, claimed map[string]string) bool {+ for k, v := range required {+ if claimed[k] == v {return true}}@@ -72,26 +84,26 @@ func regionAllowed(required []string, claimed string) bool {// locals first, then remotes by ascending advertised load. Providers with no// load information look idle — without telemetry this degrades to rotation// among equals. Every exclusion is accounted per reason.-func (f *openAIFacade) rankProviders(providers []modelProvider, requiredRegions []string) []modelProvider {+func (f *openAIFacade) rankProviders(providers []modelProvider, requiredLabels map[string]string) []modelProvider {var locals, remotes []modelProviderfor _, p := range providers {- region := p.region- if p.peerID == "" && f.localRegion != nil {- region = f.localRegion()- } else if region == "" && p.peerID != "" && f.peerRegion != nil {+ labels := p.labels+ if p.peerID == "" && f.localLabels != nil {+ labels = f.localLabels()+ } else if len(labels) == 0 && p.peerID != "" && f.peerLabels != nil {// Registry-probed providers carry no labels; the gossip view may- // still know the peer's claim.- region = f.peerRegion(p.peerID)+ // still know the peer's claims.+ labels = f.peerLabels(p.peerID)}- // Labels are routing hints: a remote whose own claim mismatches the+ // Labels are routing hints: a remote whose own claims mismatch the// requirement is dropped early, but an unlabeled remote proceeds to- // the region gate, the authoritative fail-closed check on the- // provider's biscuit-attested region (see region_gate.go). Locals- // have no gate, so their declared region stays fail-closed here.- if len(requiredRegions) > 0 {- knownMismatch := region != "" && !regionAllowed(requiredRegions, region)- if knownMismatch || (p.peerID == "" && !regionAllowed(requiredRegions, region)) {- recordFacadeRejection(reasonRegionMismatch)+ // the label gate, the authoritative fail-closed check on the+ // provider's biscuit-attested labels (see labels_gate.go). Locals+ // have no gate, so their declared labels stay fail-closed here.+ if len(requiredLabels) > 0 {+ knownMismatch := len(labels) > 0 && !labelsAllowed(requiredLabels, labels)+ if knownMismatch || (p.peerID == "" && !labelsAllowed(requiredLabels, labels)) {+ recordFacadeRejection(reasonLabelMismatch)continue}}diff --git a/internal/node/options.go b/internal/node/options.goindex c857f933..cb3d0ee5 100644--- a/internal/node/options.go+++ b/internal/node/options.go@@ -58,9 +58,10 @@ type Options struct {DiscoveryConcurrency int// RequiredRole restricts enrollment and startup to only accept tokens containing this role.RequiredRole string- // Region is the operator-declared jurisdiction of this node (api.LabelRegion).- // Empty means no claim; consumers with a region requirement will not select it.- Region string+ // Labels are operator-declared key=value claims for this node (e.g.+ // {"region": "us-east-1"}, see api/labels.go). Empty means no claims;+ // consumers with a label requirement will not select this node.+ Labels map[string]string// PolicySyncInterval specifies how often the node syncs the mesh policy from the control plane.PolicySyncInterval time.Duration// PolicySyncJitter specifies the maximum jitter delay when scheduling policy syncs on event broadcasts.@@ -111,7 +112,6 @@ func (o *Options) Default() {if o.PolicySyncJitter <= 0 {o.PolicySyncJitter = 10 * time.Second}- o.Region = api.NormalizeRegion(o.Region)}// Validate verifies that the required options are provided and valid.@@ -125,10 +125,8 @@ func (o *Options) Validate() error {if o.RequiredRole == "" {return fmt.Errorf("RequiredRole must be specified")}- if o.Region != "" {- if err := api.ValidateRegion(o.Region); err != nil {- return err- }+ if err := api.ValidateLabels(o.Labels); err != nil {+ return err}return nil}diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.goindex af46818c..45fa0005 100644--- a/internal/storage/sql_store.go+++ b/internal/storage/sql_store.go@@ -332,6 +332,25 @@ var migrations = []migration{`INSERT OR IGNORE INTO rotation_lock (id, next_rotation_at) VALUES (1, 0)`,},},+ {+ // Replaces the region-specific claim with a generic key=value label+ // set (see api/labels.go): no built-in taxonomy or hierarchy, just a+ // JSON-encoded map an operator can populate with as many labels as+ // their composition needs.+ version: 7,+ postgres: []string{+ `ALTER TABLE nodes DROP COLUMN IF EXISTS region`,+ `ALTER TABLE nodes ADD COLUMN IF NOT EXISTS labels_json TEXT DEFAULT '' NOT NULL`,+ `ALTER TABLE enrollment_requests DROP COLUMN IF EXISTS region`,+ `ALTER TABLE enrollment_requests ADD COLUMN IF NOT EXISTS labels_json TEXT DEFAULT '' NOT NULL`,+ },+ sqlite: []string{+ `ALTER TABLE nodes DROP COLUMN region`,+ `ALTER TABLE nodes ADD COLUMN labels_json TEXT DEFAULT '' NOT NULL`,+ `ALTER TABLE enrollment_requests DROP COLUMN region`,+ `ALTER TABLE enrollment_requests ADD COLUMN labels_json TEXT DEFAULT '' NOT NULL`,+ },+ },}func (s *SQLStore) initSchema() error {@@ -567,23 +586,28 @@ func (s *SQLStore) SaveInitialKey(ctx context.Context, priv ed25519.PrivateKey,// EnrollNode implements Store.func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {+ labelsJSON, err := json.Marshal(node.Labels)+ if err != nil {+ return fmt.Errorf("failed to marshal labels: %w", err)+ }+var query stringif s.isPostgres() {query = s.rebind(`- INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, region, enrolled_at, expires_at, banned)+ INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, labels_json, enrolled_at, expires_at, banned)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)ON CONFLICT (peer_id)- DO UPDATE SET public_key = EXCLUDED.public_key, biscuit_token = EXCLUDED.biscuit_token, role = EXCLUDED.role, enrollment_type = EXCLUDED.enrollment_type, claims_json = EXCLUDED.claims_json, owner_id = EXCLUDED.owner_id, region = EXCLUDED.region, enrolled_at = EXCLUDED.enrolled_at, expires_at = EXCLUDED.expires_at`)+ DO UPDATE SET public_key = EXCLUDED.public_key, biscuit_token = EXCLUDED.biscuit_token, role = EXCLUDED.role, enrollment_type = EXCLUDED.enrollment_type, claims_json = EXCLUDED.claims_json, owner_id = EXCLUDED.owner_id, labels_json = EXCLUDED.labels_json, enrolled_at = EXCLUDED.enrolled_at, expires_at = EXCLUDED.expires_at`)} else {query = s.rebind(`- INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, region, enrolled_at, expires_at, banned)+ INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, labels_json, enrolled_at, expires_at, banned)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)ON CONFLICT (peer_id)- DO UPDATE SET public_key = excluded.public_key, biscuit_token = excluded.biscuit_token, role = excluded.role, enrollment_type = excluded.enrollment_type, claims_json = excluded.claims_json, owner_id = excluded.owner_id, region = excluded.region, enrolled_at = excluded.enrolled_at, expires_at = excluded.expires_at`)+ DO UPDATE SET public_key = excluded.public_key, biscuit_token = excluded.biscuit_token, role = excluded.role, enrollment_type = excluded.enrollment_type, claims_json = excluded.claims_json, owner_id = excluded.owner_id, labels_json = excluded.labels_json, enrolled_at = excluded.enrolled_at, expires_at = excluded.expires_at`)}ownerIDNull := sql.NullString{String: node.OwnerID, Valid: node.OwnerID != ""}- _, err := s.db.ExecContext(ctx, query,+ _, err = s.db.ExecContext(ctx, query,node.PeerID,node.PublicKey,node.Biscuit,@@ -591,7 +615,7 @@ func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {node.EnrollmentType,node.ClaimsJSON,ownerIDNull,- node.Region,+ string(labelsJSON),node.EnrolledAt.UnixMilli(),node.ExpiresAt.UnixMilli(),)@@ -600,9 +624,9 @@ func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {// GetNode implements Store.func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, error) {- query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, region, enrolled_at, expires_at, banned FROM nodes WHERE peer_id = ?`)+ query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, labels_json, enrolled_at, expires_at, banned FROM nodes WHERE peer_id = ?`)var node EnrolledNode- var claimsJSON, ownerID sql.NullString+ var claimsJSON, ownerID, labelsJSON sql.NullStringvar enrolledAtUnix, expiresAtUnix int64err := s.db.QueryRowContext(ctx, query, peerID).Scan(&node.PeerID,@@ -612,7 +636,7 @@ func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, e&node.EnrollmentType,&claimsJSON,&ownerID,- &node.Region,+ &labelsJSON,&enrolledAtUnix,&expiresAtUnix,&node.Banned,@@ -629,6 +653,11 @@ func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, eif err != nil {return nil, err}+ if labelsJSON.Valid && labelsJSON.String != "" {+ if err := json.Unmarshal([]byte(labelsJSON.String), &node.Labels); err != nil {+ return nil, fmt.Errorf("failed to unmarshal labels: %w", err)+ }+ }node.EnrolledAt = time.UnixMilli(enrolledAtUnix)node.ExpiresAt = time.UnixMilli(expiresAtUnix)return &node, nil@@ -932,19 +961,23 @@ func (s *SQLStore) IncrementBootstrapTokenUsage(ctx context.Context, id string)// CreateEnrollmentRequest saves a new pending request.func (s *SQLStore) CreateEnrollmentRequest(ctx context.Context, req *EnrollmentRequest) error {- query := `INSERT INTO enrollment_requests (id, peer_id, public_key, token_id, status, region, biscuit_token, created_at, resolved_at, resolved_by)+ labelsJSON, err := json.Marshal(req.Labels)+ if err != nil {+ return fmt.Errorf("failed to marshal labels: %w", err)+ }+ query := `INSERT INTO enrollment_requests (id, peer_id, public_key, token_id, status, labels_json, biscuit_token, created_at, resolved_at, resolved_by)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`var resAt sql.NullInt64if req.ResolvedAt != nil {resAt = sql.NullInt64{Int64: req.ResolvedAt.Unix(), Valid: true}}- _, err := s.db.ExecContext(ctx, s.rebind(query),+ _, err = s.db.ExecContext(ctx, s.rebind(query),req.ID,req.PeerID,req.PublicKey,req.TokenID,int(req.Status),- req.Region,+ string(labelsJSON),req.BiscuitToken,req.CreatedAt.Unix(),resAt,@@ -958,14 +991,14 @@ func (s *SQLStore) CreateEnrollmentRequest(ctx context.Context, req *EnrollmentR// GetEnrollmentRequest retrieves request by PeerID.func (s *SQLStore) GetEnrollmentRequest(ctx context.Context, peerID string) (*EnrollmentRequest, error) {- query := `SELECT id, peer_id, public_key, token_id, status, region, biscuit_token, created_at, resolved_at, resolved_by+ query := `SELECT id, peer_id, public_key, token_id, status, labels_json, biscuit_token, created_at, resolved_at, resolved_byFROM enrollment_requests WHERE peer_id = ?`return s.scanEnrollmentRequest(s.db.QueryRowContext(ctx, s.rebind(query), peerID))}// GetEnrollmentRequestByID retrieves request by UUID.func (s *SQLStore) GetEnrollmentRequestByID(ctx context.Context, id string) (*EnrollmentRequest, error) {- query := `SELECT id, peer_id, public_key, token_id, status, region, biscuit_token, created_at, resolved_at, resolved_by+ query := `SELECT id, peer_id, public_key, token_id, status, labels_json, biscuit_token, created_at, resolved_at, resolved_byFROM enrollment_requests WHERE id = ?`return s.scanEnrollmentRequest(s.db.QueryRowContext(ctx, s.rebind(query), id))}@@ -978,6 +1011,7 @@ func (s *SQLStore) scanEnrollmentRequest(row scannable) (*EnrollmentRequest, errvar created int64var resAt sql.NullInt64var statusVal int+ var labelsJSON sql.NullStringvar req EnrollmentRequesterr := row.Scan(@@ -986,7 +1020,7 @@ func (s *SQLStore) scanEnrollmentRequest(row scannable) (*EnrollmentRequest, err&req.PublicKey,&req.TokenID,&statusVal,- &req.Region,+ &labelsJSON,&req.BiscuitToken,&created,&resAt,@@ -997,6 +1031,11 @@ func (s *SQLStore) scanEnrollmentRequest(row scannable) (*EnrollmentRequest, err} else if err != nil {return nil, fmt.Errorf("failed to scan enrollment request: %w", err)}+ if labelsJSON.Valid && labelsJSON.String != "" {+ if err := json.Unmarshal([]byte(labelsJSON.String), &req.Labels); err != nil {+ return nil, fmt.Errorf("failed to unmarshal labels: %w", err)+ }+ }req.CreatedAt = time.Unix(created, 0)req.Status = api.EnrollmentStatus(statusVal)@@ -1018,7 +1057,7 @@ func (s *SQLStore) scanEnrollmentRequest(row scannable) (*EnrollmentRequest, err// ListEnrollmentRequests retrieves all requests.func (s *SQLStore) ListEnrollmentRequests(ctx context.Context) ([]EnrollmentRequest, error) {- query := `SELECT id, peer_id, public_key, token_id, status, region, biscuit_token, created_at, resolved_at, resolved_by+ query := `SELECT id, peer_id, public_key, token_id, status, labels_json, biscuit_token, created_at, resolved_at, resolved_byFROM enrollment_requests ORDER BY created_at DESC`rows, err := s.db.QueryContext(ctx, s.rebind(query))if err != nil {@@ -1058,7 +1097,7 @@ func (s *SQLStore) UpdateEnrollmentRequest(ctx context.Context, id string, statu// ListNodes retrieves all enrolled nodes.func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {- query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, region, enrolled_at, expires_at, banned FROM nodes ORDER BY enrolled_at DESC`)+ query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, labels_json, enrolled_at, expires_at, banned FROM nodes ORDER BY enrolled_at DESC`)rows, err := s.db.QueryContext(ctx, query)if err != nil {return nil, fmt.Errorf("failed to query nodes: %w", err)@@ -1068,7 +1107,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {var nodes []EnrolledNodefor rows.Next() {var node EnrolledNode- var claimsJSON, ownerID sql.NullString+ var claimsJSON, ownerID, labelsJSON sql.NullStringvar enrolledAtUnix, expiresAtUnix int64err := rows.Scan(&node.PeerID,@@ -1078,7 +1117,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {&node.EnrollmentType,&claimsJSON,&ownerID,- &node.Region,+ &labelsJSON,&enrolledAtUnix,&expiresAtUnix,&node.Banned,@@ -1092,6 +1131,11 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {if ownerID.Valid {node.OwnerID = ownerID.String}+ if labelsJSON.Valid && labelsJSON.String != "" {+ if err := json.Unmarshal([]byte(labelsJSON.String), &node.Labels); err != nil {+ return nil, fmt.Errorf("failed to unmarshal labels: %w", err)+ }+ }node.EnrolledAt = time.UnixMilli(enrolledAtUnix)node.ExpiresAt = time.UnixMilli(expiresAtUnix)diff --git a/internal/storage/sql_store_test.go b/internal/storage/sql_store_test.goindex 2c3b5f6a..f92d43e7 100644--- a/internal/storage/sql_store_test.go+++ b/internal/storage/sql_store_test.go@@ -242,7 +242,7 @@ func TestNodeEnrollmentOps(t *testing.T) {Biscuit: biscuitData,Role: "node",EnrollmentType: "OIDC",- Region: "EU-DE",+ Labels: map[string]string{"region": "eu-de"},EnrolledAt: time.Now(),ExpiresAt: expiresAt,}@@ -259,8 +259,8 @@ func TestNodeEnrollmentOps(t *testing.T) {if n.PeerID != peerID || !bytes.Equal(n.Biscuit, biscuitData) || n.Banned {t.Fatalf("node data mismatch: %+v", n)}- if n.Region != "EU-DE" {- t.Fatalf("node region mismatch: got %q, want EU-DE", n.Region)+ if n.Labels["region"] != "eu-de" {+ t.Fatalf("node labels mismatch: got %+v, want region=eu-de", n.Labels)}// Ban node@@ -474,7 +474,7 @@ func TestBootstrapTokensAndEnrollmentRequestsOps(t *testing.T) {PublicKey: []byte("my-public-key-bytes"),TokenID: tok.ID,Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING,- Region: "NA-US",+ Labels: map[string]string{"region": "na-us"},BiscuitToken: nil,CreatedAt: time.Now().Truncate(time.Second),}@@ -490,8 +490,8 @@ func TestBootstrapTokensAndEnrollmentRequestsOps(t *testing.T) {if gotReq.ID != req.ID || gotReq.Status != req.Status || !bytes.Equal(gotReq.PublicKey, req.PublicKey) {t.Errorf("retrieved request mismatch: %+v", gotReq)}- if gotReq.Region != "NA-US" {- t.Errorf("retrieved request region mismatch: got %q, want NA-US", gotReq.Region)+ if gotReq.Labels["region"] != "na-us" {+ t.Errorf("retrieved request labels mismatch: got %+v, want region=na-us", gotReq.Labels)}gotReqByID, err := store.GetEnrollmentRequestByID(ctx, req.ID)diff --git a/internal/storage/storage.go b/internal/storage/storage.goindex 2685cbc7..44b4abb0 100644--- a/internal/storage/storage.go+++ b/internal/storage/storage.go@@ -61,9 +61,9 @@ type EnrolledNode struct {EnrollmentType stringClaimsJSON stringOwnerID string- // Region is the attested region claim minted into the node's biscuit;- // kept on the record so token refreshes re-mint it unchanged.- Region string+ // Labels are the attested key=value claims minted into the node's+ // biscuit; kept on the record so token refreshes re-mint them unchanged.+ Labels map[string]stringEnrolledAt time.TimeExpiresAt time.TimeBanned bool@@ -89,9 +89,9 @@ type EnrollmentRequest struct {PublicKey []byteTokenID stringStatus api.EnrollmentStatus- // Region is the operator-declared region claim, surfaced to the- // approving admin; approval attests it into the minted biscuit.- Region string+ // Labels are the operator-declared key=value claims, surfaced to the+ // approving admin; approval attests them into the minted biscuit.+ Labels map[string]stringBiscuitToken []byteCreatedAt time.TimeResolvedAt *time.Timediff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.goindex f1c6bfef..a04346e9 100644--- a/mobile/sam-node-ffi/ffi/ffi.go+++ b/mobile/sam-node-ffi/ffi/ffi.go@@ -419,7 +419,7 @@ func CallRemoteTool(peerIDStr string, toolName string, argsJSON string) string {}}- res, err := n.CallMCPTool(context.Background(), targetPeer, toolName, params)+ res, err := n.CallMCPTool(context.Background(), targetPeer, toolName, params, nil)if err != nil {return fmt.Sprintf(`{"error": "failed to call tool: %s"}`, err.Error())}diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.mdindex 7321500f..f3e53ece 100644--- a/site/content/docs/user/node-configuration.md+++ b/site/content/docs/user/node-configuration.md@@ -87,40 +87,42 @@ You can further restrict access using the `attenuation` block. Local policies de----## 4. Regions & Data Sovereignty+## 4. Labels & Data Sovereignty-SAM supports jurisdiction constraints so a request never leaves a required region.+SAM supports attested key=value labels (e.g. `region`, `team`) so a request never leaves a required scope. Cloud providers, on-prem operators, and countries all name regions differently, so SAM imposes no built-in taxonomy or hierarchy: composition (e.g. also attesting a coarser value) is entirely up to the operator.-### Declaring a region (provider)+### Declaring labels (provider)-Start the node with its operator-declared region, using the hierarchical form `CONTINENT[-COUNTRY[-ZONE]]` (ISO 3166, e.g. `EU`, `EU-DE`, `NA-US-CA`):+Start the node with its operator-declared labels, a comma-separated `key=value` list:```bash-sam-node run --region EU-DE ...+sam-node run --labels region=us-east-1,team=platform ...```-The region is declared at enrollment and **attested by the control plane**: for bootstrap enrollments the administrator sees the declared region on the pending request and approving it attests the claim. The control plane then mints one signed `region()` fact per hierarchy level into the node's Biscuit (`region("EU")`, `region("EU-DE")`), so a coarser requirement matches a finer claim, but never the reverse. An invalid region is rejected at enrollment; an empty one means no claim.+Labels are declared at enrollment and **attested by the control plane**: for bootstrap enrollments the administrator sees the declared labels on the pending request and approving it attests the claims. The control plane then mints one signed `label(key, value)` fact per declared label into the node's Biscuit. Matching is exact and case-sensitive; an empty value means no claim for that key.-### Requiring a region (consumer)+### Requiring labels (consumer)-On the sidecar's OpenAI-compatible endpoints, constrain a request with the `X-Sam-Required-Region` header (comma-separated, any-of):+On the sidecar's OpenAI-compatible endpoints, constrain a request with the `X-Sam-Required-Labels` header (comma-separated `key=value` pairs, any-of):```bashcurl http://localhost:8080/v1/chat/completions \-H "Authorization: Bearer $SAM_API_TOKEN" \- -H "X-Sam-Required-Region: EU" \+ -H "X-Sam-Required-Labels: region=us-east-1" \-d '{"model":"test-model","messages":[{"role":"user","content":"hi"}]}'```-Enforcement is fail-closed and cryptographic: gossiped region labels only rank candidate providers, and before any request data leaves your node the sidecar verifies the provider's control-plane-signed Biscuit and checks its attested `region()` facts. Providers that return no identity or lack a matching fact are rejected.+The `call_remote_tool` MCP tool accepts the same requirement via its `required_labels` parameter.-### Restricting callers by region (provider)+Enforcement is fail-closed and cryptographic: gossiped labels only rank candidate providers, and before any request data leaves your node the sidecar verifies the provider's control-plane-signed Biscuit and checks its attested `label()` facts. Providers that return no identity or lack a matching fact are rejected.-Because every enrolled node's token carries its attested region facts, a provider can require callers to be in a region with a single local check in its `attenuation` block:+### Restricting callers by label (provider)++Because every enrolled node's token carries its attested label facts, a provider can require callers to hold a label with a single local check in its `attenuation` block:```yamlattenuation:checks:- - 'check if region("EU");'+ - 'check if label("region", "us-east-1");'```diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.goindex 1a25a82d..af0faac8 100644--- a/tests/integration/fallback_test.go+++ b/tests/integration/fallback_test.go@@ -93,7 +93,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {writer := msgio.NewVarintWriter(s)resp := &api.AuthResponse{Success: true,- Biscuit: createMockBiscuitToken(t, newH.ID().String(), priv, api.RoleRouter),+ Biscuit: createMockBiscuitToken(t, newH.ID().String(), priv, api.RoleRouter, nil),}respBytes, _ := proto.Marshal(resp)_ = writer.WriteMsg(respBytes)@@ -155,7 +155,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv, api.RoleNode),+ BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv, api.RoleNode, nil),ControlPlanePublicKey: pub,RouterAddresses: []string{addr},}diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex b74dffbd..a6f528c2 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -234,7 +234,7 @@ func startMockRouter(t *testing.T) (peer.ID, string) {writer := msgio.NewVarintWriter(s)resp := &api.AuthResponse{Success: true,- Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter),+ Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter, nil),}respBytes, _ := proto.Marshal(resp)_ = writer.WriteMsg(respBytes)@@ -265,7 +265,7 @@ func startMockRouter(t *testing.T) (peer.ID, string) {}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode, req.Region),+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode, req.Labels),ControlPlanePublicKey: pub,RouterAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},}@@ -315,7 +315,7 @@ func startMockRouterWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, strinwriter := msgio.NewVarintWriter(s)resp := &api.AuthResponse{Success: true,- Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter),+ Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter, nil),}respBytes, _ := proto.Marshal(resp)_ = writer.WriteMsg(respBytes)@@ -365,7 +365,7 @@ func startMockRouterWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, strin}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode, req.Region),+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode, req.Labels),ControlPlanePublicKey: pub,RouterAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},}@@ -390,18 +390,16 @@ func startMockRouterWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, strinreturn h.ID(), httpServer.URL}-func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey, role string, region ...string) []byte {+func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey, role string, labels map[string]string) []byte {builder := biscuit.NewBuilder(priv)err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})if err != nil {t.Fatalf("failed to add target_unrestricted: %v", err)}- for _, r := range region {- for _, fact := range api.RegionFacts(r) {- if err := builder.AddAuthorityFact(fact); err != nil {- t.Fatalf("failed to add region fact: %v", err)- }+ for _, fact := range api.LabelFacts(labels) {+ if err := builder.AddAuthorityFact(fact); err != nil {+ t.Fatalf("failed to add label fact: %v", err)}}diff --git a/tests/integration/openai_facade_test.go b/tests/integration/openai_facade_test.goindex 815ee6ee..5dd87fd4 100644--- a/tests/integration/openai_facade_test.go+++ b/tests/integration/openai_facade_test.go@@ -48,7 +48,7 @@ func TestOpenAIFacadeCUJ(t *testing.T) {"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",- "--region", "eu", // exercise the operator region claim end to end+ "--labels", "region=eu", // exercise the operator label claim end to end)t.Log("Starting Node B (consumer)...")_ = startBackgroundNode(t, nodeBin, hubAddr, homeB,@@ -133,19 +133,19 @@ func TestOpenAIFacadeCUJ(t *testing.T) {t.Fatalf("unexpected completion: %s", string(body))}- // CUJ step 2b: a region requirement is enforced end to end — the provider- // declared "eu" at enrollment, so its biscuit carries attested region- // facts and the consumer's region gate admits it. The region label- // arrives via interest-scoped gossip, so poll until it propagates.+ // CUJ step 2b: a label requirement is enforced end to end — the provider+ // declared region=eu at enrollment, so its biscuit carries an attested+ // label fact and the consumer's label gate admits it. The region gossip+ // hint arrives via interest-scoped gossip, so poll until it propagates.deadline := time.Now().Add(30 * time.Second)for {req, _ = http.NewRequest("POST", "http://"+apiAddrB+"/v1/chat/completions", strings.NewReader(reqBody))req.Header.Set("Authorization", "Bearer "+apiToken)req.Header.Set("Content-Type", "application/json")- req.Header.Set(api.HeaderSamRequiredRegion, "EU")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=eu")respEU, err := http.DefaultClient.Do(req)if err != nil {- t.Fatalf("region-constrained completion request failed: %v", err)+ t.Fatalf("label-constrained completion request failed: %v", err)}euBody, _ := io.ReadAll(respEU.Body)_ = respEU.Body.Close()@@ -153,23 +153,23 @@ func TestOpenAIFacadeCUJ(t *testing.T) {break}if time.Now().After(deadline) {- t.Fatalf("region-constrained completion status: got %d, body: %s", respEU.StatusCode, string(euBody))+ t.Fatalf("label-constrained completion status: got %d, body: %s", respEU.StatusCode, string(euBody))}time.Sleep(200 * time.Millisecond)}- // A finer requirement than the provider's claim fails closed.+ // A requirement that mismatches the provider's declared label fails closed.req, _ = http.NewRequest("POST", "http://"+apiAddrB+"/v1/chat/completions", strings.NewReader(reqBody))req.Header.Set("Authorization", "Bearer "+apiToken)- req.Header.Set(api.HeaderSamRequiredRegion, "EU-DE")+ req.Header.Set(api.HeaderSamRequiredLabels, "region=us-east-1")respDE, err := http.DefaultClient.Do(req)if err != nil {- t.Fatalf("finer-region completion request failed: %v", err)+ t.Fatalf("mismatched-label completion request failed: %v", err)}defer func() { _ = respDE.Body.Close() }()deBody, _ := io.ReadAll(respDE.Body)if respDE.StatusCode != http.StatusServiceUnavailable {- t.Fatalf("finer region must fail closed: got %d, body: %s", respDE.StatusCode, string(deBody))+ t.Fatalf("mismatched label must fail closed: got %d, body: %s", respDE.StatusCode, string(deBody))}// CUJ step 3: unknown models fail with an OpenAI-style error.diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.goindex d54cb08c..2ccf1d10 100644--- a/tests/integration/proxy_test.go+++ b/tests/integration/proxy_test.go@@ -53,7 +53,7 @@ func TestSamNodeRunWithStoredIdentity(t *testing.T) {if err != nil {return err}- biscuitBytes := createMockBiscuitToken(t, "12D3KooWRHDt3Ajd1t7YikBXyK2Uw1wrJwEX88XbwJhHh1XtBNkx", priv, "sam:role:node")+ biscuitBytes := createMockBiscuitToken(t, "12D3KooWRHDt3Ajd1t7YikBXyK2Uw1wrJwEX88XbwJhHh1XtBNkx", priv, "sam:role:node", nil)if err := b.Put([]byte("identity_biscuit"), biscuitBytes); err != nil {return err}