Skip to content

Agent Mesh

oidc refactor and dex deployment

Antonio Ojea82606cd44181
diff --git a/.github/k8s/dex-config.yaml b/.github/k8s/dex-config.yaml
new file mode 100644
index 00000000..3650c70e
--- /dev/null
+++ b/.github/k8s/dex-config.yaml
@@ -0,0 +1,53 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: dex
+ namespace: dex
+data:
+ config.yaml: |
+ # The public URL where Dex is accessible
+ issuer: https://auth.sam-mesh.dev
+
+ storage:
+ type: kubernetes
+ config:
+ inCluster: true
+
+ web:
+ # Serve plain HTTP locally; the GKE Ingress handles HTTPS termination
+ http: 0.0.0.0:5556
+
+ oauth2:
+ # Explicitly enable the Device Flow for headless CLI usage
+ grantTypes:
+ - "authorization_code"
+ - "refresh_token"
+ - "urn:ietf:params:oauth:grant-type:device_code"
+ skipApprovalScreen: true
+
+ connectors:
+ - type: google
+ id: google
+ name: Google
+ config:
+ clientID: $GOOGLE_CLIENT_ID
+ clientSecret: $GOOGLE_CLIENT_SECRET
+ redirectURI: https://auth.sam-mesh.dev/callback
+
+ - type: github
+ id: github
+ name: GitHub
+ config:
+ clientID: $GITHUB_CLIENT_ID
+ clientSecret: $GITHUB_CLIENT_SECRET
+ redirectURI: https://auth.sam-mesh.dev/callback
+
+ staticClients:
+ # This ID becomes the 'aud' claim in the JWT consumed by sam-hub
+ - id: sam-mesh-audience
+ name: 'SAM Mesh CLI'
+ secret: $CLI_OAUTH_SECRET
+ public: true # Allows PKCE flow for CLIs without exposing the secret
+ redirectURIs:
+ - 'http://127.0.0.1:8080/callback'
+ - 'http://localhost:8080/callback'
diff --git a/.github/k8s/dex-deployment.yaml b/.github/k8s/dex-deployment.yaml
new file mode 100644
index 00000000..1147c4e2
--- /dev/null
+++ b/.github/k8s/dex-deployment.yaml
@@ -0,0 +1,174 @@
+---
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: dex
+ namespace: dex
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: ClusterRole
+metadata:
+ name: dex
+rules:
+- apiGroups: ["dex.coreos.com"]
+ resources: ["*"]
+ verbs: ["*"]
+- apiGroups: ["apiextensions.k8s.io"]
+ resources: ["customresourcedefinitions"]
+ verbs: ["create"]
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: ClusterRoleBinding
+metadata:
+ name: dex
+roleRef:
+ apiGroup: rbac.authorization.k8s.io
+ kind: ClusterRole
+ name: dex
+subjects:
+- kind: ServiceAccount
+ name: dex
+ namespace: dex
+---
+# Custom Health Check configuration for the Google Cloud Load Balancer
+apiVersion: cloud.google.com/v1
+kind: BackendConfig
+metadata:
+ name: dex-backend-config
+ namespace: dex
+spec:
+ healthCheck:
+ checkIntervalSec: 15
+ port: 5556
+ type: HTTP
+ requestPath: /healthz
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: dex
+ namespace: dex
+ annotations:
+ # Bind the backend config to the service so the L7 Load Balancer uses /healthz
+ cloud.google.com/backend-config: '{"default": "dex-backend-config"}'
+spec:
+ # Must be NodePort for GKE L7 Ingress to route to it
+ type: NodePort
+ ports:
+ - name: dex
+ port: 5556
+ protocol: TCP
+ targetPort: 5556
+ selector:
+ app: dex
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: dex
+ namespace: dex
+ labels:
+ app: dex
+spec:
+ replicas: 2
+ selector:
+ matchLabels:
+ app: dex
+ template:
+ metadata:
+ labels:
+ app: dex
+ spec:
+ serviceAccountName: dex
+ containers:
+ - image: ghcr.io/dexidp/dex:v2.38.0
+ name: dex
+ command: ["/usr/local/bin/dex", "serve", "/etc/dex/cfg/config.yaml"]
+ ports:
+ - name: http
+ containerPort: 5556
+ volumeMounts:
+ - name: config
+ mountPath: /etc/dex/cfg
+ env:
+ # Dynamically pulls the values injected by your GitHub Actions pipeline
+ - name: GOOGLE_CLIENT_ID
+ valueFrom:
+ secretKeyRef:
+ name: dex-secrets
+ key: google-client-id
+ - name: GOOGLE_CLIENT_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: dex-secrets
+ key: google-client-secret
+ - name: GITHUB_CLIENT_ID
+ valueFrom:
+ secretKeyRef:
+ name: dex-secrets
+ key: github-client-id
+ - name: GITHUB_CLIENT_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: dex-secrets
+ key: github-client-secret
+ - name: CLI_OAUTH_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: dex-secrets
+ key: cli-oauth-secret
+ readinessProbe:
+ httpGet:
+ path: /healthz
+ port: 5556
+ scheme: HTTP
+ initialDelaySeconds: 5
+ periodSeconds: 10
+ resources:
+ requests:
+ cpu: 50m
+ memory: 64Mi
+ limits:
+ cpu: 200m
+ memory: 128Mi
+ volumes:
+ - name: config
+ configMap:
+ name: dex
+ items:
+ - key: config.yaml
+ path: config.yaml
+---
+# Request a free, auto-renewing SSL certificate from Google
+apiVersion: networking.gke.io/v1
+kind: ManagedCertificate
+metadata:
+ name: dex-cert
+ namespace: dex
+spec:
+ domains:
+ - auth.sam-mesh.dev
+---
+# The L7 Load Balancer
+apiVersion: networking.k8s.io/v1
+kind: Ingress
+metadata:
+ name: dex-ingress
+ namespace: dex
+ annotations:
+ kubernetes.io/ingress.class: "gce"
+ networking.gke.io/managed-certificates: dex-cert
+ # Tells GKE to attach the global static IP you reserved earlier
+ kubernetes.io/ingress.global-static-ip-name: "auth-sam-mash"
+spec:
+ rules:
+ - host: auth.sam-mesh.dev
+ http:
+ paths:
+ - path: /*
+ pathType: ImplementationSpecific
+ backend:
+ service:
+ name: dex
+ port:
+ number: 5556
diff --git a/.github/k8s/sam-hub-template.yaml b/.github/k8s/sam-hub-template.yaml
index d79b6540..426ad0c9 100644
--- a/.github/k8s/sam-hub-template.yaml
+++ b/.github/k8s/sam-hub-template.yaml
@@ -62,8 +62,10 @@ spec:
args:
- "--listen=/ip4/0.0.0.0/tcp/4001,/ip4/0.0.0.0/udp/4001/quic-v1"
- "--external-multiaddr=${EXTERNAL_MULTIADDR}"
-
- # Critical for multi-tenant clusters: prevent testnet from starving prod
+ # 1. Trust Dex for humans/Google/GitHub. 2. Trust GKE for internal Canaries.
+ - "--oidc-issuer=https://auth.sam-mesh.dev,https://container.googleapis.com/v1/projects/${GCP_PROJECT_ID}/locations/${CLUSTER_REGION}/clusters/${CLUSTER_NAME}"
+ # 1. Dex CLI client ID. 2. Canary projected volume audience.
+ - "--audiences=sam-mesh-audience,sam-hub-audience"
resources:
requests:
cpu: 100m
diff --git a/.github/k8s/sam-node-template.yaml b/.github/k8s/sam-node-template.yaml
index 21eeed3b..22e2201b 100644
--- a/.github/k8s/sam-node-template.yaml
+++ b/.github/k8s/sam-node-template.yaml
@@ -22,6 +22,12 @@ data:
# We call the injected busybox binary explicitly
command: ["/shared/busybox", "sh", "-c", "while read line; do echo '{\"jsonrpc\": \"2.0\", \"id\": 1, \"result\": {\"status\": \"canary-alive\"}}'; done"]
---
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: sam-node-sa
+ namespace: sam-canary-${ENV_NAME}
+---
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -37,6 +43,7 @@ spec:
labels:
app: sam-canary-${ENV_NAME}
spec:
+ serviceAccountName: sam-node-sa
# 1. The Init Container: Copies busybox to the shared volume
initContainers:
- name: inject-busybox
@@ -54,6 +61,7 @@ spec:
- "run"
- "--config=/etc/sam/sam-node.yaml"
- "--hub=/dns4/sam-hub-${ENV_NAME}.sam-${ENV_NAME}.svc.cluster.local/udp/4001/quic-v1"
+ - "--jwt-path=/var/run/secrets/tokens/sam-token"
ports:
- containerPort: 8080
resources:
@@ -68,6 +76,9 @@ spec:
mountPath: /etc/sam
- name: shared-bin
mountPath: /shared
+ - name: sam-token
+ mountPath: /var/run/secrets/tokens
+ readOnly: true
# 3. The Dummy MCP Backend Sidecar
- name: mock-mcp-server
@@ -83,3 +94,10 @@ spec:
name: sam-canary-config-${ENV_NAME}
- name: shared-bin
emptyDir: {}
+ - name: sam-token
+ projected:
+ sources:
+ - serviceAccountToken:
+ path: sam-token
+ expirationSeconds: 3600
+ audience: "sam-hub-audience"
diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml
index d5904d8b..f84ed3db 100644
--- a/.github/workflows/deploy.yaml
+++ b/.github/workflows/deploy.yaml
@@ -121,9 +121,42 @@ jobs:
export NAMESPACE="sam-${ENV_NAME}"
export CANARY_NAMESPACE="sam-canary-${ENV_NAME}"
+ kubectl create namespace dex --dry-run=client -o yaml | kubectl apply -f -
kubectl create namespace ${NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
kubectl create namespace ${CANARY_NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
+ - name: Provision Dex Secrets
+ env:
+ GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
+ GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
+ GITHUB_CLIENT_ID: ${{ secrets.GHUB_CLIENT_ID }}
+ GITHUB_CLIENT_SECRET: ${{ secrets.GHUB_CLIENT_SECRET }}
+ CLI_OAUTH_SECRET: ${{ secrets.CLI_OAUTH_SECRET }}
+ run: |
+ # Declaratively apply secrets without writing them to disk
+ kubectl create secret generic dex-secrets \
+ --namespace=dex \
+ --from-literal=google-client-id="${GOOGLE_CLIENT_ID}" \
+ --from-literal=google-client-secret="${GOOGLE_CLIENT_SECRET}" \
+ --from-literal=github-client-id="${GITHUB_CLIENT_ID}" \
+ --from-literal=github-client-secret="${GITHUB_CLIENT_SECRET}" \
+ --from-literal=cli-oauth-secret="${CLI_OAUTH_SECRET}" \
+ --dry-run=client -o yaml | kubectl apply -f -
+
+ - name: Deploy Dex Resources
+ run: |
+ # Apply the Dex manifests
+ kubectl apply -f .github/k8s/dex-config.yaml
+ kubectl apply -f .github/k8s/dex-deployment.yaml
+
+ # Force a restart to pick up any changes to the secrets, and wait for readiness
+ kubectl rollout restart deployment/dex -n dex
+ kubectl rollout status deployment/dex -n dex --timeout=120s || {
+ echo "Dex Deployment failed! Rolling back..."
+ kubectl rollout undo deployment/dex -n dex
+ exit 1
+ }
+
- name: Deploy Hub
run: |
sudo apt-get install -y gettext-base
diff --git a/api/constants.go b/api/constants.go
index 8ebb0a4e..a18f78dc 100644
--- a/api/constants.go
+++ b/api/constants.go
@@ -21,6 +21,8 @@ const MCPProtocolID protocol.ID = "/sam/mcp/1.0.0"
const GossipEvents = "/sam/mesh/events/v1"
const AuthProtocolID protocol.ID = "/sam/auth/1.0.0"
+const DefaultAudience = "sam-mesh-audience"
+
// Biscuit fact names
const (
FactExpiration = "expiration"
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
index 7987f1ef..90f5092b 100644
--- a/cmd/sam-hub/main.go
+++ b/cmd/sam-hub/main.go
@@ -95,23 +95,25 @@ var (
tlsKeyFile string
tlsCAFile string
externalMultiaddrs []string
+ allowedAudiencesFlag string
)
var logger = golog.Logger("sam-hub")
// Hub handles identity bridging and network discovery
type Hub struct {
- Host host.Host
- DHT *dht.IpfsDHT
- Providers map[string]*oidc.Provider
- KeyRing *KeyRing
- MeshID string
- PubSub *pubsub.PubSub
- EventTopic *pubsub.Topic
- gater *hubConnGate
- Policy *api.PolicyConfig
- limiter *rate.Limiter
- ExternalAddrs []string
+ Host host.Host
+ DHT *dht.IpfsDHT
+ Providers map[string]*oidc.Provider
+ KeyRing *KeyRing
+ MeshID string
+ PubSub *pubsub.PubSub
+ EventTopic *pubsub.Topic
+ gater *hubConnGate
+ Policy *api.PolicyConfig
+ limiter *rate.Limiter
+ ExternalAddrs []string
+ AllowedAudiences []string
}
// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)
@@ -189,16 +191,28 @@ func NewHub(ctx context.Context, policy *api.PolicyConfig) (*Hub, error) {
return nil, fmt.Errorf("failed to create keyring: %w", err)
}
+ var auds []string
+ for _, aud := range strings.Split(allowedAudiencesFlag, ",") {
+ aud = strings.TrimSpace(aud)
+ if aud != "" {
+ auds = append(auds, aud)
+ }
+ }
+ if len(auds) == 0 {
+ auds = []string{api.DefaultAudience}
+ }
+
hub := &Hub{
- Host: h,
- DHT: kadDHT,
- gater: gater,
- Providers: providers,
- KeyRing: kr,
- MeshID: meshName,
- Policy: policy,
- limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
- ExternalAddrs: externalMultiaddrs,
+ Host: h,
+ DHT: kadDHT,
+ gater: gater,
+ Providers: providers,
+ KeyRing: kr,
+ MeshID: meshName,
+ Policy: policy,
+ limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
+ ExternalAddrs: externalMultiaddrs,
+ AllowedAudiences: auds,
}
h.Network().Notify(&notifier{hub: hub})
@@ -255,7 +269,7 @@ func (h *Hub) handleEnroll(s network.Stream) {
ctx, cancel := context.WithTimeout(context.Background(), JWTVerificationTimeout)
defer cancel()
- claims, token, err := h.parseAndVerifyJWT(ctx, req.Jwt)
+ claims, token, err := h.parseAndVerifyJWT(ctx, req.Jwt, h.AllowedAudiences)
if err != nil {
logger.Errorw("JWT verification failed", "peer_id", remotePeer, "error", err)
samHubEnrollmentTotal.WithLabelValues("failed").Inc()
@@ -359,18 +373,26 @@ func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg s
}
}
-func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string) (jwt.MapClaims, *oidc.IDToken, error) {
+func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string, allowedAudiences []string) (jwt.MapClaims, *oidc.IDToken, error) {
jwtParser := jwt.Parser{}
jwtToken, _, err := jwtParser.ParseUnverified(jwtStr, jwt.MapClaims{})
if err != nil {
return nil, nil, fmt.Errorf("failed to parse JWT: %w", err)
}
+
+ // 1. Defend against downgrade attacks immediately
+ alg, ok := jwtToken.Header["alg"].(string)
+ if !ok || alg == "" || strings.ToLower(alg) == "none" {
+ return nil, nil, fmt.Errorf("invalid or missing alg header")
+ }
+
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok {
return nil, nil, fmt.Errorf("invalid JWT claims")
}
iss, _ := claims["iss"].(string)
+ // 2. Extract the audience
var aud string
switch a := claims["aud"].(type) {
case string:
@@ -385,27 +407,35 @@ func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string) (jwt.MapClai
return nil, nil, fmt.Errorf("missing aud claim")
}
- alg, ok := jwtToken.Header["alg"].(string)
- if !ok || alg == "" {
- return nil, nil, fmt.Errorf("missing alg header")
+ // 3. Verify the audience matches one of your expected tenants/platforms
+ validAudience := false
+ for _, allowed := range allowedAudiences {
+ if aud == allowed {
+ validAudience = true
+ break
+ }
+ }
+ if !validAudience {
+ return nil, nil, fmt.Errorf("untrusted audience: %s", aud)
}
+ // 4. Route to the correct provider
provider, ok := h.Providers[iss]
if !ok {
return nil, nil, fmt.Errorf("unknown issuer: %s", iss)
}
- verifier := provider.Verifier(&oidc.Config{ClientID: clientID})
+ // 5. Verify cryptographic signature, bypassing the strict single-clientID check
+ // because we already validated the audience against our allowed list above.
+ verifier := provider.Verifier(&oidc.Config{
+ SkipClientIDCheck: true,
+ })
token, err := verifier.Verify(ctx, jwtStr)
if err != nil {
return nil, nil, fmt.Errorf("JWT validation failed: %w", err)
}
- if alg == "none" {
- return nil, nil, fmt.Errorf("invalid alg claim")
- }
-
return claims, token, nil
}
@@ -672,6 +702,7 @@ func main() {
rootCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/8080/quic-v1", "/ip4/0.0.0.0/tcp/8080"}, "libp2p Listen Addrs")
rootCmd.Flags().StringSliceVar(&externalMultiaddrs, "external-multiaddr", []string{}, "External multiaddrs to announce")
rootCmd.Flags().StringVar(&meshName, "mesh", DefaultMeshName, "Mesh federation name")
+ rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")
rootCmd.Flags().BoolVar(&insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "Skip TLS verification for OIDC issuers")
rootCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")
rootCmd.Flags().StringVar(&policyFile, "policy-file", DefaultPolicyFile, "Path to policies.yaml")
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 983cfdc8..81c45119 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -39,7 +39,7 @@ const (
DefaultMeshName = "public-mesh"
DefaultDiscoveryInterval = "2s"
DefaultHubURL = "http://localhost:8080"
- DefaultConfigFile = "sam-node.yaml"
+ DefaultConfigFile = "sam-node.yaml"
// Renewal timing defaults
DefaultRenewalFallback = 50 * time.Minute
@@ -56,13 +56,15 @@ var (
clientIDFlag string
clientSecretFlag string
tokenURLFlag string
+ deviceAuthURLFlag string
+ audienceFlag string
hubPublicKeyFlag string
bindAddrFlag string
meshFlag string
discoveryIntervalFlag string
enableRelayFlag bool
logLevelFlag string
- configFile string
+ configFile string
keyGracePeriodFlag time.Duration
apiTokenFlag string
@@ -161,7 +163,7 @@ func main() {
if len(token) == 0 {
logger.Fatal("No JWT or stored identity found. Cannot authenticate.")
}
- fmt.Println("Using stored identity.")
+ logger.Infoln("Using stored identity.")
if len(hubPubKey) == 0 {
logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")
@@ -172,6 +174,7 @@ func main() {
logger.Fatalf("Failed to start mesh node: %v", err)
}
} else {
+ // We have a new JWT (from flag or interactive login), need to enroll
var initHubAddrs []multiaddr.Multiaddr
ma, err := multiaddr.NewMultiaddr(hubAddr)
if err == nil {
@@ -256,12 +259,20 @@ func main() {
}
}()
- if tokenURLFlag == "" {
- logger.Fatal("--token-url is required for login")
- }
-
dummyNode := &SamNode{Store: store}
- jwtStr, err := dummyNode.InteractiveLogin(ctx, tokenURLFlag)
+ deviceAuthURL := deviceAuthURLFlag
+ if deviceAuthURL == "" {
+ deviceAuthURL = "https://oauth2.googleapis.com/device/code"
+ }
+ tokenURL := tokenURLFlag
+ if tokenURL == "" {
+ tokenURL = "https://oauth2.googleapis.com/token"
+ }
+ clientID := clientIDFlag
+ if clientID == "" {
+ clientID = api.DefaultAudience
+ }
+ jwtStr, err := dummyNode.InteractiveLogin(ctx, deviceAuthURL, tokenURL, clientID, audienceFlag)
if err != nil {
logger.Fatalf("Failed to get token: %v", err)
}
@@ -322,6 +333,8 @@ func main() {
rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", DefaultHubURL, "Hub URL")
rootCmd.PersistentFlags().StringVar(&configFile, "config", DefaultConfigFile, "Path to sam-node.yaml configuration file")
rootCmd.PersistentFlags().StringVar(&tokenURLFlag, "token-url", "", "OIDC Token URL")
+ rootCmd.PersistentFlags().StringVar(&deviceAuthURLFlag, "device-auth-url", "", "OIDC Device Authorization URL")
+ rootCmd.PersistentFlags().StringVar(&audienceFlag, "audience", api.DefaultAudience, "OIDC Audience")
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(loginCmd)
diff --git a/cmd/sam-node/oidc.go b/cmd/sam-node/oidc.go
index 54a79476..9e47b494 100644
--- a/cmd/sam-node/oidc.go
+++ b/cmd/sam-node/oidc.go
@@ -15,11 +15,14 @@
package main
import (
- "bufio"
"context"
+ "encoding/json"
"fmt"
- "os"
+ "io"
+ "net/http"
+ "net/url"
"strings"
+ "time"
"golang.org/x/oauth2/clientcredentials"
)
@@ -38,27 +41,140 @@ func (n *SamNode) FetchJWT(ctx context.Context, tokenURL, clientID, clientSecret
return token.AccessToken, nil
}
-// InteractiveLogin prompts the user to go to a URL and paste the token back.
-func (n *SamNode) InteractiveLogin(ctx context.Context, tokenURL string) (string, error) {
+// InteractiveLogin prompts the user to go to a URL and enter a code.
+func (n *SamNode) InteractiveLogin(ctx context.Context, deviceAuthURL, tokenURL, clientID, audience string) (string, error) {
+ if deviceAuthURL == "" {
+ return "", fmt.Errorf("device authorization URL is required")
+ }
+ if tokenURL == "" {
+ return "", fmt.Errorf("token URL is required")
+ }
+ if clientID == "" {
+ return "", fmt.Errorf("client ID is required for device flow")
+ }
+
+ data := url.Values{}
+ data.Set("client_id", clientID)
+ data.Set("scope", "openid email profile")
+ if audience != "" {
+ data.Set("audience", audience)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", deviceAuthURL, strings.NewReader(data.Encode()))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ client := &http.Client{}
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ logger.Errorf("Failed to close response body: %v", err)
+ }
+ }()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return "", fmt.Errorf("device auth request failed: %s - %s", resp.Status, string(body))
+ }
+
+ var authResp struct {
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ VerificationURI string `json:"verification_uri"`
+ ExpiresIn int `json:"expires_in"`
+ Interval int `json:"interval"`
+ }
+
+ if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
+ return "", err
+ }
+
fmt.Println("------------------------------------------------------------")
fmt.Println("Device Authorization Flow")
fmt.Println("------------------------------------------------------------")
fmt.Printf("To authenticate, please go to the following URL in your browser:\n\n")
- fmt.Printf(" %s\n\n", tokenURL)
- fmt.Println("After successful login, copy the token and paste it below.")
+ fmt.Printf(" %s\n\n", authResp.VerificationURI)
+ fmt.Printf("And enter the following code:\n\n")
+ fmt.Printf(" %s\n\n", authResp.UserCode)
+ fmt.Println("Waiting for authorization...")
fmt.Println("------------------------------------------------------------")
- fmt.Print("Enter JWT Token: ")
- reader := bufio.NewReader(os.Stdin)
- token, err := reader.ReadString('\n')
- if err != nil {
- return "", fmt.Errorf("failed to read token: %v", err)
+ interval := authResp.Interval
+ if interval <= 0 {
+ interval = 5
}
- token = strings.TrimSpace(token)
- if token == "" {
- return "", fmt.Errorf("empty token provided")
- }
+ ticker := time.NewTicker(time.Duration(interval) * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-ticker.C:
+ pollData := url.Values{}
+ pollData.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
+ pollData.Set("device_code", authResp.DeviceCode)
+ pollData.Set("client_id", clientID)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(pollData.Encode()))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
- return token, nil
+ if resp.StatusCode == http.StatusOK {
+ var tokenResp struct {
+ AccessToken string `json:"access_token"`
+ IdToken string `json:"id_token"`
+ }
+ err := json.NewDecoder(resp.Body).Decode(&tokenResp)
+ if closeErr := resp.Body.Close(); closeErr != nil {
+ logger.Errorf("Failed to close response body: %v", closeErr)
+ }
+ if err != nil {
+ return "", err
+ }
+ if tokenResp.IdToken != "" {
+ return tokenResp.IdToken, nil
+ }
+ return tokenResp.AccessToken, nil
+ }
+
+ var errResp struct {
+ Error string `json:"error"`
+ }
+ err = json.NewDecoder(resp.Body).Decode(&errResp)
+ if closeErr := resp.Body.Close(); closeErr != nil {
+ logger.Errorf("Failed to close response body: %v", closeErr)
+ }
+ if err != nil {
+ return "", fmt.Errorf("token request failed with status %s", resp.Status)
+ }
+
+ switch errResp.Error {
+ case "authorization_pending":
+ continue
+ case "slow_down":
+ ticker.Reset(time.Duration(interval+5) * time.Second)
+ continue
+ case "expired_token":
+ return "", fmt.Errorf("device code expired")
+ case "access_denied":
+ return "", fmt.Errorf("access denied by user")
+ default:
+ return "", fmt.Errorf("token request failed: %s", errResp.Error)
+ }
+ }
+ }
}
diff --git a/cmd/sam-node/oidc_test.go b/cmd/sam-node/oidc_test.go
new file mode 100644
index 00000000..eed5b009
--- /dev/null
+++ b/cmd/sam-node/oidc_test.go
@@ -0,0 +1,94 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestInteractiveLogin(t *testing.T) {
+ // Mock OIDC server
+ mux := http.NewServeMux()
+
+ // State for polling
+ var authorized atomic.Bool
+
+ mux.HandleFunc("/device/code", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]interface{}{
+ "device_code": "dev_code_123",
+ "user_code": "ABCD-1234",
+ "verification_uri": "http://example.com/verify",
+ "expires_in": 60,
+ "interval": 1, // Fast polling for test
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ })
+
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+
+ if !authorized.Load() {
+ w.WriteHeader(http.StatusBadRequest)
+ if err := json.NewEncoder(w).Encode(map[string]string{
+ "error": "authorization_pending",
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ return
+ }
+
+ if err := json.NewEncoder(w).Encode(map[string]string{
+ "access_token": "access_token_xyz",
+ "id_token": "id_token_abc",
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ })
+
+ server := httptest.NewServer(mux)
+ defer server.Close()
+
+ node := &SamNode{}
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ // Run InteractiveLogin in a goroutine because it blocks
+ type result struct {
+ token string
+ err error
+ }
+ resChan := make(chan result, 1)
+
+ go func() {
+ token, err := node.InteractiveLogin(ctx, server.URL+"/device/code", server.URL+"/token", "client_id_test", "sam-e2e")
+ resChan <- result{token, err}
+ }()
+
+ // Wait a bit and then authorize the user
+ time.Sleep(1500 * time.Millisecond)
+ authorized.Store(true)
+
+ res := <-resChan
+ if res.err != nil {
+ t.Fatalf("InteractiveLogin failed: %v", res.err)
+ }
+
+ if res.token != "id_token_abc" {
+ t.Errorf("Expected token 'id_token_abc', got '%s'", res.token)
+ }
+}
diff --git a/tests/e2e/auth_flows.bats b/tests/e2e/auth_flows.bats
index 42d4b2a3..078fd8aa 100644
--- a/tests/e2e/auth_flows.bats
+++ b/tests/e2e/auth_flows.bats
@@ -60,7 +60,7 @@ teardown() {
-v "${data_vol}:/root/.config/sam-mesh" \
-i \
"sam-node:local" \
- login --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" --token-url "http://mock-oidc:18080/token"
+ login --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" --token-url "http://mock-oidc:18080/token" --device-auth-url "http://mock-oidc:18080/device/code"
# Now run the node with the stored identity
docker run -d \
diff --git a/tests/e2e/docker/mock_oidc.py b/tests/e2e/docker/mock_oidc.py
index add3cfda..6caf867e 100644
--- a/tests/e2e/docker/mock_oidc.py
+++ b/tests/e2e/docker/mock_oidc.py
@@ -58,6 +58,7 @@ class Handler(BaseHTTPRequestHandler):
'issuer': 'http://mock-oidc:18080',
'authorization_endpoint': 'http://mock-oidc:18080/auth',
'token_endpoint': 'http://mock-oidc:18080/token',
+ 'device_authorization_endpoint': 'http://mock-oidc:18080/device/code',
'jwks_uri': 'http://mock-oidc:18080/keys'
}
data = json.dumps(body).encode('utf-8')
@@ -80,10 +81,25 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(b'ok')
def do_POST(self):
+ if self.path == '/device/code':
+ body = {
+ 'device_code': 'dev_code_123',
+ 'user_code': 'ABCD-1234',
+ 'verification_uri': 'http://example.com/verify',
+ 'expires_in': 60,
+ 'interval': 1
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
if self.path == '/token':
payload = {
'iss': 'http://mock-oidc:18080',
- 'aud': 'sam-e2e',
+ 'aud': 'sam-mesh-audience',
'sub': 'test-user',
'exp': int(time.time()) + 3600,
'roles': ['admin', 'user']
@@ -91,6 +107,7 @@ class Handler(BaseHTTPRequestHandler):
token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers={'kid': 'test-key-id'})
body = {
'access_token': token,
+ 'id_token': token,
'token_type': 'Bearer',
'expires_in': 3600
}
diff --git a/tests/e2e/kind_wi.bats b/tests/e2e/kind_wi.bats
index 55d48ab2..15cd0ece 100644
--- a/tests/e2e/kind_wi.bats
+++ b/tests/e2e/kind_wi.bats
@@ -88,7 +88,7 @@ metadata:
name: sam-hub-config
data:
SAM_OIDC_ISSUER: "${issuer}"
- SAM_OIDC_ID: "sam-hub-audience"
+ SAM_OIDC_ID: "sam-mesh-audience"
SAM_HUB_KEY: "0000000000000000000000000000000000000000000000000000000000000000"
---
apiVersion: apps/v1
@@ -190,7 +190,7 @@ spec:
- serviceAccountToken:
path: sam-token
expirationSeconds: 3600
- audience: "sam-hub-audience"
+ audience: "sam-mesh-audience"
EOF
# Wait for Node to be ready
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index df8b5106..40326404 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -209,6 +209,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
"sam-hub:local" \
--issuer "http://mock-oidc:18080" \
--client-id "sam-e2e" \
+ --allowed-audiences "sam-e2e" \
--key "${key}" \
--listen "/ip4/0.0.0.0/udp/4001/quic-v1" \
--listen "/ip4/0.0.0.0/tcp/4002" \
@@ -240,7 +241,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
/usr/local/bin/sam-node run \
${flags} \
--hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
- --client-id "sam-e2e" \
+ --client-id "sam-mesh-audience" \
--client-secret "sam-e2e-secret" \
--token-url "http://mock-oidc:18080/token" \
--listen "/ip4/0.0.0.0/udp/5001/quic-v1" \
diff --git a/tests/integration/login_test.go b/tests/integration/login_test.go
index c9869df7..e142c0ab 100644
--- a/tests/integration/login_test.go
+++ b/tests/integration/login_test.go
@@ -16,6 +16,9 @@ package integration_test
import (
"context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
@@ -32,19 +35,43 @@ func TestSamNodeLogin(t *testing.T) {
"XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),
)
- // We simulate the user pasting the token followed by a newline.
- stdin := "test-jwt-token\n"
+ // Mock OIDC server for device flow
+ mux := http.NewServeMux()
+ mux.HandleFunc("/device/code", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]interface{}{
+ "device_code": "dev_code_123",
+ "user_code": "ABCD-1234",
+ "verification_uri": "http://example.com/verify",
+ "expires_in": 60,
+ "interval": 1,
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ })
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]string{
+ "access_token": "test-jwt-token",
+ "id_token": "test-jwt-token",
+ }); err != nil {
+ t.Errorf("Failed to encode response: %v", err)
+ }
+ })
+ server := httptest.NewServer(mux)
+ defer server.Close()
stdout, stderr, err := runCommand(
t,
repoRoot(t),
5*time.Second,
env,
- stdin,
+ "", // No stdin needed
nodeBin,
"login",
"--hub", hubAddr,
- "--token-url", "http://example.com/token",
+ "--token-url", server.URL+"/token",
+ "--device-auth-url", server.URL+"/device/code",
)
if err != nil {
t.Fatalf("login command failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)