Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions service/integration/attributes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1573,6 +1573,44 @@ func (s *AttributesSuite) Test_GetKeyMappingsByFqns() {
validateSimpleKasKey(&s.Suite, kasKey, mappings[fqnAlpha].GetKeys()[0])
}

func (s *AttributesSuite) Test_GetEntitleableAttributesByFqns() {
value1 := s.f.GetAttributeValueKey("example.com/attr/attr1/value/value1")
value2 := s.f.GetAttributeValueKey("example.com/attr/attr1/value/value2")
fqn1 := "https://example.com/attr/attr1/value/value1"
fqn2 := "https://example.com/attr/attr1/value/value2"

resp, err := s.db.PolicyClient.GetEntitleableAttributesByFqns(s.ctx, &attributes.GetEntitleableAttributesByFqnsRequest{
Fqns: []string{fqn1, fqn2},
})
s.Require().NoError(err)
s.Len(resp, 2)

e1 := resp[fqn1]
s.Require().NotNil(e1)
s.Equal(fqn1, e1.GetFqn())
s.Equal("https://example.com/attr/attr1", e1.GetAttributeFqn())
s.Equal(value1.ID, e1.GetValueId())
s.NotEqual(policy.AttributeRuleTypeEnum_ATTRIBUTE_RULE_TYPE_ENUM_UNSPECIFIED, e1.GetRule())
s.Contains(e1.GetDefinitionValueFqns(), fqn1)
s.Contains(e1.GetDefinitionValueFqns(), fqn2)
// value1 has multiple value-level subject mappings in the fixtures; every
// returned mapping must belong to value1 (verifies grouping by FQN).
s.GreaterOrEqual(len(e1.GetSubjectMappings()), 3)
for _, sm := range e1.GetSubjectMappings() {
s.Equal(fqn1, sm.GetAttributeValue().GetFqn())
s.NotEmpty(sm.GetId())
s.NotNil(sm.GetSubjectConditionSet())
}

e2 := resp[fqn2]
s.Require().NotNil(e2)
s.Equal(value2.ID, e2.GetValueId())
s.GreaterOrEqual(len(e2.GetSubjectMappings()), 1)
for _, sm := range e2.GetSubjectMappings() {
s.Equal(fqn2, sm.GetAttributeValue().GetFqn())
}
}

