sdk

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2025 License: Apache-2.0 Imports: 22 Imported by: 6

Documentation

Overview

pkg/sdk/auth.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildBexprFilter

func BuildBexprFilter(labels LabelMap) string

BuildBexprFilter builds a bexpr AND filter from the provided labels. Strings are quoted, booleans and numbers are emitted verbatim. When labels is empty an empty string is returned.

func ConvertLabelsToProto

func ConvertLabelsToProto(labels LabelMap) map[string]*statev1.LabelValue

ConvertLabelsToProto converts a LabelMap to the proto representation used by RPC requests.

func LoginWithDeviceCode deprecated

func LoginWithDeviceCode(
	ctx context.Context,
	issuer string,
	clientID string,
) (*LoginSuccessMetadata, *Credentials, error)

LoginWithDeviceCode initiates the OIDC Device Authorization Flow (RFC 8628). It guides the user to authorize the CLI in a browser, polls for tokens, and returns the credentials.

Deprecated: Use LoginInteractive instead, which automatically discovers the correct issuer and client ID from the Grid API.

This function works with both Grid deployment modes:

The function performs OIDC discovery from the issuer to find device authorization endpoints automatically.

Types

type AddDependencyInput

type AddDependencyInput struct {
	From          StateReference
	FromOutput    string
	To            StateReference
	ToInputName   string
	MockValueJSON string
}

AddDependencyInput describes the parameters used to create a dependency edge.

type AddDependencyResult

type AddDependencyResult struct {
	Edge          DependencyEdge
	AlreadyExists bool
}

AddDependencyResult returns the created or existing dependency edge and metadata.

type AssignGroupRoleInput

type AssignGroupRoleInput struct {
	GroupName string
	RoleName  string
}

AssignGroupRoleInput describes the parameters for AssignGroupRole.

type AssignGroupRoleResult

type AssignGroupRoleResult struct {
	Success    bool
	AssignedAt time.Time
}

AssignGroupRoleResult is the result of AssignGroupRole.

type AuthConfig

type AuthConfig struct {
	Mode               string  `json:"mode"`                 // "external-idp" or "internal-idp"
	Issuer             string  `json:"issuer"`               // OIDC issuer URL
	ClientID           *string `json:"client_id,omitempty"`  // Public client ID for device flow (nil if not supported)
	Audience           *string `json:"audience,omitempty"`   // Expected aud claim in access tokens
	SupportsDeviceFlow bool    `json:"supports_device_flow"` // Whether interactive device flow is supported
}

AuthConfig represents Grid's authentication configuration. This is returned by the /auth/config endpoint and tells SDK clients where to authenticate and what client ID to use.

func DiscoverAuthConfig

func DiscoverAuthConfig(ctx context.Context, serverURL string) (*AuthConfig, error)

DiscoverAuthConfig fetches authentication configuration from Grid API. This enables mode-agnostic authentication by discovering whether Grid is using an external IdP (Mode 1) or internal IdP (Mode 2).

type BackendConfig

type BackendConfig struct {
	Address       string
	LockAddress   string
	UnlockAddress string
}

BackendConfig represents Terraform HTTP backend endpoints for a state.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides a high-level interface to the Grid state management API. It wraps the generated Connect RPC client with ergonomic methods.

func NewClient

func NewClient(baseURL string, optFns ...ClientOption) *Client

NewClient creates a new Grid SDK client that communicates with the API server at baseURL. An http.Client is created automatically when one is not supplied.

func (*Client) AddDependency

func (c *Client) AddDependency(ctx context.Context, input AddDependencyInput) (*AddDependencyResult, error)

AddDependency creates a new dependency edge from a producer state's output to a consumer state's input. The state references may be specified by logic ID or GUID. If ToInputName is empty, it will be auto-generated by the server.

func (*Client) AssignGroupRole

func (c *Client) AssignGroupRole(ctx context.Context, input AssignGroupRoleInput) (*AssignGroupRoleResult, error)

AssignGroupRole assigns a group to a role.

func (*Client) CreateState

func (c *Client) CreateState(ctx context.Context, input CreateStateInput) (*State, error)

CreateState creates a new Terraform state. When GUID is empty, a random UUID is generated.

func (*Client) ExportRoles

func (c *Client) ExportRoles(ctx context.Context, input ExportRolesInput) (*ExportRolesResult, error)

ExportRoles exports roles to a JSON string.

func (*Client) GetDependencyGraph

func (c *Client) GetDependencyGraph(ctx context.Context, ref StateReference) (*DependencyGraph, error)

GetDependencyGraph retrieves the dependency graph for a consumer state reference.

