Skip to content
Open
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
2 changes: 2 additions & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ type PermitApiClient struct {
RoleAssignments *RoleAssignments
Roles *Roles
Tenants *Tenants
UserAttributes *UserAttributes
Users *Users
}

Expand Down Expand Up @@ -198,6 +199,7 @@ func NewPermitApiClient(config *config.PermitConfig) *PermitApiClient {
RoleAssignments: NewRoleAssignmentsApi(client, config),
Roles: NewRolesApi(client, config),
Tenants: NewTenantsApi(client, config),
UserAttributes: NewUserAttributesApi(client, config),
Users: NewUsersApi(client, config),
}
}
Expand Down
153 changes: 153 additions & 0 deletions pkg/api/userAttributes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package api

import (
"context"

"github.com/google/uuid"
"github.com/permitio/permit-golang/pkg/config"
"github.com/permitio/permit-golang/pkg/errors"
"github.com/permitio/permit-golang/pkg/models"
"github.com/permitio/permit-golang/pkg/openapi"
"go.uber.org/zap"
)

// DefaultUserAttributeResourceID is the default resource_id query parameter for user schema attributes (V2 API).
const DefaultUserAttributeResourceID = "__user"

type UserAttributes struct {
permitBaseApi
}

func NewUserAttributesApi(client *openapi.APIClient, config *config.PermitConfig) *UserAttributes {
return &UserAttributes{
permitBaseApi: permitBaseApi{
client: client,
config: config,
logger: config.Logger,
},
}
}

// List returns all user attributes for the User resource (resource_id __user).
//
// attrs, err := PermitClient.Api.UserAttributes.List(ctx, 1, 30)
func (a *UserAttributes) List(ctx context.Context, page int, perPage int) ([]models.UserAttributeRead, error) {
return a.ListForResource(ctx, DefaultUserAttributeResourceID, page, perPage)
}

// ListForResource lists user attributes when using a non-default user resource id.
func (a *UserAttributes) ListForResource(ctx context.Context, resourceID string, page int, perPage int) ([]models.UserAttributeRead, error) {
perPageLimit := int32(DefaultPerPageLimit)
if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) {
err := errors.NewPermitPaginationError()
a.logger.Error("error listing user attributes - max per page exceeded", zap.Error(err))
return nil, err
}
err := a.lazyLoadPermitContext(ctx)
if err != nil {
return nil, err
}
attrs, _, err := a.client.UserAttributesApi.ListUserAttributes(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment()).

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.

Same errors.HttpErrorHandle gap applies to all five *ForResource methods in this file (lines 50, 72, 106, 126, 146). Each discards the *http.Response with _ instead of passing it through errors.HttpErrorHandle(err, httpRes) like every other API method in the codebase.

See the comment on line 55 for the full explanation and suggested fix.

ResourceId(resourceID).Page(int32(page)).PerPage(int32(perPage)).Execute()
if err != nil {
a.logger.Error("error listing user attributes", zap.Error(err))
return nil, err
}
Comment on lines +50 to +55

Copilot AI Mar 19, 2026

Copy link

Choose a reason for hiding this comment

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

UserAttributes API methods are discarding the *http.Response from the OpenAPI client and returning the raw error. This bypasses errors.HttpErrorHandle (used across most other pkg/api clients) and can cause callers to miss structured PermitError types/status codes. Capture the response from Execute() and pass (err, httpRes) through errors.HttpErrorHandle in List/Get/Create/Update/Delete (incl. the ForResource variants).

Copilot uses AI. Check for mistakes.

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.

HTTP response discarded — missing errors.HttpErrorHandle call

Every other API wrapper in this codebase (see resources.go, roles.go, tenants.go, users.go, etc.) captures the *http.Response return value and passes it through errors.HttpErrorHandle(err, httpRes). This converts HTTP status codes into the SDK's typed error hierarchy (PermitNotFoundError, PermitConflictError, PermitForbiddenError, etc.).

In userAttributes.go, all five methods (ListForResource, GetForResource, CreateForResource, UpdateForResource, DeleteForResource) discard the HTTP response with _, so callers receive raw OpenAPI errors instead of typed PermitError values. This breaks error handling for any consumer that uses type assertions or checks ErrorCode on the returned error.

