Skip to content

Agent Mesh

feat(api): hierarchical ISO 3166 region model with strict validation

Antonio Ojeabb2730b6c168
diff --git a/api/network.go b/api/network.go
index 5fdb68d0..75bd831a 100644
--- a/api/network.go
+++ b/api/network.go
@@ -110,8 +110,10 @@ const (
// HeaderSamRequiredRegion constrains an inference request on the sidecar's
// OpenAI-compatible endpoints (/v1/*) to providers whose declared region is
- // in the comma-separated list. It can only narrow what mesh policy allows,
- // never widen it. Absent means any region permitted by policy.
+ // 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.
//
// Reserved as part of the sidecar contract; enforced by the provider
// scorer. Region declarations are routing hints until attested via the
@@ -122,13 +124,19 @@ const (
// ============================================================================
// Well-Known Node Labels
// ============================================================================
+//
+// Placement rule: anything two nodes must agree on to interoperate (topics,
+// headers, labels, wire caps, canonical value forms) is defined here in api/.
+// Behavioral tuning a node decides alone (intervals, TTLs, table bounds)
+// lives in the package that owns the behavior.
const (
- // LabelRegion is the operator-declared jurisdiction of a node (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, 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 = "region"
)
diff --git a/api/region.go b/api/region.go
new file mode 100644
index 00000000..ef0881b2
--- /dev/null
+++ b/api/region.go
@@ -0,0 +1,125 @@
+// 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+"-")
+}
+
+// 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.go
new file mode 100644
index 00000000..5a520be6
--- /dev/null
+++ b/api/region_test.go
@@ -0,0 +1,73 @@
+// 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)
+ }
+}
diff --git a/api/validation.go b/api/validation.go
index bd8b879c..4ccd0a16 100644
--- a/api/validation.go
+++ b/api/validation.go
@@ -44,6 +44,11 @@ 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.go
index e3eaec23..4f912171 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -580,7 +580,7 @@ func main() {
joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")
joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
runCmd.Flags().StringVar(&apiTokenFlag, "api-token", "", "Static Bearer token for API authorization")
- runCmd.Flags().StringVar(&regionFlag, "region", "", "Operator-declared region of this node (e.g. \"eu\"); empty means no claim")
+ runCmd.Flags().StringVar(&regionFlag, "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(&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/node/discovery/discovery_test.go b/internal/node/discovery/discovery_test.go
index bfa2732c..9c366e0e 100644
--- a/internal/node/discovery/discovery_test.go
+++ b/internal/node/discovery/discovery_test.go
@@ -277,6 +277,12 @@ 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"}
+ }, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
diff --git a/internal/node/discovery_source.go b/internal/node/discovery_source.go
index bdd528c0..fc33bbaa 100644
--- a/internal/node/discovery_source.go
+++ b/internal/node/discovery_source.go
@@ -48,7 +48,7 @@ func capKeys(keys []string) []string {
// 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 != "" {
+ if n.config.Region != "" { // normalized and validated at startup
labels = map[string]string{api.LabelRegion: n.config.Region}
}
var out []discovery.Announcement
diff --git a/internal/node/mcp_discovery_test.go b/internal/node/mcp_discovery_test.go
index e6f47299..f58b1b50 100644
--- a/internal/node/mcp_discovery_test.go
+++ b/internal/node/mcp_discovery_test.go
@@ -72,7 +72,8 @@ func (f *fakeToolService) Tools(_ context.Context) ([]string, error) {
func TestDiscoverySource(t *testing.T) {
node := &SamNode{
services: NewServiceRegistry(&fakeDHT{}),
- config: Options{Region: "eu"},
+ // Region arrives normalized and validated from Options.Default/Validate.
+ config: Options{Region: "EU"},
}
ctx := context.Background()
@@ -106,8 +107,8 @@ func TestDiscoverySource(t *testing.T) {
t.Errorf("reviewer announcement: %+v", a)
}
for name, a := range byName {
- if a.Labels[api.LabelRegion] != "eu" {
- t.Errorf("%s labels: got %v, want region=eu", name, a.Labels)
+ if a.Labels[api.LabelRegion] != "EU" {
+ t.Errorf("%s labels: got %v, want region=EU", name, a.Labels)
}
}
}
diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.go
index 939cde91..c93e76f7 100644
--- a/internal/node/openai_facade.go
+++ b/internal/node/openai_facade.go
@@ -338,6 +338,12 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)
return
}
+ requiredRegions, err := parseRequiredRegions(r.Header.Get(api.HeaderSamRequiredRegion))
+ if err != nil {
+ writeOpenAIError(w, http.StatusBadRequest, "invalid_request", err.Error())
+ return
+ }
+
providers := f.providersFor(r.Context(), req.Model)
if len(providers) == 0 {
writeOpenAIError(w, http.StatusNotFound, "model_not_found",
@@ -345,7 +351,6 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)
return
}
- requiredRegions := parseRequiredRegions(r.Header.Get(api.HeaderSamRequiredRegion))
ranked := f.rankProviders(providers, requiredRegions)
if len(ranked) == 0 {
recordFacadeRejection(reasonNoEligible)
diff --git a/internal/node/openai_facade_test.go b/internal/node/openai_facade_test.go
index 281f9637..1a79d0cf 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", active: 5}
- remoteUS := modelProvider{peerID: "peerUS", service: "srv", region: "us", active: 0}
+ remoteEU := modelProvider{peerID: "peerEU", service: "srv", region: "EU-DE", active: 5}
+ remoteUS := modelProvider{peerID: "peerUS", service: "srv", 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,19 +396,25 @@ func TestRankProviders(t *testing.T) {
}
})
- t.Run("region requirement is fail-closed", func(t *testing.T) {
+ t.Run("region requirement is fail-closed and hierarchical", func(t *testing.T) {
f := newTestFacade()
- got := f.rankProviders([]modelProvider{remoteEU, remoteUS, remoteNoLabel, local}, []string{"eu"})
- // Unlabeled remote and unlabeled local must both be excluded.
+ // Requiring the continent matches the finer country claim; the
+ // unlabeled remote and unlabeled local must both be excluded.
+ got := f.rankProviders([]modelProvider{remoteEU, remoteUS, remoteNoLabel, local}, []string{"EU"})
if len(got) != 1 || got[0].peerID != "peerEU" {
t.Fatalf("unexpected ranking under region 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)
+ }
})
t.Run("local matches its declared region", func(t *testing.T) {
f := newTestFacade()
- f.localRegion = func() string { return "eu" }
- got := f.rankProviders([]modelProvider{local, remoteUS}, []string{"eu"})
+ f.localRegion = func() string { return "EU" }
+ got := f.rankProviders([]modelProvider{local, remoteUS}, []string{"EU"})
if len(got) != 1 || got[0].service != "local-llm" {
t.Fatalf("local with matching region should survive: %+v", got)
}
@@ -452,11 +458,30 @@ func TestRankProviders(t *testing.T) {
}
func TestParseRequiredRegions(t *testing.T) {
- if got := parseRequiredRegions(""); got != nil {
- t.Errorf("empty header: got %v, want nil", got)
+ if got, err := parseRequiredRegions(""); 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)
+ }
+ if _, err := parseRequiredRegions("mars"); err == nil {
+ t.Error("invalid region code must be rejected")
+ }
+ if _, err := parseRequiredRegions("EU-US"); err == nil {
+ t.Error("country outside its continent must be rejected")
+ }
+}
+
+func TestRankProviders_RegionMatchIsCaseInsensitive(t *testing.T) {
+ f := newTestFacade()
+ provider := modelProvider{peerID: "peerEU", service: "srv", region: "eu-de"}
+ required, err := parseRequiredRegions("Eu")
+ if err != nil {
+ t.Fatalf("parseRequiredRegions: %v", err)
}
- if got := parseRequiredRegions(" eu , us ,,"); len(got) != 2 || got[0] != "eu" || got[1] != "us" {
- t.Errorf("parse: got %v", got)
+ if got := f.rankProviders([]modelProvider{provider}, required); len(got) != 1 {
+ t.Errorf("region match must be canonical (eu-de vs Eu): got %+v", got)
}
}
@@ -529,8 +554,8 @@ func TestFacade_Completions_RegionRequirement(t *testing.T) {
f := newTestFacade()
f.viewProviders = func(model string) []modelProvider {
return []modelProvider{
- {peerID: "peerEU", service: "srvEU", region: "eu"},
- {peerID: "peerUS", service: "srvUS", region: "us"},
+ {peerID: "peerEU", service: "srvEU", region: "EU-DE"},
+ {peerID: "peerUS", service: "srvUS", region: "NA-US"},
}
}
var gotPath, gotRegionHeader string
@@ -540,7 +565,7 @@ func TestFacade_Completions_RegionRequirement(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.HeaderSamRequiredRegion, "EU")
rec := httptest.NewRecorder()
f.handleCompletions(rec, req)
@@ -551,14 +576,23 @@ func TestFacade_Completions_RegionRequirement(t *testing.T) {
t.Errorf("%s must not travel to the provider, got %q", api.HeaderSamRequiredRegion, gotRegionHeader)
}
- // No provider satisfies the requirement.
+ // No provider satisfies the requirement (valid code, no claimant).
req = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))
- req.Header.Set(api.HeaderSamRequiredRegion, "mars")
+ req.Header.Set(api.HeaderSamRequiredRegion, "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())
}
+
+ // Invalid region codes are rejected outright.
+ req = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))
+ req.Header.Set(api.HeaderSamRequiredRegion, "mars")
+ 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())
+ }
}
func TestAttemptWriter(t *testing.T) {
diff --git a/internal/node/openai_scorer.go b/internal/node/openai_scorer.go
index 6dda6167..45143ef1 100644
--- a/internal/node/openai_scorer.go
+++ b/internal/node/openai_scorer.go
@@ -16,10 +16,11 @@ package node
import (
"net/http"
- "slices"
"sort"
"strings"
"time"
+
+ "github.com/google/sam/api"
)
// providerBackoff is how long a provider is skipped after a retryable failure.
@@ -34,18 +35,36 @@ const (
reasonAttemptsExceeded = "attempts_exceeded"
)
-// parseRequiredRegions splits the X-Sam-Required-Region header value.
-func parseRequiredRegions(h string) []string {
+// 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) {
if h == "" {
- return nil
+ return nil, nil
}
var out []string
for _, part := range strings.Split(h, ",") {
- if p := strings.TrimSpace(part); p != "" {
- out = append(out, p)
+ p := api.NormalizeRegion(part)
+ if p == "" {
+ continue
+ }
+ if err := api.ValidateRegion(p); err != nil {
+ return nil, err
+ }
+ out = append(out, p)
+ }
+ 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) {
+ return true
}
}
- return out
+ return false
}
// rankProviders applies hard constraints then orders the survivors: eligible
@@ -59,9 +78,10 @@ func (f *openAIFacade) rankProviders(providers []modelProvider, requiredRegions
if p.peerID == "" && f.localRegion != nil {
region = f.localRegion()
}
- // Region is fail-closed: a requirement never matches an unlabeled
- // provider. Labels are routing hints until biscuit-attested.
- if len(requiredRegions) > 0 && !slices.Contains(requiredRegions, region) {
+ // Region is fail-closed: a requirement never matches an unlabeled or
+ // coarser-scoped provider. Labels are routing hints until
+ // biscuit-attested.
+ if len(requiredRegions) > 0 && !regionAllowed(requiredRegions, region) {
recordFacadeRejection(reasonRegionMismatch)
continue
}
diff --git a/internal/node/options.go b/internal/node/options.go
index 24a1845b..c857f933 100644
--- a/internal/node/options.go
+++ b/internal/node/options.go
@@ -111,6 +111,7 @@ 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.
@@ -124,5 +125,10 @@ 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
+ }
+ }
return nil
}