func (*Client) GetEffectivePermissions

func (c *Client) GetEffectivePermissions(ctx context.Context, input GetEffectivePermissionsInput) (*GetEffectivePermissionsResult, error)

GetEffectivePermissions retrieves the effective permissions for a principal. The principal can be identified by prefixing the ID ("user:alice", "sa:deployer") or by explicitly setting PrincipalType. Valid types: "user", "service_account".

func (*Client) GetLabelPolicy

func (c *Client) GetLabelPolicy(ctx context.Context) (*LabelPolicy, error)

GetLabelPolicy retrieves the current label validation policy.

func (*Client) GetOutputSchema

func (c *Client) GetOutputSchema(ctx context.Context, ref StateReference, outputKey string) (string, error)

GetOutputSchema retrieves the JSON Schema for a specific state output. Returns empty string if no schema has been set.

func (*Client) GetState

func (c *Client) GetState(ctx context.Context, ref StateReference) (*State, error)

GetState retrieves state metadata and backend configuration using either GUID or logic ID.

func (*Client) GetStateInfo

func (c *Client) GetStateInfo(ctx context.Context, ref StateReference) (*StateInfo, error)

GetStateInfo retrieves comprehensive state information including dependencies, dependents, and outputs. This consolidates information that would otherwise require multiple RPC calls.

func (*Client) GetStateLock

func (c *Client) GetStateLock(ctx context.Context, guid string) (StateLock, error)

GetStateLock inspects the current lock status and metadata for a state by its GUID.

func (*Client) GetStateStatus

func (c *Client) GetStateStatus(ctx context.Context, ref StateReference) (*StateStatus, error)

GetStateStatus computes the dependency status for the supplied state reference.

func (*Client) GetTopologicalOrder

func (c *Client) GetTopologicalOrder(ctx context.Context, input TopologyInput) ([]TopologyLayer, error)

GetTopologicalOrder returns a layered ordering of states rooted at the provided reference.

func (*Client) ImportRoles

func (c *Client) ImportRoles(ctx context.Context, input ImportRolesInput) (*ImportRolesResult, error)

ImportRoles imports roles from a JSON string.

func (*Client) ListAllEdges

func (c *Client) ListAllEdges(ctx context.Context) ([]DependencyEdge, error)

ListAllEdges returns all dependency edges in the system, ordered by ID. Used by dashboards and monitoring tools to visualize complete topology.

func (*Client) ListDependencies

func (c *Client) ListDependencies(ctx context.Context, ref StateReference) ([]DependencyEdge, error)

ListDependencies returns all incoming dependency edges for a consumer state reference.

func (*Client) ListDependents

func (c *Client) ListDependents(ctx context.Context, ref StateReference) ([]DependencyEdge, error)

ListDependents returns all outgoing dependency edges for a producer state reference.

func (*Client) ListGroupRoles

func (c *Client) ListGroupRoles(ctx context.Context, input ListGroupRolesInput) (*ListGroupRolesResult, error)

func (*Client) ListStateOutputs

func (c *Client) ListStateOutputs(ctx context.Context, ref StateReference) ([]OutputKey, error)

ListStateOutputs returns the output keys from a state's Terraform JSON. Output values are not returned for security/size reasons - only keys and sensitive flags.

func (*Client) ListStates

func (c *Client) ListStates(ctx context.Context) ([]StateSummary, error)

ListStates returns summary information for all states managed by the server.

func (*Client) ListStatesWithOptions

func (c *Client) ListStatesWithOptions(ctx context.Context, opts ListStatesOptions) ([]StateSummary, error)

ListStatesWithOptions returns summaries with optional filter/label projection controls.

func (*Client) RemoveDependency

func (c *Client) RemoveDependency(ctx context.Context, edgeID int64) error

RemoveDependency deletes an existing dependency edge by its edge ID.

func (*Client) RemoveGroupRole

func (c *Client) RemoveGroupRole(ctx context.Context, input RemoveGroupRoleInput) (*RemoveGroupRoleResult, error)

RemoveGroupRole removes a group from a role.

func (*Client) SearchByOutput

func (c *Client) SearchByOutput(ctx context.Context, outputKey string) ([]DependencyEdge, error)

SearchByOutput finds every dependency edge that consumes a specific producer output key.

func (*Client) SetLabelPolicy

func (c *Client) SetLabelPolicy(ctx context.Context, policyJSON []byte) (*LabelPolicy, error)

SetLabelPolicy replaces the label policy using the provided JSON definition.

func (*Client) SetOutputSchema

