Skip to content

Agent Mesh

security: optimize biscuit verify, ensure deterministic serialization, protect against nil claims, and add micro-benchmarks

Antonio Ojea9779a01c7361
diff --git a/cmd/sam-hub/biscuit.go b/cmd/sam-hub/biscuit.go
index 34334be4..0026e62b 100644
--- a/cmd/sam-hub/biscuit.go
+++ b/cmd/sam-hub/biscuit.go
@@ -16,6 +16,7 @@ package main
import (
"fmt"
+ "sort"
"strings"
"time"
@@ -32,6 +33,9 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
if token == nil {
return nil, fmt.Errorf("token cannot be nil")
}
+ if claims == nil {
+ return nil, fmt.Errorf("claims cannot be nil")
+ }
oidcRoles := toStringSlice(claims["roles"])
oidcGroups := toStringSlice(claims["groups"])
@@ -93,7 +97,13 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
}
// Assert resolved authorized roles in the token
+ roles := make([]string, 0, len(resolvedRoles))
for role := range resolvedRoles {
+ roles = append(roles, role)
+ }
+ sort.Strings(roles)
+
+ for _, role := range roles {
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: api.FactRole,
IDs: []biscuit.Term{biscuit.String(role)},
@@ -157,6 +167,23 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
return biscuitData, nil
}
+var (
+ staticTimeCheck biscuit.Check
+ staticAllowPolicy biscuit.Policy
+)
+
+func init() {
+ var err error
+ staticTimeCheck, err = parser.FromStringCheck(`check if time($time), expiration($exp), $time <= $exp`)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse static time check: %v", err))
+ }
+ staticAllowPolicy, err = parser.FromStringPolicy("allow if true")
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse static allow policy: %v", err))
+ }
+}
+
func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Biscuit, error) {
b, err := biscuit.Unmarshal(biscuitData)
if err != nil {
@@ -168,16 +195,6 @@ func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Bi
authOpts = append(authOpts, biscuit.WithWorldOptions(datalog.WithMaxDuration(h.BiscuitTimeout)))
}
- timeCheck, err := parser.FromStringCheck(`check if time($time), expiration($exp), $time <= $exp`)
- if err != nil {
- return nil, fmt.Errorf("failed to parse time check: %w", err)
- }
-
- rule, err := parser.FromStringPolicy("allow if true")
- if err != nil {
- return nil, fmt.Errorf("failed to parse allow policy: %w", err)
- }
-
keys := h.KeyRing.GetAllValidPublicKeys()
var lastErr error
for _, pubKey := range keys {
@@ -194,8 +211,8 @@ func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Bi
},
})
- authorizer.AddCheck(timeCheck)
- authorizer.AddPolicy(rule)
+ authorizer.AddCheck(staticTimeCheck)
+ authorizer.AddPolicy(staticAllowPolicy)
if err := authorizer.Authorize(); err == nil {
return b, nil
@@ -208,7 +225,14 @@ func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Bi
}
func translateClaimsToFacts(builder biscuit.Builder, claims map[string]any) error {
- for claimKey, factName := range api.OIDCClaimToFact {
+ keys := make([]string, 0, len(api.OIDCClaimToFact))
+ for k := range api.OIDCClaimToFact {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ for _, claimKey := range keys {
+ factName := api.OIDCClaimToFact[claimKey]
val, ok := claims[claimKey]
if !ok || val == nil {
continue
diff --git a/cmd/sam-hub/biscuit_benchmark_test.go b/cmd/sam-hub/biscuit_benchmark_test.go
new file mode 100644
index 00000000..58f52508
--- /dev/null
+++ b/cmd/sam-hub/biscuit_benchmark_test.go
@@ -0,0 +1,138 @@
+// 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 main
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/coreos/go-oidc/v3/oidc"
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+)
+
+func BenchmarkMintBiscuitToken(b *testing.B) {
+ dir := b.TempDir()
+ dbPath := filepath.Join(dir, "test.db")
+
+ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer func() { _ = kr.Close() }()
+
+ hub := &Hub{
+ KeyRing: kr,
+ Policy: &api.PolicyConfig{
+ Bindings: []api.Binding{
+ {
+ Group: "engineering",
+ Role: "developer-role",
+ },
+ },
+ Roles: map[string]api.RolePolicy{
+ "developer-role": {
+ MCP: api.MCPPolicy{
+ AllowedServers: []string{"git-helper", "mcp-server-2"},
+ },
+ Network: api.NetworkPolicy{
+ AllowedTargets: []string{"target-1", "target-2"},
+ },
+ CustomDatalog: []string{
+ "department(\"analytics\");",
+ },
+ },
+ },
+ },
+ }
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ b.Fatal(err)
+ }
+ dummyPeer, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ token := &oidc.IDToken{
+ Expiry: time.Now().Add(1 * time.Hour),
+ }
+
+ claims := jwt.MapClaims{
+ "sub": "user-12345",
+ "email": "[email protected]",
+ "groups": []any{"beta-testers", "engineering"},
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, err := hub.mintBiscuitToken(claims, token, dummyPeer)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkVerifyBiscuit(b *testing.B) {
+ dir := b.TempDir()
+ dbPath := filepath.Join(dir, "test.db")
+
+ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer func() { _ = kr.Close() }()
+
+ hub := &Hub{
+ KeyRing: kr,
+ Policy: &api.PolicyConfig{},
+ BiscuitTimeout: 500 * time.Millisecond,
+ }
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ b.Fatal(err)
+ }
+ dummyPeer, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ token := &oidc.IDToken{
+ Expiry: time.Now().Add(1 * time.Hour),
+ }
+
+ claims := jwt.MapClaims{
+ "sub": "user-123",
+ "roles": []any{"admin"},
+ }
+
+ biscuitData, err := hub.mintBiscuitToken(claims, token, dummyPeer)
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, err := hub.verifyBiscuit(biscuitData, dummyPeer)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
diff --git a/cmd/sam-hub/biscuit_test.go b/cmd/sam-hub/biscuit_test.go
index 9c694338..0b9c5e95 100644
--- a/cmd/sam-hub/biscuit_test.go
+++ b/cmd/sam-hub/biscuit_test.go
@@ -421,6 +421,37 @@ func TestMintBiscuitToken_NilToken(t *testing.T) {
}
}
+func TestMintBiscuitToken_NilClaims(t *testing.T) {
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "test.db")
+
+ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = kr.Close() }()
+
+ hub := &Hub{KeyRing: kr}
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dummyPeer, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ token := &oidc.IDToken{
+ Expiry: time.Now().Add(1 * time.Hour),
+ }
+
+ _, err = hub.mintBiscuitToken(nil, token, dummyPeer)
+ if err == nil {
+ t.Error("Expected mintBiscuitToken to fail with nil claims, got nil error")
+ }
+}
+
func TestMintBiscuitToken_VariousClaimsTypes(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")