Suggestion: Capture the *http.Response and call errors.HttpErrorHandle, matching the pattern used everywhere else:

attrs, httpRes, err := a.client.UserAttributesApi.ListUserAttributes(...).Execute()
err = errors.HttpErrorHandle(err, httpRes)
if err != nil {
    a.logger.Error("error listing user attributes", zap.Error(err))
    return nil, err
}

Apply the same fix to all five ForResource methods.

return attrs, nil
}

// Get returns a user attribute by id or key (slug).
//
// attr, err := PermitClient.Api.UserAttributes.Get(ctx, "clearance_level")
func (a *UserAttributes) Get(ctx context.Context, attributeIDOrKey string) (*models.UserAttributeRead, error) {
return a.GetForResource(ctx, DefaultUserAttributeResourceID, attributeIDOrKey)
}

// GetForResource gets a user attribute with an explicit resource_id query.
func (a *UserAttributes) GetForResource(ctx context.Context, resourceID, attributeIDOrKey string) (*models.UserAttributeRead, error) {
err := a.lazyLoadPermitContext(ctx)
if err != nil {
return nil, err
}
attr, _, err := a.client.UserAttributesApi.GetUserAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), attributeIDOrKey).
ResourceId(resourceID).Execute()
if err != nil {
a.logger.Error("error getting user attribute: "+attributeIDOrKey, zap.Error(err))
return nil, err
}
return attr, nil
}

// GetByKey is an alias for Get (attribute key is the slug).
func (a *UserAttributes) GetByKey(ctx context.Context, attributeKey string) (*models.UserAttributeRead, error) {
return a.Get(ctx, attributeKey)
}

// GetById gets a user attribute by attribute UUID (uses default user resource __user).
func (a *UserAttributes) GetById(ctx context.Context, attributeID uuid.UUID) (*models.UserAttributeRead, error) {
return a.Get(ctx, attributeID.String())
}

// Create adds a user schema attribute.
//
// create := models.NewUserAttributeCreate("department", models.STRING)
// create.SetDescription("User department")
// attr, err := PermitClient.Api.UserAttributes.Create(ctx, *create)
func (a *UserAttributes) Create(ctx context.Context, body models.UserAttributeCreate) (*models.UserAttributeRead, error) {
return a.CreateForResource(ctx, DefaultUserAttributeResourceID, body)
}

// CreateForResource creates a user attribute with an explicit resource_id query.
func (a *UserAttributes) CreateForResource(ctx context.Context, resourceID string, body models.UserAttributeCreate) (*models.UserAttributeRead, error) {
err := a.lazyLoadPermitContext(ctx)
if err != nil {
return nil, err
}
attr, _, err := a.client.UserAttributesApi.CreateUserAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment()).
UserAttributeCreate(body).ResourceId(resourceID).Execute()
if err != nil {
a.logger.Error("error creating user attribute: "+body.GetKey(), zap.Error(err))
return nil, err
}
return attr, nil
}

// Update partially updates a user attribute (id or key).
func (a *UserAttributes) Update(ctx context.Context, attributeIDOrKey string, body models.UserAttributeUpdate) (*models.UserAttributeRead, error) {
return a.UpdateForResource(ctx, DefaultUserAttributeResourceID, attributeIDOrKey, body)
}

// UpdateForResource updates with an explicit resource_id query.
func (a *UserAttributes) UpdateForResource(ctx context.Context, resourceID, attributeIDOrKey string, body models.UserAttributeUpdate) (*models.UserAttributeRead, error) {
err := a.lazyLoadPermitContext(ctx)
if err != nil {
return nil, err
}
attr, _, err := a.client.UserAttributesApi.UpdateUserAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), attributeIDOrKey).
UserAttributeUpdate(body).ResourceId(resourceID).Execute()
if err != nil {
a.logger.Error("error updating user attribute: "+attributeIDOrKey, zap.Error(err))
return nil, err
}
return attr, nil
}

// Delete removes a user attribute (id or key).
func (a *UserAttributes) Delete(ctx context.Context, attributeIDOrKey string) error {
return a.DeleteForResource(ctx, DefaultUserAttributeResourceID, attributeIDOrKey)
}