func (s *AttributesSuite) Test_UnsafeUpdateAttribute_NormalizesCasing() {
created, err := s.db.PolicyClient.CreateAttribute(s.ctx, &attributes.CreateAttributeRequest{
Name: "BANANA_PUDDING",
Expand Down
17 changes: 11 additions & 6 deletions service/policy/attributes/attributes.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,16 +189,21 @@ func (s *AttributesService) GetKeyMappingsByFqns(ctx context.Context,
return connect.NewResponse(rsp), nil
}

// GetEntitleableAttributesByFqns is defined in the proto but implemented in a
// follow-up change (the server-side decisioning migration). It returns
// Unimplemented until then.
func (s *AttributesService) GetEntitleableAttributesByFqns(ctx context.Context,
_ *connect.Request[attributes.GetEntitleableAttributesByFqnsRequest],
req *connect.Request[attributes.GetEntitleableAttributesByFqnsRequest],
) (*connect.Response[attributes.GetEntitleableAttributesByFqnsResponse], error) {
_, span := s.Start(ctx, "GetEntitleableAttributesByFqns")
ctx, span := s.Start(ctx, "GetEntitleableAttributesByFqns")
defer span.End()

return nil, connect.NewError(connect.CodeUnimplemented, errors.New("GetEntitleableAttributesByFqns is not yet implemented"))
rsp := &attributes.GetEntitleableAttributesByFqnsResponse{}

entitleable, err := s.dbClient.GetEntitleableAttributesByFqns(ctx, req.Msg)
if err != nil {
return nil, db.StatusifyError(ctx, s.logger, err, db.ErrTextGetRetrievalFailed, slog.String("fqns", fmt.Sprintf("%v", req.Msg.GetFqns())))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use slog.Any instead of slog.String with fmt.Sprintf to log the slice of FQNs. This is cleaner, more idiomatic, and avoids string formatting overhead.

Suggested change
return nil, db.StatusifyError(ctx, s.logger, err, db.ErrTextGetRetrievalFailed, slog.String("fqns", fmt.Sprintf("%v", req.Msg.GetFqns())))
return nil, db.StatusifyError(ctx, s.logger, err, db.ErrTextGetRetrievalFailed, slog.Any("fqns", req.Msg.GetFqns()))

}
rsp.FqnEntitleableAttributes = entitleable

return connect.NewResponse(rsp), nil
}

func (s *AttributesService) UpdateAttribute(ctx context.Context,
Expand Down
99 changes: 99 additions & 0 deletions service/policy/db/attribute_fqn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package db

import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strings"
Expand Down Expand Up @@ -233,6 +234,104 @@ func (c *PolicyDBClient) GetKeyMappingsByFqns(ctx context.Context, r *attributes
return mappings, nil
}

// GetEntitleableAttributesByFqns returns, for each requested attribute value FQN,
// the information needed to resolve entitlements: the attribute rule, the value
// identity, the definition's ordered value FQNs (for hierarchy rule logic), and
// the value-level subject mappings. It runs two selective queries: the attribute
// FQN lookup for rule/value/sibling data, and a single subject-mapping-by-FQN
// query, avoiding the full-policy load used by the entitlement path today.
func (c *PolicyDBClient) GetEntitleableAttributesByFqns(ctx context.Context, r *attributes.GetEntitleableAttributesByFqnsRequest) (map[string]*attributes.GetEntitleableAttributesByFqnsResponse_EntitleableAttribute, error) {
ctx, span := c.Start(ctx, "DB:GetEntitleableAttributesByFqns")
defer span.End()

fqns := r.GetFqns()
normalized := make([]string, len(fqns))
for i, fqn := range fqns {
normalized[i] = strings.ToLower(fqn)
}
Comment on lines +247 to +251

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If the requested slice of FQNs is empty, we can return early and avoid executing any database queries.

    fqns := r.GetFqns()
    if len(fqns) == 0 {
        return make(map[string]*attributes.GetEntitleableAttributesByFqnsResponse_EntitleableAttribute), nil
    }
    normalized := make([]string, len(fqns))
    for i, fqn := range fqns {
        normalized[i] = strings.ToLower(fqn)
    }


pairs, err := c.GetAttributesByValueFqns(ctx, &attributes.GetAttributeValuesByFqnsRequest{Fqns: normalized})
if err != nil {
return nil, err
}

// Fetch value-level subject mappings for the requested FQNs in one query and
// group them by the value FQN they map to.
smRows, err := c.queries.getSubjectMappingsByValueFqns(ctx, normalized)
if err != nil {
return nil, db.WrapIfKnownInvalidQueryErr(err)
}
subjectMappingsByFqn := make(map[string][]*policy.SubjectMapping, len(smRows))
for _, row := range smRows {
sm, err := hydrateSubjectMappingForEntitlement(row)
if err != nil {
return nil, err
}
subjectMappingsByFqn[row.ValueFqn] = append(subjectMappingsByFqn[row.ValueFqn], sm)
}

entitleable := make(map[string]*attributes.GetEntitleableAttributesByFqnsResponse_EntitleableAttribute, len(pairs))
for fqn, pair := range pairs {
attr := pair.GetAttribute()

definitionValueFqns := make([]string, 0, len(attr.GetValues()))
for _, v := range attr.GetValues() {
definitionValueFqns = append(definitionValueFqns, v.GetFqn())
}

entitleable[fqn] = &attributes.GetEntitleableAttributesByFqnsResponse_EntitleableAttribute{
Fqn: fqn,
AttributeFqn: attr.GetFqn(),
Rule: attr.GetRule(),
ValueId: pair.GetValue().GetId(),
DefinitionValueFqns: definitionValueFqns,
SubjectMappings: subjectMappingsByFqn[fqn],
}
}

return entitleable, nil
}

// hydrateSubjectMappingForEntitlement converts a getSubjectMappingsByValueFqns
// row into a policy.SubjectMapping, mirroring the hydration in ListSubjectMappings.
func hydrateSubjectMappingForEntitlement(row getSubjectMappingsByValueFqnsRow) (*policy.SubjectMapping, error) {
metadata := &common.Metadata{}
if err := unmarshalMetadata(row.Metadata, metadata); err != nil {
return nil, err
}

av := &policy.Value{}
if err := unmarshalAttributeValue(row.AttributeValue, av); err != nil {
return nil, err
}

stdActionsBytes, err := json.Marshal(row.StandardActions)
if err != nil {
return nil, fmt.Errorf("failed to marshal standard actions: %w", err)
}
customActionsBytes, err := json.Marshal(row.CustomActions)
if err != nil {
return nil, fmt.Errorf("failed to marshal custom actions: %w", err)
}
actions := []*policy.Action{}
if err := unmarshalAllActionsProto(stdActionsBytes, customActionsBytes, &actions); err != nil {
return nil, err
}
Comment on lines +308 to +319

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since row.StandardActions and row.CustomActions are now []byte (thanks to the jsonb cast in SQL), we can completely eliminate the redundant json.Marshal calls. This significantly improves performance by avoiding reflection and extra allocations.

Suggested change
stdActionsBytes, err := json.Marshal(row.StandardActions)
if err != nil {
return nil, fmt.Errorf("failed to marshal standard actions: %w", err)
}
customActionsBytes, err := json.Marshal(row.CustomActions)
if err != nil {
return nil, fmt.Errorf("failed to marshal custom actions: %w", err)
}
actions := []*policy.Action{}
if err := unmarshalAllActionsProto(stdActionsBytes, customActionsBytes, &actions); err != nil {
return nil, err
}
actions := []*policy.Action{}
if err := unmarshalAllActionsProto(row.StandardActions, row.CustomActions, &actions); err != nil {
return nil, err
}


scs := policy.SubjectConditionSet{}
if err := unmarshalSubjectConditionSet(row.SubjectConditionSet, &scs); err != nil {
return nil, err
}

return &policy.SubjectMapping{
Id: row.ID,
Metadata: metadata,
AttributeValue: av,
SubjectConditionSet: &scs,
Actions: actions,
}, nil
}

// resolveEffectiveKasKeys selects the effective mapped KAS keys for a value using
// value > definition > namespace precedence, matching the SDK granter logic in
// sdk/granter.go (newGranterFromService).
Expand Down
60 changes: 60 additions & 0 deletions service/policy/db/queries/subject_mappings.sql
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,66 @@ ORDER BY
LIMIT @limit_
OFFSET @offset_;

-- name: getSubjectMappingsByValueFqns :many
-- Returns value-level subject mappings for the provided attribute value FQNs,
-- for entitlement resolution. Each row carries the value FQN it maps to so the
-- caller can group mappings by FQN. Namespace-level mappings (no attribute value)
-- are excluded by the inner join on attribute_values.
WITH subject_actions AS (
SELECT
sma.subject_mapping_id,
COALESCE(
JSONB_AGG(JSONB_BUILD_OBJECT('id', a.id, 'name', a.name,
'namespace', CASE WHEN a.namespace_id IS NULL THEN NULL
ELSE JSONB_BUILD_OBJECT('id', ans.id, 'name', ans.name, 'fqn', ans_fqns.fqn)
END
)) FILTER (WHERE a.is_standard = TRUE),
'[]'::JSONB
) AS standard_actions,
COALESCE(
JSONB_AGG(JSONB_BUILD_OBJECT('id', a.id, 'name', a.name,
'namespace', CASE WHEN a.namespace_id IS NULL THEN NULL
ELSE JSONB_BUILD_OBJECT('id', ans.id, 'name', ans.name, 'fqn', ans_fqns.fqn)
END
)) FILTER (WHERE a.is_standard = FALSE),
'[]'::JSONB
) AS custom_actions
FROM subject_mapping_actions sma
JOIN actions a ON sma.action_id = a.id
LEFT JOIN attribute_namespaces ans ON ans.id = a.namespace_id
LEFT JOIN attribute_fqns ans_fqns ON ans_fqns.namespace_id = ans.id AND ans_fqns.attribute_id IS NULL AND ans_fqns.value_id IS NULL
GROUP BY sma.subject_mapping_id
)
SELECT
sm.id,
fqns.fqn AS value_fqn,
sa.standard_actions,
sa.custom_actions,
Comment on lines +235 to +239

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

By explicitly casting sa.standard_actions and sa.custom_actions to jsonb in the SQL query, sqlc will generate []byte fields in the Go struct instead of interface{}. This avoids the need to marshal them back to JSON in Go, improving performance and type safety.

SELECT
    sm.id,
    fqns.fqn AS value_fqn,
    sa.standard_actions::jsonb AS standard_actions,
    sa.custom_actions::jsonb AS custom_actions,

JSON_STRIP_NULLS(JSON_BUILD_OBJECT('labels', sm.metadata -> 'labels', 'created_at', sm.created_at, 'updated_at', sm.updated_at)) AS metadata,
JSON_BUILD_OBJECT(
'id', scs.id,
'metadata', JSON_STRIP_NULLS(JSON_BUILD_OBJECT('labels', scs.metadata->'labels', 'created_at', scs.created_at, 'updated_at', scs.updated_at)),
'subject_sets', scs.condition,
'namespace', CASE
WHEN scs.namespace_id IS NULL THEN NULL
ELSE JSON_BUILD_OBJECT('id', scs_ns.id, 'name', scs_ns.name, 'fqn', scs_ns_fqns.fqn)
END
) AS subject_condition_set,
JSON_BUILD_OBJECT(
'id', av.id,
'value', av.value,
'active', av.active,
'fqn', fqns.fqn
) AS attribute_value
FROM subject_mappings sm
JOIN attribute_values av ON sm.attribute_value_id = av.id
JOIN attribute_fqns fqns ON av.id = fqns.value_id
LEFT JOIN subject_actions sa ON sm.id = sa.subject_mapping_id
LEFT JOIN subject_condition_set scs ON scs.id = sm.subject_condition_set_id
LEFT JOIN attribute_namespaces scs_ns ON scs_ns.id = scs.namespace_id
LEFT JOIN attribute_fqns scs_ns_fqns ON scs_ns_fqns.namespace_id = scs_ns.id AND scs_ns_fqns.attribute_id IS NULL AND scs_ns_fqns.value_id IS NULL
WHERE fqns.fqn = ANY(@value_fqns::TEXT[]);

-- name: getSubjectMapping :one
SELECT
sm.id,
Expand Down
Loading
Loading