Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cyclops-cs): preserve verified identity on user keys (#7285)

Francesco Bonaccid5d4f50cf4f1
diff --git a/libs/fleet/backend/auth/auth.go b/libs/fleet/backend/auth/auth.go
index 34fa07d9c7..c10ca48a5d 100644
--- a/libs/fleet/backend/auth/auth.go
+++ b/libs/fleet/backend/auth/auth.go
@@ -261,6 +261,10 @@ func validateKeycloak(raw string) (*User, error) {
"preferred_username": str(claims, "preferred_username"),
"user_sub": str(claims, "user_sub"),
"user_groups": str(claims, "user_groups"),
+ "user_email": str(claims, "user_email"),
+ "user_email_verified": fmt.Sprint(
+ boolean(claims, "user_email_verified"),
+ ),
},
}, nil
}
diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.go
index 0c151485c2..21b9776db0 100644
--- a/libs/fleet/backend/auth/middlewares.go
+++ b/libs/fleet/backend/auth/middlewares.go
@@ -718,6 +718,10 @@ func applyUserKeyIdentity(user *User, userKeyPfx string) error {
}
user.ID = userSub
user.PrincipalType = PrincipalTypeUserKey
+ // Ignore any service-account email claims. Only the creation-time owner
+ // evidence stamped by the backend may classify a user-key request.
+ user.Email = strings.TrimSpace(user.Claims["user_email"])
+ user.EmailVerified = user.Email != "" && user.Claims["user_email_verified"] == "true"
if userGroups := user.Claims["user_groups"]; userGroups != "" {
user.Groups = strings.Split(userGroups, ",")
}
diff --git a/libs/fleet/backend/auth/user_key_test.go b/libs/fleet/backend/auth/user_key_test.go
index 6ad5074767..60bd6a9dea 100644
--- a/libs/fleet/backend/auth/user_key_test.go
+++ b/libs/fleet/backend/auth/user_key_test.go
@@ -9,11 +9,15 @@ func TestApplyUserKeyIdentity(t *testing.T) {
t.Run("maps owner identity", func(t *testing.T) {
user := &User{
ID: "service-account-123",
+ Email: "[email protected]",
+ EmailVerified: true,
AZP: "ukey-test123",
PrincipalType: PrincipalTypeUser,
Claims: map[string]string{
- "user_sub": "user-123",
- "user_groups": "group-a,group-b",
+ "user_sub": "user-123",
+ "user_groups": "group-a,group-b",
+ "user_email": "[email protected]",
+ "user_email_verified": "true",
},
}
@@ -29,6 +33,27 @@ func TestApplyUserKeyIdentity(t *testing.T) {
if got := strings.Join(user.Groups, ","); got != "group-a,group-b" {
t.Fatalf("Groups = %q, want group-a,group-b", got)
}
+ if user.Email != "[email protected]" || !user.EmailVerified {
+ t.Fatalf("owner email evidence was not applied: email=%q verified=%v", user.Email, user.EmailVerified)
+ }
+ })
+
+ t.Run("old keys remain unknown instead of using service account email", func(t *testing.T) {
+ user := &User{
+ ID: "service-account-123",
+ Email: "[email protected]",
+ EmailVerified: true,
+ AZP: "ukey-test123",
+ PrincipalType: PrincipalTypeUser,
+ Claims: map[string]string{"user_sub": "user-123"},
+ }
+
+ if err := applyUserKeyIdentity(user, "ukey-"); err != nil {
+ t.Fatalf("applyUserKeyIdentity() error = %v", err)
+ }
+ if user.Email != "" || user.EmailVerified {
+ t.Fatalf("service account email leaked into owner identity: email=%q verified=%v", user.Email, user.EmailVerified)
+ }
})
t.Run("rejects missing owner identity", func(t *testing.T) {
diff --git a/libs/fleet/backend/handlers/user_keys.go b/libs/fleet/backend/handlers/user_keys.go
index a802bd06e5..8d907a52c5 100644
--- a/libs/fleet/backend/handlers/user_keys.go
+++ b/libs/fleet/backend/handlers/user_keys.go
@@ -70,7 +70,7 @@ func (h Handlers) CreateUserKey(w http.ResponseWriter, r *http.Request) {
}
}
- cid, secret, _, err := h.Admin.CreateUserKeyClient(r.Context(), req.Name, user.ID, req.Scope)
+ cid, secret, _, err := h.Admin.CreateUserKeyClient(r.Context(), req.Name, user.ID, user.Email, user.EmailVerified, req.Scope)
if err != nil {
writeErr(w, http.StatusInternalServerError, "keycloak: "+err.Error())
return
diff --git a/libs/fleet/backend/handlers/user_keys_test.go b/libs/fleet/backend/handlers/user_keys_test.go
index fc1f9c8000..c7cf692174 100644
--- a/libs/fleet/backend/handlers/user_keys_test.go
+++ b/libs/fleet/backend/handlers/user_keys_test.go
@@ -56,12 +56,24 @@ func TestListUserKeysSerializesEmptyScopeAsArray(t *testing.T) {
func TestCreateUserKeyReturnsConfiguredPublicTokenURL(t *testing.T) {
var keycloakServer *httptest.Server
+ createdClaims := map[string]string{}
keycloakServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/realms/cyclops-cs/protocol/openid-connect/token":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"admin-token","token_type":"Bearer","expires_in":300}`))
case "/admin/realms/cyclops-cs/clients":
+ var request struct {
+ ProtocolMappers []struct {
+ Config map[string]string `json:"config"`
+ } `json:"protocolMappers"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ t.Fatalf("decode Keycloak client: %v", err)
+ }
+ for _, mapper := range request.ProtocolMappers {
+ createdClaims[mapper.Config["claim.name"]] = mapper.Config["claim.value"]
+ }
w.Header().Set("Location", keycloakServer.URL+"/admin/realms/cyclops-cs/clients/user-key-client")
w.WriteHeader(http.StatusCreated)
case "/admin/realms/cyclops-cs/clients/user-key-client/client-secret":
@@ -79,7 +91,7 @@ func TestCreateUserKeyReturnsConfiguredPublicTokenURL(t *testing.T) {
KC: config.KeycloakConfiguration{TokenURL: publicTokenURL},
}
r := httptest.NewRequest(http.MethodPost, "/api/user-keys", bytes.NewBufferString(`{"name":"ci-key"}`))
- r = withUser(r, &auth.User{ID: "user-123"})
+ r = withUser(r, &auth.User{ID: "user-123", Email: "[email protected]", EmailVerified: true})
w := httptest.NewRecorder()
h.CreateUserKey(w, r)
@@ -94,4 +106,7 @@ func TestCreateUserKeyReturnsConfiguredPublicTokenURL(t *testing.T) {
if got := response.TokenURL; got != publicTokenURL {
t.Fatalf("token_url = %q, want %q", got, publicTokenURL)
}
+ if createdClaims["user_email"] != "[email protected]" || createdClaims["user_email_verified"] != "true" {
+ t.Fatalf("verified owner claims = %#v", createdClaims)
+ }
}
diff --git a/libs/fleet/backend/keycloak/admin.go b/libs/fleet/backend/keycloak/admin.go
index 9608bf3a81..16d6f0bf1b 100644
--- a/libs/fleet/backend/keycloak/admin.go
+++ b/libs/fleet/backend/keycloak/admin.go
@@ -265,9 +265,10 @@ type UserKeyClient struct {
}
// CreateUserKeyClient creates a confidential service-account client whose
-// access tokens carry hardcoded `user_sub` and `user_groups` claims.
+// access tokens carry hardcoded owner identity claims. Verified email evidence
+// is copied only when it was present on the authenticated creation request.
// Returns the client_id, freshly generated client_secret, and token URL.
-func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub string, scope []string) (clientID, clientSecret, tokenURL string, err error) {
+func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub, ownerEmail string, ownerEmailVerified bool, scope []string) (clientID, clientSecret, tokenURL string, err error) {
ctx, span := adminTracer().Start(ctx, "keycloak.create_user_key_client", trace.WithAttributes(
attribute.String("keycloak.key_type", "user"),
attribute.String("key.name", name),
@@ -292,6 +293,36 @@ func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub string,
scopeStr := strings.Join(scope, ",")
+ protocolMappers := []gocloak.ProtocolMapperRepresentation{
+ {
+ Name: gocloak.StringP("user_sub"),
+ Protocol: gocloak.StringP("openid-connect"),
+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
+ Config: &map[string]string{
+ "claim.name": "user_sub",
+ "claim.value": ownerSub,
+ "jsonType.label": "String",
+ "access.token.claim": "true",
+ "id.token.claim": "false",
+ "userinfo.token.claim": "false",
+ },
+ },
+ {
+ Name: gocloak.StringP("user_groups"),
+ Protocol: gocloak.StringP("openid-connect"),
+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
+ Config: &map[string]string{
+ "claim.name": "user_groups",
+ "claim.value": identity.ImpersonateGroup(ctx, ownerSub),
+ "jsonType.label": "String",
+ "access.token.claim": "true",
+ "id.token.claim": "false",
+ "userinfo.token.claim": "false",
+ },
+ },
+ }
+ protocolMappers = append(protocolMappers, verifiedUserIdentityMappers(ownerEmail, ownerEmailVerified)...)
+
c := gocloak.Client{
ClientID: gocloak.StringP(clientID),
Name: gocloak.StringP(name),
@@ -309,34 +340,7 @@ func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub string,
"key_type": "user",
"scope": scopeStr,
},
- ProtocolMappers: &[]gocloak.ProtocolMapperRepresentation{
- {
- Name: gocloak.StringP("user_sub"),
- Protocol: gocloak.StringP("openid-connect"),
- ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
- Config: &map[string]string{
- "claim.name": "user_sub",
- "claim.value": ownerSub,
- "jsonType.label": "String",
- "access.token.claim": "true",
- "id.token.claim": "false",
- "userinfo.token.claim": "false",
- },
- },
- {
- Name: gocloak.StringP("user_groups"),
- Protocol: gocloak.StringP("openid-connect"),
- ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
- Config: &map[string]string{
- "claim.name": "user_groups",
- "claim.value": identity.ImpersonateGroup(ctx, ownerSub),
- "jsonType.label": "String",
- "access.token.claim": "true",
- "id.token.claim": "false",
- "userinfo.token.claim": "false",
- },
- },
- },
+ ProtocolMappers: &protocolMappers,
}
kcUUID, err := a.client.CreateClient(ctx, tok, a.realm, c)
@@ -357,6 +361,41 @@ func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub string,
return clientID, *cs.Value, tokenURL, nil
}
+func verifiedUserIdentityMappers(email string, verified bool) []gocloak.ProtocolMapperRepresentation {
+ email = strings.TrimSpace(email)
+ if !verified || email == "" {
+ return nil
+ }
+ return []gocloak.ProtocolMapperRepresentation{
+ {
+ Name: gocloak.StringP("user_email"),
+ Protocol: gocloak.StringP("openid-connect"),
+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
+ Config: &map[string]string{
+ "claim.name": "user_email",
+ "claim.value": email,
+ "jsonType.label": "String",
+ "access.token.claim": "true",
+ "id.token.claim": "false",
+ "userinfo.token.claim": "false",
+ },
+ },
+ {
+ Name: gocloak.StringP("user_email_verified"),
+ Protocol: gocloak.StringP("openid-connect"),
+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),
+ Config: &map[string]string{
+ "claim.name": "user_email_verified",
+ "claim.value": "true",
+ "jsonType.label": "boolean",
+ "access.token.claim": "true",
+ "id.token.claim": "false",
+ "userinfo.token.claim": "false",
+ },
+ },
+ }
+}
+
// ListUserKeyClients returns every user-key client owned by ownerSub.
func (a *Admin) ListUserKeyClients(ctx context.Context, ownerSub string) ([]UserKeyClient, error) {
ctx, span := adminTracer().Start(ctx, "keycloak.list_user_key_clients", trace.WithAttributes(
diff --git a/libs/fleet/backend/keycloak/admin_user_keys_test.go b/libs/fleet/backend/keycloak/admin_user_keys_test.go
new file mode 100644
index 0000000000..1e7fc8c40b
--- /dev/null
+++ b/libs/fleet/backend/keycloak/admin_user_keys_test.go
@@ -0,0 +1,43 @@
+package keycloak
+
+import "testing"
+
+func TestVerifiedUserIdentityMappers(t *testing.T) {
+ t.Run("stamps verified owner evidence", func(t *testing.T) {
+ mappers := verifiedUserIdentityMappers(" [email protected] ", true)
+ if len(mappers) != 2 {
+ t.Fatalf("mappers = %d, want 2", len(mappers))
+ }
+ claims := map[string]map[string]string{}
+ for _, mapper := range mappers {
+ if mapper.Config == nil {
+ t.Fatal("mapper config is nil")
+ }
+ claims[(*mapper.Config)["claim.name"]] = *mapper.Config
+ }
+ if got := claims["user_email"]["claim.value"]; got != "[email protected]" {
+ t.Fatalf("user_email = %q, want trimmed verified email", got)
+ }
+ if got := claims["user_email_verified"]["claim.value"]; got != "true" {
+ t.Fatalf("user_email_verified = %q, want true", got)
+ }
+ if got := claims["user_email_verified"]["jsonType.label"]; got != "boolean" {
+ t.Fatalf("user_email_verified type = %q, want boolean", got)
+ }
+ })
+
+ for _, test := range []struct {
+ name string
+ email string
+ verified bool
+ }{
+ {name: "unverified", email: "[email protected]"},
+ {name: "missing email", verified: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ if got := verifiedUserIdentityMappers(test.email, test.verified); len(got) != 0 {
+ t.Fatalf("mappers = %d, want 0", len(got))
+ }
+ })
+ }
+}