func (c *Client) SetOutputSchema(ctx context.Context, ref StateReference, outputKey string, schemaJSON string) error

SetOutputSchema sets or updates the JSON Schema for a specific state output. This allows declaring expected output types before the output exists in state.

func (*Client) UnlockState

func (c *Client) UnlockState(ctx context.Context, guid, lockID string) (StateLock, error)

UnlockState releases a lock on a state identified by GUID. The lockID must match the ID of the current lock, or the operation will fail.

func (*Client) UpdateStateLabels

func (c *Client) UpdateStateLabels(ctx context.Context, input UpdateStateLabelsInput) (*UpdateStateLabelsResult, error)

UpdateStateLabels mutates labels on an existing state and returns the updated set.

type ClientOption

type ClientOption func(*ClientOptions)

ClientOption mutates ClientOptions.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient overrides the HTTP client used for RPC calls.

type ClientOptions

type ClientOptions struct {
	HTTPClient *http.Client
}

ClientOptions configures SDK client construction.

type CreateConstraint

type CreateConstraint struct {
	AllowedValues []string
	Required      bool
}

CreateConstraint defines a constraint for a label key.

type CreateConstraints

type CreateConstraints struct {
	Constraints map[string]CreateConstraint
}

CreateConstraints defines the constraints for creating a state.

type CreateStateInput

type CreateStateInput struct {
	GUID    string
	LogicID string
	Labels  LabelMap
}

CreateStateInput describes the payload required to create a Terraform state.

type CredentialStore

type CredentialStore interface {
	// SaveCredentials persists the given credentials.
	// Implementations SHOULD ensure credentials are stored securely (e.g., file permissions 0600).
	SaveCredentials(credentials *Credentials) error

	// LoadCredentials retrieves previously saved credentials.
	// Returns an error if credentials don't exist or cannot be loaded.
	LoadCredentials() (*Credentials, error)

	// DeleteCredentials removes stored credentials.
	// Should be idempotent (no error if credentials don't exist).
	DeleteCredentials() error
}

CredentialStore abstracts credential persistence. Implementations MUST be provided by SDK consumers (e.g., gridctl, web apps). This interface enables the SDK to remain agnostic to storage mechanisms while allowing consumers to implement platform-specific persistence (filesystem, browser localStorage, secure enclaves, etc.).

type Credentials