// DeleteForResource deletes with an explicit resource_id query.
func (a *UserAttributes) DeleteForResource(ctx context.Context, resourceID, attributeIDOrKey string) error {
err := a.lazyLoadPermitContext(ctx)
if err != nil {
return err
}
_, err = a.client.UserAttributesApi.DeleteUserAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), attributeIDOrKey).
ResourceId(resourceID).Execute()
if err != nil {
a.logger.Error("error deleting user attribute: "+attributeIDOrKey, zap.Error(err))
return err
}
return nil
}
28 changes: 16 additions & 12 deletions pkg/models/model_attribute_type.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions pkg/models/model_user_attribute_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package models

import "encoding/json"

// UserAttributeCreate is the request body for creating a user (schema) attribute.
// It matches the V2 POST /v2/schema/{proj_id}/{env_id}/users/attributes payload.
type UserAttributeCreate struct {
// A URL-friendly name of the attribute (i.e: slug).
Key string `json:"key"`
// The type of the attribute (bool, number, string, time, array, json, object, object_array).
Type AttributeType `json:"type"`
// An optional longer description of what this attribute represents in your system.
Description *string `json:"description,omitempty"`
}

// NewUserAttributeCreate builds a create request with required key and type.
func NewUserAttributeCreate(key string, type_ AttributeType) *UserAttributeCreate {
return &UserAttributeCreate{Key: key, Type: type_}
}

// NewUserAttributeCreateWithDefaults instantiates an empty UserAttributeCreate.
func NewUserAttributeCreateWithDefaults() *UserAttributeCreate {
return &UserAttributeCreate{}
}

func (o *UserAttributeCreate) GetKey() string {
if o == nil {
return ""
}
return o.Key
}

func (o *UserAttributeCreate) SetKey(v string) {
o.Key = v
}

func (o *UserAttributeCreate) GetType() AttributeType {
if o == nil {
return ""
}
return o.Type
}

func (o *UserAttributeCreate) SetType(v AttributeType) {
o.Type = v
}

func (o *UserAttributeCreate) GetDescription() string {
if o == nil || IsNil(o.Description) {
return ""
}
return *o.Description
}

func (o *UserAttributeCreate) SetDescription(v string) {
o.Description = &v
}

func (o UserAttributeCreate) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{"key": o.Key, "type": o.Type}
if !IsNil(o.Description) {
m["description"] = o.Description
}
return json.Marshal(m)
}

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.

Missing HasDescription() method — inconsistent with ResourceAttributeCreate

The existing ResourceAttributeCreate model provides HasDescription() (and *Ok() tuple-return methods) that allow callers to distinguish between "not set" and "set to empty string" for optional fields. UserAttributeCreate only has Get/Set methods and is missing HasDescription(). Since these two types serve the same role (attribute creation) for different resource types, callers will expect the same API surface.

Suggestion: Add HasDescription() to match the existing pattern:

func (o *UserAttributeCreate) HasDescription() bool {
    return o != nil && !IsNil(o.Description)
}

75 changes: 75 additions & 0 deletions pkg/models/model_user_attribute_read.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package models

import (
"encoding/json"
"time"
)

// UserAttributeRead is a user schema attribute as returned by the V2 API.
type UserAttributeRead struct {
Type AttributeType `json:"type"`
Description *string `json:"description,omitempty"`
Key string `json:"key"`
Id string `json:"id"`
ResourceId string `json:"resource_id"`
ResourceKey string `json:"resource_key"`
OrganizationId string `json:"organization_id"`
ProjectId string `json:"project_id"`
EnvironmentId string `json:"environment_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
BuiltIn bool `json:"built_in"`
}

func NewUserAttributeReadWithDefaults() *UserAttributeRead {
return &UserAttributeRead{}
}

func (o *UserAttributeRead) GetKey() string {
if o == nil {
return ""
}
return o.Key
}

func (o *UserAttributeRead) GetId() string {
if o == nil {
return ""
}
return o.Id
}

func (o *UserAttributeRead) GetType() AttributeType {
if o == nil {
return ""
}
return o.Type
}

func (o *UserAttributeRead) GetBuiltIn() bool {
if o == nil {
return false
}
return o.BuiltIn
}

func (o *UserAttributeRead) GetDescription() string {
if o == nil || IsNil(o.Description) {
return ""
}
return *o.Description
}

func (o UserAttributeRead) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"type": o.Type, "key": o.Key, "id": o.Id,
"resource_id": o.ResourceId, "resource_key": o.ResourceKey,
"organization_id": o.OrganizationId, "project_id": o.ProjectId,
"environment_id": o.EnvironmentId, "created_at": o.CreatedAt,
"updated_at": o.UpdatedAt, "built_in": o.BuiltIn,
}
if !IsNil(o.Description) {
m["description"] = o.Description
}
return json.Marshal(m)
}
Comment on lines +3 to +75

Copilot AI Mar 19, 2026

Copy link

Choose a reason for hiding this comment

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

These UserAttribute* models duplicate the existing ResourceAttributeCreate/Update/Read schema almost 1:1. To avoid drift and keep the generated helper methods/Nullable wrappers consistent across the SDK, consider making these types aliases/wrappers around the existing ResourceAttribute* models (or regenerating from the OpenAPI spec) instead of maintaining a separate parallel struct set.

Suggested change
import (
"encoding/json"
"time"
)
// UserAttributeRead is a user schema attribute as returned by the V2 API.
type UserAttributeRead struct {
Type AttributeType `json:"type"`
Description *string `json:"description,omitempty"`
Key string `json:"key"`
Id string `json:"id"`
ResourceId string `json:"resource_id"`
ResourceKey string `json:"resource_key"`
OrganizationId string `json:"organization_id"`
ProjectId string `json:"project_id"`
EnvironmentId string `json:"environment_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
BuiltIn bool `json:"built_in"`
}
func NewUserAttributeReadWithDefaults() *UserAttributeRead {
return &UserAttributeRead{}
}
func (o *UserAttributeRead) GetKey() string {
if o == nil {
return ""
}
return o.Key
}
func (o *UserAttributeRead) GetId() string {
if o == nil {
return ""
}
return o.Id
}
func (o *UserAttributeRead) GetType() AttributeType {
if o == nil {
return ""
}
return o.Type
}
func (o *UserAttributeRead) GetBuiltIn() bool {
if o == nil {
return false
}
return o.BuiltIn
}
func (o *UserAttributeRead) GetDescription() string {
if o == nil || IsNil(o.Description) {
return ""
}
return *o.Description
}
func (o UserAttributeRead) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"type": o.Type, "key": o.Key, "id": o.Id,
"resource_id": o.ResourceId, "resource_key": o.ResourceKey,
"organization_id": o.OrganizationId, "project_id": o.ProjectId,
"environment_id": o.EnvironmentId, "created_at": o.CreatedAt,
"updated_at": o.UpdatedAt, "built_in": o.BuiltIn,
}
if !IsNil(o.Description) {
m["description"] = o.Description
}
return json.Marshal(m)
}
// UserAttributeRead is a user schema attribute as returned by the V2 API.
// It is an alias of the canonical ResourceAttributeRead model to avoid
// duplication and drift in field definitions and helper methods.
type UserAttributeRead = ResourceAttributeRead
func NewUserAttributeReadWithDefaults() *UserAttributeRead {
return (*UserAttributeRead)(NewResourceAttributeReadWithDefaults())
}

Copilot uses AI. Check for mistakes.

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.

Custom MarshalJSON without matching UnmarshalJSON — potential data loss on round-trip

UserAttributeRead defines a custom MarshalJSON but relies on the default struct-tag-based UnmarshalJSON. While this works for basic deserialization from the API, it creates an asymmetry: the custom MarshalJSON serializes Description conditionally (only when non-nil), but if someone marshals and then unmarshals a UserAttributeRead with a nil Description, the behavior is correct only by coincidence of omitempty tag alignment.

More concretely, ResourceAttributeRead (the analogous type) does not define a custom MarshalJSON at all — it uses the generated code pattern with toSerialize map. The new UserAttributeRead introduces a divergent serialization style.

Suggestion: Either remove the custom MarshalJSON and rely on struct tags (since the json tags already handle the serialization correctly with omitempty), or document why a custom implementation is needed. The struct tags as defined are sufficient for correct JSON output.

Loading
Loading