type Credentials struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type"`
	ExpiresAt    time.Time `json:"expires_at"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	PrincipalID  string    `json:"principal_id,omitempty"` // Casbin principal ID (e.g., "sa:{clientID}" or "user:{subject}")
}

Credentials represents the authentication credentials.

func LoginWithServiceAccount

func LoginWithServiceAccount(
	ctx context.Context,
	issuer string,
	clientID string,
	clientSecret string,
) (*Credentials, error)

LoginWithServiceAccount authenticates using the OAuth2 client credentials flow. This is used for service accounts (machine-to-machine authentication).

This function works with both Grid deployment modes:

  • Mode 1 (External IdP): Service account is created in external IdP (e.g., Keycloak client)
  • Mode 2 (Internal IdP): Service account is created in Grid via CreateServiceAccount RPC

The function performs OIDC discovery to find the token endpoint, then exchanges client credentials for an access token.

func RefreshToken

func RefreshToken(
	ctx context.Context,
	issuer string,
	clientID string,
	refreshToken string,
) (*Credentials, error)

RefreshToken attempts to refresh an expired access token using a refresh token. Returns the new credentials on success.

func (*Credentials) IsExpired

func (c *Credentials) IsExpired() bool

type DependencyEdge

type DependencyEdge struct {
	ID             int64
	From           StateReference
	FromOutput     string
	To             StateReference
	ToInputName    string
	Status         string
	InDigest       string
	OutDigest      string
	MockValueJSON  string
	LastProducedAt *time.Time
	LastConsumedAt *time.Time
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

DependencyEdge represents a dependency relationship between producer and consumer states.

type DependencyGraph

type DependencyGraph struct {
	Consumer  StateReference
	Producers []ProducerState
	Edges     []DependencyEdge
}

DependencyGraph captures the full dependency topology for a consumer state.

type EffectivePermissions

type EffectivePermissions struct {
	Roles                      []string
	Actions                    []string
	LabelScopeExprs            []string
	EffectiveCreateConstraints *CreateConstraints
	EffectiveImmutableKeys     []string
}

EffectivePermissions describes the effective permissions for a principal.

type EnvCreds

type EnvCreds struct {
	ClientID     string
	ClientSecret string
}

func CheckEnvCreds

func CheckEnvCreds() (bool, EnvCreds)

type ExportRolesInput

type ExportRolesInput struct {
	RoleNames []string
}

ExportRolesInput describes the parameters for ExportRoles.

type ExportRolesResult

type ExportRolesResult struct {
	RolesJSON string
}

ExportRolesResult is the result of ExportRoles.

type GetEffectivePermissionsInput

type GetEffectivePermissionsInput struct {
	PrincipalType string
	PrincipalID   string
}

GetEffectivePermissionsInput describes the parameters for GetEffectivePermissions.

type GetEffectivePermissionsResult

type GetEffectivePermissionsResult struct {
	Permissions *EffectivePermissions
}

GetEffectivePermissionsResult is the result of GetEffectivePermissions.

type GroupRoleAssignmentInfo

type GroupRoleAssignmentInfo struct {
	GroupName        string
	RoleName         string
	AssignedAt       time.Time
	AssignedByUserID string
}

GroupRoleAssignmentInfo describes a group-to-role assignment.

type ImportRolesInput

type ImportRolesInput struct {
	RolesJSON string
	Force     bool
}

ImportRolesInput describes the parameters for ImportRoles.

type ImportRolesResult

type ImportRolesResult struct {
	ImportedCount int
	SkippedCount  int
	Errors        []string
}

ImportRolesResult is the result of ImportRoles.

type IncomingEdge

type IncomingEdge struct {
	ID             int64
	From           StateReference
	FromOutput     string
	Status         string
	InDigest       string
	OutDigest      string
	LastProducedAt *time.Time
	LastConsumedAt *time.Time
}

IncomingEdge conveys details about an incoming producer edge when computing status.

type Label

type Label struct {
	Key   string
	Value any
}

Label represents a single key/value label pair after sorting.

func SortLabels

func SortLabels(labels LabelMap) []Label

SortLabels returns a slice of Label sorted lexicographically by key. Nil input results in an empty slice.

type LabelMap

type LabelMap map[string]any

LabelMap stores typed label values exposed by the SDK.

func ConvertProtoLabels

func ConvertProtoLabels(pb map[string]*statev1.LabelValue) LabelMap

ConvertProtoLabels converts a proto label map into a LabelMap with native Go types.

type LabelPolicy

type LabelPolicy struct {
	Version    int32
	PolicyJSON string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

LabelPolicy describes the label validation policy configured on the server.

type LabelValidator

type LabelValidator struct {
	// contains filtered or unexported fields
}

LabelValidator validates labels against optional policy constraints.

func NewLabelValidator

func NewLabelValidator(policy *PolicyDefinition) *LabelValidator

NewLabelValidator constructs a validator (nil policy enables basic validation only).

func (*LabelValidator) Validate

func (v *LabelValidator) Validate(labels LabelMap) error

Validate checks labels against policy constraints.

type ListGroupRolesInput

type ListGroupRolesInput struct {
	GroupName string
}

ListGroupRolesInput describes the parameters for ListGroupRoles.

type ListGroupRolesResult

type ListGroupRolesResult struct {
	Assignments []GroupRoleAssignmentInfo
}

ListGroupRolesResult is the result of ListGroupRoles.

type ListStatesOptions

type ListStatesOptions struct {
	Filter        string
	IncludeLabels *bool
	IncludeStatus *bool // Whether to compute status for each state (default: true, expensive N+1 operation)
}

ListStatesOptions configures optional parameters for ListStatesWithOptions.

type LockInfo

type LockInfo struct {
	ID        string
	Operation string
	Info      string
	Who       string
	Version   string
	Created   *time.Time
	Path      string
}

LockInfo contains details about a Terraform state lock.

type LoginSuccessMetadata

type LoginSuccessMetadata struct {
	// User is the 'sub' claim from the ID token.
	User string
	// Email is the 'email' claim, if present.
	Email string
	// ExpiresAt is when the access token expires.
	ExpiresAt time.Time
}

LoginSuccessMetadata contains information about the successful login, useful for displaying a confirmation message to the user.

func LoginInteractive

func LoginInteractive(ctx context.Context, serverURL string, store CredentialStore) (*LoginSuccessMetadata, error)

LoginInteractive performs device flow authentication using discovered config. This is the SDK's main authentication entrypoint for interactive users.

Flow: 1. Discovers auth configuration from Grid API (/auth/config) 2. Checks if interactive device flow is supported 3. Initiates OIDC device authorization flow against the discovered issuer 4. Optionally saves credentials using the provided store

The store parameter is optional - pass nil to skip credential persistence.

Returns an error if the Grid deployment does not support interactive authentication (e.g., Mode 2 Internal IdP only supports service accounts).

type OutputKey

type OutputKey struct {
	Key              string
	Sensitive        bool
	SchemaJSON       *string    // Optional JSON Schema definition for this output
	SchemaSource     *string    // Schema source: "manual" or "inferred"
	ValidationStatus *string    // Validation status: "valid", "invalid", or "error"
	ValidationError  *string    // Validation error message (if validation failed)
	ValidatedAt      *time.Time // Last validation timestamp
}

OutputKey represents a Terraform output name and metadata.

type PolicyDefinition

type PolicyDefinition struct {
	AllowedKeys      map[string]struct{} `json:"allowed_keys,omitempty"`
	AllowedValues    map[string][]string `json:"allowed_values,omitempty"`
	ReservedPrefixes []string            `json:"reserved_prefixes,omitempty"`
	MaxKeys          int                 `json:"max_keys"`
	MaxValueLen      int                 `json:"max_value_len"`
}

PolicyDefinition mirrors the server-side structure for label validation rules.

func ParsePolicyDefinition

func ParsePolicyDefinition(policyJSON string) (*PolicyDefinition, error)

ParsePolicyDefinition decodes JSON policy into a PolicyDefinition.

type ProducerState

type ProducerState struct {
	State         StateReference
	BackendConfig BackendConfig
}

ProducerState describes a unique producer within a dependency graph.

type RemoveGroupRoleInput

type RemoveGroupRoleInput struct {
	GroupName string
	RoleName  string
}

RemoveGroupRoleInput describes the parameters for RemoveGroupRole.

type RemoveGroupRoleResult

type RemoveGroupRoleResult struct {
	Success bool
}

RemoveGroupRoleResult is the result of RemoveGroupRole.

type State

type State struct {
	GUID          string
	LogicID       string
	BackendConfig BackendConfig
}

State describes a Terraform state along with its backend configuration.

type StateInfo

type StateInfo struct {
	State         StateReference
	BackendConfig BackendConfig
	Dependencies  []DependencyEdge
	Dependents    []DependencyEdge
	Outputs       []OutputKey
	SizeBytes     int64
	CreatedAt     time.Time
	UpdatedAt     time.Time
	Labels        LabelMap
}

StateInfo provides comprehensive information about a state including dependencies, dependents, and outputs.

type StateLock

type StateLock struct {
	Locked bool
	Info   *LockInfo
}

StateLock reports whether a state is locked along with lock metadata when present.

type StateReference

type StateReference struct {
	GUID    string
	LogicID string
}

StateReference identifies a state by logic ID or GUID.

type StateStatus

type StateStatus struct {
	State    StateReference
	Status   string
	Incoming []IncomingEdge
	Summary  StatusSummary
}

StateStatus captures runtime dependency status information for a state.

type StateSummary

type StateSummary struct {
	GUID               string
	LogicID            string
	Locked             bool
	SizeBytes          int64
	CreatedAt          time.Time
	UpdatedAt          time.Time
	ComputedStatus     string
	DependencyLogicIDs []string
	Labels             LabelMap

	// Count fields populated from backend (efficient for list rendering)
	DependenciesCount int32
	DependentsCount   int32
	OutputsCount      int32
}

StateSummary conveys lightweight information about a state returned by ListStates. Optimized with count fields to eliminate N+1 queries for list rendering.

type StatusSummary

type StatusSummary struct {
	IncomingClean   int
	IncomingDirty   int
	IncomingPending int
	IncomingUnknown int
}

StatusSummary aggregates incoming edge statuses for a state.

type TopologyDirection

type TopologyDirection string

TopologyDirection indicates the traversal direction for topological ordering.

const (
	// Downstream traverses from producer to dependents (default).
	Downstream TopologyDirection = "downstream"
	// Upstream traverses from consumer to producers.
	Upstream TopologyDirection = "upstream"
)

type TopologyInput

type TopologyInput struct {
	Root      StateReference
	Direction TopologyDirection
}

TopologyInput configures a topological ordering request.

type TopologyLayer

type TopologyLayer struct {
	Level  int
	States []StateReference
}

TopologyLayer represents a level within a topological ordering of states.

type UpdateStateLabelsInput

type UpdateStateLabelsInput struct {
	StateID  string
	Adds     LabelMap
	Removals []string
}

UpdateStateLabelsInput describes label mutations for UpdateStateLabels.

type UpdateStateLabelsResult

type UpdateStateLabelsResult struct {
	StateID       string
	Labels        LabelMap
	PolicyVersion int32
	UpdatedAt     time.Time
}

UpdateStateLabelsResult reports the outcome of a label mutation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL