helpers

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package helpers provides business logic and AWS SDK interactions for various AWS services

Index

Constants

View Source
const (
	IAMRoleTypeSSOManaged  = "SSO Managed Role"
	IAMRoleTypeServiceRole = "Service Role"
	IAMRoleTypeUserDefined = "User defined Role"
)

IAM Role type

View Source
const (
	IAMPolicyTypeAttached   = "Attached Policy"
	IAMPolicyTypeInline     = "Inline Policy"
	IAMPolicyTypeAssumeRole = "Assume Role Policy"
)

IAM Policy Type

View Source
const (
	IAMPrincipalTypeService = "Service"
	IAMPrincipalTypeAWS     = "AWS"
)

IAM Principal Type

View Source
const (
	IAMObjectTypeGroup = "Group"
	IAMObjectTypeUser  = "User"
)

IAM Object Type

View Source
const (
	AccountIDPlaceholder    = "{account_id}"
	AccountNamePlaceholder  = "{account_name}"
	AccountAliasPlaceholder = "{account_alias}"
	RoleNamePlaceholder     = "{role_name}"
	RegionPlaceholder       = "{region}"
)

Supported placeholder variables

Variables

This section is empty.

Functions

func FlattenStringMaps

func FlattenStringMaps(stringmaps []map[string]string) map[string]string

FlattenStringMaps combines multiple stringmaps into a single one. Later values will override earlier if duplicates are present

func FormatRouteTableInfo

func FormatRouteTableInfo(routeTable *types.RouteTable) (string, []string)

FormatRouteTableInfo formats route table information similar to vpc routes command

func GetAccountAlias

func GetAccountAlias(svc *iam.Client, stsSvc *sts.Client) map[string]string

GetAccountAlias returns the account alias in a map of [accountid]accountalias If no alias is present, it will return the account ID instead

func GetAccountID

func GetAccountID(svc *sts.Client) string

GetAccountID returns the ID of the account the command is run from

func GetAccountSummary

func GetAccountSummary(svc *iam.Client) (map[string]int32, error)

GetAccountSummary retrieves the account summary map which contains high level information about the root account

func GetAllBuckets

func GetAllBuckets(svc *s3.Client) ([]types.Bucket, string)

GetAllBuckets returns an overview of all buckets GetAllBuckets retrieves all S3 buckets and returns them along with the owner name

func GetAllEC2ResourceNames

func GetAllEC2ResourceNames(svc *ec2.Client) map[string]string

GetAllEC2ResourceNames retrieves the names of EC2 related objects

func GetAllEc2Instances

func GetAllEc2Instances(svc *ec2.Client) []types.Reservation

GetAllEc2Instances retrieves all EC2 instances

func GetAllRdsResourceNames

func GetAllRdsResourceNames(svc *rds.Client) map[string]string

GetAllRdsResourceNames gets a list of all names for RDS objects TODO: clusters, subnet groups, parameter groups, option groups

func GetAllSecurityGroups

func GetAllSecurityGroups(svc *ec2.Client) []types.SecurityGroup

GetAllSecurityGroups returns a list of all securitygroups in the region

func GetAllUnservicedAppMeshNodes

func GetAllUnservicedAppMeshNodes(meshname *string, svc *appmesh.Client) []string

GetAllUnservicedAppMeshNodes returns a slice of nodes that don't serve as the backend for any service

func GetAttachedPoliciesMapForGroup

func GetAttachedPoliciesMapForGroup(groupname *string, svc *iam.Client) map[string]string

GetAttachedPoliciesMapForGroup retrieves a map of attached policies for the provided IAM groupname where the key is the name of the policy and the value is the actual json policy document

func GetAttachedPoliciesMapForGroups

func GetAttachedPoliciesMapForGroups(groups []string, svc *iam.Client) map[string]string

GetAttachedPoliciesMapForGroups retrieves a map of attached policies for the slice of IAM groupnames where the key is the name of the policy and the value is the actual json policy document

func GetAttachedPoliciesMapForUser

func GetAttachedPoliciesMapForUser(username *string, svc *iam.Client) map[string]string

GetAttachedPoliciesMapForUser retrieves a map of attached policies for the provided IAM username where the key is the name of the policy and the value is the actual json policy document

func GetEc2BySecurityGroup

func GetEc2BySecurityGroup(securitygroupID *string, svc *ec2.Client) []types.Reservation

GetEc2BySecurityGroup retrieves all instances attached to a securitygroup

func GetEc2Name

func GetEc2Name(ec2name string, svc *ec2.Client) string

GetEc2Name returns the name of the provided EC2 Resource

func GetGroupNameSliceForUser

func GetGroupNameSliceForUser(username *string, svc *iam.Client) []string

GetGroupNameSliceForUser retrieves a slice of all the groups the provided IAM username belongs to

func GetGroupPoliciesMapForGroup

func GetGroupPoliciesMapForGroup(groupname *string, svc *iam.Client) map[string]string

GetGroupPoliciesMapForGroup retrieves a map of policies for the provided IAM groupname where the key is the name of the policy and the value is the actual json policy document

func GetGroupPoliciesMapForGroups

func GetGroupPoliciesMapForGroups(groups []string, svc *iam.Client) map[string]string

GetGroupPoliciesMapForGroups retrieves all of the policies for the provided slice of groups, where the key is the name of the policy and the value is the json policy document

func GetNatGatewayFromNetworkInterface

func GetNatGatewayFromNetworkInterface(netinterface types.NetworkInterface, svc *ec2.Client) *types.NatGateway

GetNatGatewayFromNetworkInterface returns the NAT gateway associated with a network interface

func GetNestedCloudFormationResources

func GetNestedCloudFormationResources(stackname *string, svc *cloudformation.Client) []types.StackResource

GetNestedCloudFormationResources retrieves a slice of the Stack Resources that are in the provided stack or in one of its children

func GetNetworkInterfaces

func GetNetworkInterfaces(svc *ec2.Client) []types.NetworkInterface

GetNetworkInterfaces retrieves all network interfaces in the region

func GetPoliciesMap

func GetPoliciesMap(svc *iam.Client) map[string]types.Policy

GetPoliciesMap retrieves a map of policies with the policy name as the key and the actual policy object as the value

func GetRDSName

func GetRDSName(rdsname *string, svc *rds.Client) string

GetRDSName returns the name of the provided RDS Resource

func GetResourceDisplayNameWithGlobalLookup

func GetResourceDisplayNameWithGlobalLookup(resourceID string, tags []types.Tag, globalLookupFunc func(string) string) string

GetResourceDisplayNameWithGlobalLookup provides comprehensive tiered name lookup for AWS resources 1. First tries global naming lookup using the provided lookup function 2. Then checks Name tag on the resource 3. Finally falls back to the resource ID Returns either "Name (ID)" or just "ID" if no name found

func GetResourcesByStackName

func GetResourcesByStackName(stackname *string, svc *cloudformation.Client) []types.StackResource

GetResourcesByStackName returns a slice of the Stack Resources in the provided stack

func GetRouteTablesForTransitGateway

func GetRouteTablesForTransitGateway(tgwID string, svc *ec2.Client) map[string]TransitGatewayRouteTable

GetRouteTablesForTransitGateway returns all route tables attached to a Transit Gateway

func GetStringMapFromJSONFile

func GetStringMapFromJSONFile(filename string) map[string]string

GetStringMapFromJSONFile parses a JSON file and returns it as a string map

func GetSubnetRouteTable

func GetSubnetRouteTable(subnetID string, routeTables []types.RouteTable) *types.RouteTable

GetSubnetRouteTable finds the route table associated with a specific subnet

func GetSupportedPlaceholders

func GetSupportedPlaceholders() []string

GetSupportedPlaceholders returns all supported placeholder variables

func GetTransitGatewayFromNetworkInterface

func GetTransitGatewayFromNetworkInterface(netinterface types.NetworkInterface, svc *ec2.Client) string

GetTransitGatewayFromNetworkInterface returns the Transit Gateway attachment ID for a network interface

func GetUserPoliciesMapForUser

func GetUserPoliciesMapForUser(username *string, svc *iam.Client) map[string]string

GetUserPoliciesMapForUser retrieves a map of policies for the provided IAM username where the key is the name of the policy and the value is the actual json policy document

func GetVPCEndpointFromNetworkInterface

func GetVPCEndpointFromNetworkInterface(netinterface types.NetworkInterface, svc *ec2.Client) *types.VpcEndpoint

GetVPCEndpointFromNetworkInterface returns the VPC endpoint associated with a network interface

func IsLatestInstanceFamily

func IsLatestInstanceFamily(instanceFamily string) bool

IsLatestInstanceFamily checks if an instance is part of the la test family is running in the latest instance family. TODO: Automate this to work properly

func IsValidCIDR

func IsValidCIDR(cidr string) bool

IsValidCIDR validates if the provided string is a valid CIDR block

func IsValidIPAddress

func IsValidIPAddress(ip string) bool

IsValidIPAddress validates if the provided string is a valid IP address

func SanitizeProfileName

func SanitizeProfileName(name string) string

SanitizeProfileName sanitizes a profile name by removing invalid characters

func TypeByResourceID

func TypeByResourceID(resourceID string) string

TypeByResourceID identifies the type of resource based on its unique ID

func ValidatePatternExamples

func ValidatePatternExamples() map[string]error

ValidatePatternExamples validates common naming pattern examples

Types

type AWSConfigFile

type AWSConfigFile struct {
	FilePath string
	Profiles map[string]Profile
	Sessions map[string]SSOSession // SSO session configurations
}

AWSConfigFile represents an AWS config file with its profiles

func LoadAWSConfigFile

func LoadAWSConfigFile(filePath string) (*AWSConfigFile, error)

LoadAWSConfigFile loads and parses an AWS configuration file with comprehensive error recovery and validation capabilities. This function handles both existing and non-existent configuration files gracefully.

File Path Resolution: 1. Uses provided filePath if not empty 2. Checks AWS_CONFIG_FILE environment variable 3. Falls back to default ~/.aws/config location

Parsing Features: - Supports both profile and SSO session sections - Handles legacy and modern SSO profile formats - Recovers from malformed sections when possible - Validates file permissions and security - Provides detailed error context for troubleshooting

Parameters:

  • filePath: Path to AWS config file (empty for auto-detection)

Returns:

  • *AWSConfigFile: Parsed configuration with profiles and SSO sessions
  • error: Critical parsing error or file system error

Error Recovery Strategy: - Missing file: Returns empty configuration (not an error) - Malformed sections: Skips invalid sections, continues parsing - Permission issues: Returns detailed error with context - Partial parsing: Returns warning with successfully parsed content

Security Validations: - Checks file permissions (should be 600 or similar) - Validates file ownership (should be current user) - Ensures file is readable and not corrupted

Supported Formats: - Legacy SSO profiles with direct sso_* properties - Modern SSO profiles with sso_session references - Mixed environments with both formats - Standard AWS CLI configuration sections

Example usage:

configFile, err := LoadAWSConfigFile("")
if err != nil {
    return fmt.Errorf("failed to load config: %w", err)
}

profile, exists := configFile.GetProfile("my-profile")
if !exists {
    return fmt.Errorf("profile not found")
}

func (*AWSConfigFile) AddProfile

func (cf *AWSConfigFile) AddProfile(name string, profile Profile) error

AddProfile adds a new profile to the config file

func (*AWSConfigFile) AppendProfiles

func (cf *AWSConfigFile) AppendProfiles(profiles []GeneratedProfile) error

AppendProfiles appends multiple profiles to the config file

func (*AWSConfigFile) AppendToFile

func (cf *AWSConfigFile) AppendToFile(profiles []GeneratedProfile) error

AppendToFile appends new profiles to the end of the config file with file locking

func (*AWSConfigFile) AtomicRemoveProfile

func (cf *AWSConfigFile) AtomicRemoveProfile(profileName string) error

AtomicRemoveProfile atomically removes a profile with backup and rollback

func (*AWSConfigFile) AtomicReplaceProfile

func (cf *AWSConfigFile) AtomicReplaceProfile(oldName, newName string, newProfile Profile) error

AtomicReplaceProfile atomically replaces a profile with backup and rollback

func (*AWSConfigFile) AtomicWriteToFile

func (cf *AWSConfigFile) AtomicWriteToFile() error

AtomicWriteToFile writes the config file atomically with file locking

func (*AWSConfigFile) BeginTransaction

func (cf *AWSConfigFile) BeginTransaction() (*Transaction, error)

BeginTransaction starts a new transaction for atomic operations

func (*AWSConfigFile) BuildProfileLookupIndex

func (cf *AWSConfigFile) BuildProfileLookupIndex() (*ProfileLookupIndex, error)

BuildProfileLookupIndex creates efficient lookup indices for profile searching

func (*AWSConfigFile) CreateBackup

func (cf *AWSConfigFile) CreateBackup() (string, error)

CreateBackup creates a timestamped backup of the config file before modifications

func (*AWSConfigFile) DetectProfileConflicts

func (cf *AWSConfigFile) DetectProfileConflicts(newProfiles []GeneratedProfile) []string

DetectProfileConflicts detects conflicts between existing profiles and new profiles

func (*AWSConfigFile) ExecuteAtomicProfileOperations

func (cf *AWSConfigFile) ExecuteAtomicProfileOperations(operations []func(*Transaction) error) error

ExecuteAtomicProfileOperations executes multiple profile operations atomically

func (*AWSConfigFile) FindDuplicateProfiles

func (cf *AWSConfigFile) FindDuplicateProfiles() (map[string][]Profile, error)

FindDuplicateProfiles finds profiles that have the same SSO configuration

func (*AWSConfigFile) FindProfilesByName

func (cf *AWSConfigFile) FindProfilesByName(profileNames []string) map[string]Profile

FindProfilesByName finds profiles by their names using efficient lookup

func (*AWSConfigFile) FindProfilesForRole

func (cf *AWSConfigFile) FindProfilesForRole(accountID, roleName, startURL string) ([]Profile, error)

FindProfilesForRole finds existing profiles for specific roles

func (*AWSConfigFile) FindProfilesWithSSOConfig

func (cf *AWSConfigFile) FindProfilesWithSSOConfig(startURL, region, accountID, roleName string) ([]Profile, error)

FindProfilesWithSSOConfig finds all profiles that match a specific SSO configuration

func (*AWSConfigFile) GenerateProfileText

func (cf *AWSConfigFile) GenerateProfileText(profiles []GeneratedProfile) string

GenerateProfileText generates formatted profile text for multiple profiles

func (*AWSConfigFile) GetProfile

func (cf *AWSConfigFile) GetProfile(name string) (Profile, bool)

GetProfile retrieves a profile by name

func (*AWSConfigFile) GetProfileNameConflicts

func (cf *AWSConfigFile) GetProfileNameConflicts(proposedNames []string) []string

GetProfileNameConflicts checks for profile name conflicts with proposed names

func (*AWSConfigFile) GetProfileNames

func (cf *AWSConfigFile) GetProfileNames() []string

GetProfileNames returns all profile names in the config file

func (*AWSConfigFile) HasProfile

func (cf *AWSConfigFile) HasProfile(name string) bool

HasProfile checks if a profile exists in the config file

func (*AWSConfigFile) HasProfileName

func (cf *AWSConfigFile) HasProfileName(profileName string) bool

HasProfileName checks if a profile name already exists

func (*AWSConfigFile) LoadSSOSessions

func (cf *AWSConfigFile) LoadSSOSessions() error

LoadSSOSessions loads SSO session configurations from the config file

func (*AWSConfigFile) MatchesRole

func (cf *AWSConfigFile) MatchesRole(profile Profile, accountID, roleName, startURL string) (bool, error)

MatchesRole compares profiles against discovered roles using normalized SSO config

func (*AWSConfigFile) RemoveProfile

func (cf *AWSConfigFile) RemoveProfile(profileName string) error

RemoveProfile safely removes an existing profile

func (*AWSConfigFile) ReplaceProfile

func (cf *AWSConfigFile) ReplaceProfile(oldName, newName string, newProfile Profile) error

ReplaceProfile atomically replaces an existing profile with a new one

func (*AWSConfigFile) ResolveProfileSSOConfig

func (cf *AWSConfigFile) ResolveProfileSSOConfig(profile Profile) (*ResolvedSSOConfig, error)

ResolveProfileSSOConfig normalizes both legacy and session-based SSO formats

func (*AWSConfigFile) ResolveSSOSession

func (cf *AWSConfigFile) ResolveSSOSession(sessionName string) (*SSOSession, error)

ResolveSSOSession resolves an SSO session reference to actual configuration

func (*AWSConfigFile) RestoreFromBackup

func (cf *AWSConfigFile) RestoreFromBackup(backupPath string) error

RestoreFromBackup recovers from a backup file after failed operations

func (*AWSConfigFile) ValidateConfigIntegrity

func (cf *AWSConfigFile) ValidateConfigIntegrity() error

ValidateConfigIntegrity ensures the config file maintains integrity after operations

func (*AWSConfigFile) WriteToFile

func (cf *AWSConfigFile) WriteToFile() error

WriteToFile writes the config file to disk with backup creation and file locking

type ActionType

type ActionType int

ActionType represents the action taken for a specific conflict

const (
	// ActionReplace replaces existing profile
	ActionReplace ActionType = iota
	// ActionSkip skips generating profile for this role
	ActionSkip
	// ActionCreate creates new profile (no conflict)
	ActionCreate
)

ActionType constants represent different actions for handling conflicts

func (ActionType) String

func (at ActionType) String() string

String returns the string representation of the action type

type AppMeshVirtualNode

type AppMeshVirtualNode struct {
	VirtualNodeName string
	BackendServices []string
	BackendNodes    []string
}

AppMeshVirtualNode contains information about an App Mesh Virtual Node

func GetAllAppMeshNodeConnections

func GetAllAppMeshNodeConnections(meshname *string, svc *appmesh.Client) []AppMeshVirtualNode

GetAllAppMeshNodeConnections retrieves all nodes and which services/nodes they connect to

type AppMeshVirtualService

type AppMeshVirtualService struct {
	VirtualServiceName   string
	VirtualServiceRoutes []AppMeshVirtualServiceRoute
	VirtualServicePaths  []AppMeshVirtualServicePath
}

AppMeshVirtualService contains information about an App Mesh Virtual Service

func GetAllAppMeshPaths

func GetAllAppMeshPaths(meshName *string, svc *appmesh.Client) []AppMeshVirtualService

GetAllAppMeshPaths retrieves all the connections in the mesh

func (*AppMeshVirtualService) AddPath

func (service *AppMeshVirtualService) AddPath(path AppMeshVirtualServicePath)

AddPath adds a path to an AppMeshVirtualService

type AppMeshVirtualServicePath

type AppMeshVirtualServicePath struct {
	VirtualNode string
	ServiceName string
}

AppMeshVirtualServicePath shows virtual nodes and their backend that a service might be connected to

type AppMeshVirtualServiceRoute

type AppMeshVirtualServiceRoute struct {
	Router          string
	Path            string
	DestinationNode string
	Weight          int32
}

AppMeshVirtualServiceRoute contains information about an App Mesh route

type AttachedIAMPolicy

type AttachedIAMPolicy struct {
	Name   string
	Users  []string
	Groups []string
}

AttachedIAMPolicy is used to connect usernames, groups, and policy names

func (*AttachedIAMPolicy) AddObject

func (policy *AttachedIAMPolicy) AddObject(object IAMObject)

AddObject adds an IAMObject (user or group) to the AttachedIAMPolicy

type BackupError

type BackupError struct {
	ProfileGeneratorError
	BackupPath   string
	OriginalPath string
	Operation    string
}

BackupError represents errors that occur during backup and recovery operations

func NewBackupError

func NewBackupError(message string, cause error, backupPath, originalPath string) *BackupError

NewBackupError creates a new backup error

func (*BackupError) Error

func (be *BackupError) Error() string

Error implements the error interface with enhanced context

func (*BackupError) RecoveryGuidance

func (be *BackupError) RecoveryGuidance() string

RecoveryGuidance provides guidance for recovering from backup errors

func (*BackupError) WithOperation

func (be *BackupError) WithOperation(operation string) *BackupError

WithOperation adds operation context to the backup error

type CachedToken

type CachedToken struct {
	AccessToken           string    `json:"accessToken"`
	ExpiresAt             time.Time `json:"expiresAt"`
	Region                string    `json:"region"`
	StartURL              string    `json:"startUrl"`
	ClientID              string    `json:"clientId,omitempty"`
	ClientSecret          string    `json:"clientSecret,omitempty"`
	RegistrationExpiresAt time.Time `json:"registrationExpiresAt"`
	RefreshToken          string    `json:"refreshToken,omitempty"`
}

CachedToken represents a cached SSO token

type ConflictAction

type ConflictAction struct {
	Conflict ProfileConflict `json:"conflict" yaml:"conflict"`
	Action   ActionType      `json:"action" yaml:"action"`
	NewName  string          `json:"new_name" yaml:"new_name"`
	OldName  string          `json:"old_name" yaml:"old_name"`
}

ConflictAction represents the action taken for a specific conflict

func (*ConflictAction) Validate

func (ca *ConflictAction) Validate() error

Validate checks if the conflict action is valid

type ConflictResolutionError

type ConflictResolutionError struct {
	ProfileGeneratorError
	ConflictType ConflictType
	ProfileName  string
	RoleName     string
	AccountID    string
}

ConflictResolutionError represents errors that occur during profile conflict resolution

func NewConflictResolutionError

func NewConflictResolutionError(message string, cause error, conflictType ConflictType) *ConflictResolutionError

NewConflictResolutionError creates a new conflict resolution error

func (*ConflictResolutionError) Error

func (cre *ConflictResolutionError) Error() string

Error implements the error interface with enhanced context

func (*ConflictResolutionError) RecoveryGuidance

func (cre *ConflictResolutionError) RecoveryGuidance() string

RecoveryGuidance provides guidance for recovering from conflict resolution errors

func (*ConflictResolutionError) WithProfileContext

func (cre *ConflictResolutionError) WithProfileContext(profileName, roleName, accountID string) *ConflictResolutionError

WithProfileContext adds profile-specific context to the conflict resolution error

type ConflictResolutionResult

type ConflictResolutionResult struct {
	GeneratedProfiles []GeneratedProfile `json:"generated_profiles" yaml:"generated_profiles"`
	SkippedRoles      []DiscoveredRole   `json:"skipped_roles" yaml:"skipped_roles"`
	Actions           []ConflictAction   `json:"actions" yaml:"actions"`
}

ConflictResolutionResult represents the result of conflict resolution

type ConflictResolutionStrategy

type ConflictResolutionStrategy int

ConflictResolutionStrategy defines how to handle existing profile conflicts

const (
	// ConflictPrompt prompts the user for each conflict (default)
	ConflictPrompt ConflictResolutionStrategy = iota
	// ConflictReplace replaces existing profiles
	ConflictReplace
	// ConflictSkip skips roles with existing profiles
	ConflictSkip
)

ConflictResolutionStrategy constants represent different strategies for resolving conflicts

func (ConflictResolutionStrategy) String

func (crs ConflictResolutionStrategy) String() string

String returns the string representation of the conflict resolution strategy

func (ConflictResolutionStrategy) Validate

func (crs ConflictResolutionStrategy) Validate() error

Validate checks if the conflict resolution strategy is valid

type ConflictType

type ConflictType int

ConflictType represents the type of profile conflict detected

const (
	// ConflictSameRole represents same SSO account ID and role name
	ConflictSameRole ConflictType = iota
	// ConflictSameName represents same profile name but different role
	ConflictSameName
)

ConflictType constants represent different types of profile conflicts

func (ConflictType) String

func (ct ConflictType) String() string

String returns the string representation of the conflict type

type DiscoveredRole

type DiscoveredRole struct {
	AccountID         string `json:"account_id" yaml:"account_id"`
	AccountName       string `json:"account_name" yaml:"account_name"`
	AccountAlias      string `json:"account_alias" yaml:"account_alias"`
	PermissionSetName string `json:"permission_set_name" yaml:"permission_set_name"`
	PermissionSetArn  string `json:"permission_set_arn,omitempty" yaml:"permission_set_arn,omitempty"`
	RoleName          string `json:"role_name" yaml:"role_name"`
}

DiscoveredRole represents a role discovered through SSO enumeration process. It contains information about an AWS role that the user has access to through SSO, including account details and permission set information.

The role discovery process queries the SSO service to find all accounts and roles that the user can assume using their SSO credentials. Each discovered role can potentially become a generated profile.

Example:

role := DiscoveredRole{
    AccountID: "123456789012",
    AccountName: "production",
    PermissionSetName: "AdministratorAccess",
    RoleName: "AWSReservedSSO_AdministratorAccess_abc123",
}

func (*DiscoveredRole) Validate

func (dr *DiscoveredRole) Validate() error

Validate checks if the discovered role is valid and contains all required information. It ensures the role has proper AWS account ID format and all necessary fields.

Validation rules: - Account ID must be present and exactly 12 digits - Permission set name is required (used for profile naming) - Role name is required (used for AWS API calls) - Account ID must match AWS account ID format (12 digits)

Returns a ProfileGeneratorError with detailed context if validation fails.

type ENILookupCache

type ENILookupCache struct {
	VPCEndpoints     map[string]*types.VpcEndpoint // VPC ID -> endpoints in that VPC
	InstanceNames    map[string]string             // Instance ID -> name
	TransitGateways  map[string]string             // VPC ID -> TGW attachment ID
	NATGateways      map[string]*types.NatGateway  // VPC ID -> NAT gateways in that VPC
	EndpointsByENI   map[string]*types.VpcEndpoint // ENI ID -> VPC endpoint
	NATGatewaysByENI map[string]*types.NatGateway  // ENI ID -> NAT gateway
}

ENILookupCache contains pre-fetched AWS resource data to avoid N+1 API calls This cache dramatically improves performance when analyzing many ENIs by batching API calls instead of making individual requests for each ENI's attachment details.

Performance benefits: - VPC Endpoints: 1 batched DescribeVpcEndpoints call vs N individual calls - EC2 Instances: Batched DescribeInstances calls vs N individual calls - NAT Gateways: 1 batched DescribeNatGateways call vs N individual calls - Transit Gateways: 1 batched DescribeTransitGatewayVpcAttachments call vs N individual calls

For 100 ENIs, this reduces API calls from ~400 to ~4, significantly improving performance and reducing the chance of hitting AWS API rate limits.

func NewENILookupCache

func NewENILookupCache(svc *ec2.Client, networkInterfaces []types.NetworkInterface) *ENILookupCache

NewENILookupCache creates and populates a cache with all required AWS resource data

type ErrorType

type ErrorType int

ErrorType represents the category of profile generator errors

const (
	// ErrorTypeValidation represents validation errors
	ErrorTypeValidation ErrorType = iota
	// ErrorTypeAuth represents authentication errors
	ErrorTypeAuth
	// ErrorTypeAPI represents API errors
	ErrorTypeAPI
	// ErrorTypeFileSystem represents file system errors
	ErrorTypeFileSystem
	// ErrorTypeNetwork represents network errors
	ErrorTypeNetwork
	// ErrorTypeConflictResolution represents conflict resolution errors
	ErrorTypeConflictResolution
	// ErrorTypeBackup represents backup errors
	ErrorTypeBackup
)

ErrorType constants represent different categories of profile generator errors

func (ErrorType) String

func (et ErrorType) String() string

String returns the string representation of ErrorType

type GeneratedProfile

type GeneratedProfile struct {
	Name         string `json:"name" yaml:"name"`
	AccountID    string `json:"account_id" yaml:"account_id"`
	AccountName  string `json:"account_name" yaml:"account_name"`
	RoleName     string `json:"role_name" yaml:"role_name"`
	Region       string `json:"region" yaml:"region"`
	SSOStartURL  string `json:"sso_start_url" yaml:"sso_start_url"`
	SSORegion    string `json:"sso_region" yaml:"sso_region"`
	SSOSession   string `json:"sso_session" yaml:"sso_session"`
	SSOAccountID string `json:"sso_account_id" yaml:"sso_account_id"`
	SSORoleName  string `json:"sso_role_name" yaml:"sso_role_name"`
	IsLegacy     bool   `json:"is_legacy" yaml:"is_legacy"`
}

GeneratedProfile represents a generated profile configuration that will be written to the AWS config file. It contains all the necessary information to create a working AWS CLI profile for a specific role in a specific account.

Generated profiles inherit their SSO configuration from the template profile but are customized with account-specific and role-specific information discovered through the SSO enumeration process.

The profile can be in either legacy or new SSO format, determined by the IsLegacy field.

func (*GeneratedProfile) ToConfigString

func (gp *GeneratedProfile) ToConfigString() string

ToConfigString returns the profile configuration in AWS config file format. It generates the appropriate format based on whether the profile uses legacy or new SSO format.

Legacy format output:

[profile example-profile]
region = us-east-1
sso_start_url = https://my-org.awsapps.com/start
sso_region = us-east-1
sso_account_id = 123456789012
sso_role_name = AdministratorAccess

New format output:

[profile example-profile]
region = us-east-1
sso_start_url = https://my-org.awsapps.com/start
sso_region = us-east-1
sso_session = my-session

The output includes a trailing newline for proper file formatting.

func (*GeneratedProfile) Validate

func (gp *GeneratedProfile) Validate() error

Validate checks if the generated profile is valid and ready for writing to config file. It ensures all required fields are present and the profile format is consistent.

Validation rules: - Profile name, account ID, role name, SSO start URL, and SSO region are required - Legacy profiles cannot have SSO session configured - New format profiles must have SSO session configured - Format consistency is enforced based on IsLegacy flag

Returns a ProfileGeneratorError with detailed context if validation fails.

type IAMGroup

type IAMGroup struct {
	Name             string
	ID               string
	Users            []string
	AttachedPolicies map[string]string
	InlinePolicies   map[string]string
	Group            *types.Group
}

IAMGroup contains information about IAM Groups

func GetGroupDetails

func GetGroupDetails(svc *iam.Client) []IAMGroup

GetGroupDetails collects detailed information about a group, consisting mostly of the users and policies it follows.

func (IAMGroup) GetDirectPolicies

func (group IAMGroup) GetDirectPolicies() map[string]string

GetDirectPolicies retrieves all directly attached policies for the group

func (IAMGroup) GetGroups

func (group IAMGroup) GetGroups() []string

GetGroups returns an empty string slice

func (IAMGroup) GetID

func (group IAMGroup) GetID() string

GetID returns the ID of the object

func (IAMGroup) GetInheritedPolicies

func (group IAMGroup) GetInheritedPolicies() map[string]string

GetInheritedPolicies retrieves all inherited policies for the group (none)

func (IAMGroup) GetName

func (group IAMGroup) GetName() string

GetName returns the name of the group

func (IAMGroup) GetObjectType

func (group IAMGroup) GetObjectType() string

GetObjectType returns the type of IAM object

func (IAMGroup) GetUsers

func (group IAMGroup) GetUsers() []string

GetUsers returns the users attached to the Group

type IAMObject

type IAMObject interface {
	GetName() string
	GetID() string
	GetUsers() []string
	GetGroups() []string
	GetObjectType() string
	GetDirectPolicies() map[string]string
	GetInheritedPolicies() map[string]string
}

IAMObject interface for IAM objects

type IAMPolicyDocument

type IAMPolicyDocument struct {
	Name      string
	Version   string
	Type      string
	Statement []IAMPolicyDocumentStatement
	Roles     []*IAMRole
	Groups    []*IAMGroup
	Users     []*IAMUser
}

IAMPolicyDocument is an abstracted version of an IAM Policy Document

func (*IAMPolicyDocument) AddRole

func (policy *IAMPolicyDocument) AddRole(role *IAMRole)

AddRole adds the role to the policy document

func (*IAMPolicyDocument) GetRoleNames

func (policy *IAMPolicyDocument) GetRoleNames() []string

GetRoleNames returns the names of the roles the policy is attached to

type IAMPolicyDocumentStatement

type IAMPolicyDocumentStatement struct {
	Effect    string
	Principal map[string]string
	Action    any
	Condition any
	Resource  any
}

IAMPolicyDocumentStatement is an abstracted version of a Statement for a policy document

type IAMRole

type IAMRole struct {
	Name             string
	ID               string
	Path             string
	AssumeRolePolicy IAMPolicyDocument
	InlinePolicies   map[string]*IAMPolicyDocument
	AttachedPolicies map[string]*IAMPolicyDocument
	Role             *types.Role
	Type             string
	Verbose          bool
}

IAMRole is an abstracted version of an IAM Role

func GetRoleDetails

func GetRoleDetails(verbose bool, svc *iam.Client) []IAMRole

GetRoleDetails returns the list of roles in the account

func GetRolesAndPolicies

func GetRolesAndPolicies(verbose bool, svc *iam.Client) ([]IAMRole, map[string]IAMPolicyDocument)

GetRolesAndPolicies returns all the roles and and their attached policies

func (*IAMRole) CanBeAssumedFrom

func (role *IAMRole) CanBeAssumedFrom() []string

CanBeAssumedFrom returns information about the assumerole policy

func (IAMRole) GetPolicyNames

func (role IAMRole) GetPolicyNames() []string

GetPolicyNames returns the names of the policies attached to the role

type IAMUser

type IAMUser struct {
	Name                  string
	ID                    string
	AttachedPolicies      map[string]string
	InlinePolicies        map[string]string
	Groups                []string
	AttachedGroupPolicies map[string]string
	InlineGroupPolicies   map[string]string
	User                  *types.User
}

IAMUser contains information about IAM Users

func GetUserDetails

func GetUserDetails(svc *iam.Client) []IAMUser

GetUserDetails collects detailed information about a user, consisting mostly of the groups and policies it follows.

func (IAMUser) GetAllPolicies

func (user IAMUser) GetAllPolicies() map[string]string

GetAllPolicies retrieves a map of all the users policies

func (IAMUser) GetDirectPolicies

func (user IAMUser) GetDirectPolicies() map[string]string

GetDirectPolicies retrieves all directly attached policies for the user

func (IAMUser) GetGroups

func (user IAMUser) GetGroups() []string

GetGroups returns the list of groups the user has

func (IAMUser) GetID

func (user IAMUser) GetID() string

GetID returns the ID of the object

func (IAMUser) GetInheritedPolicies

func (user IAMUser) GetInheritedPolicies() map[string]string

GetInheritedPolicies retrieves all inherited policies for the user

func (IAMUser) GetLastAccessKeyDate

func (user IAMUser) GetLastAccessKeyDate(svc *iam.Client) time.Time

GetLastAccessKeyDate returns the last date an access key was used

func (IAMUser) GetLastPasswordDate

func (user IAMUser) GetLastPasswordDate() time.Time

GetLastPasswordDate returns the last date the user's password was used

func (IAMUser) GetName

func (user IAMUser) GetName() string

GetName returns the name of the user

func (IAMUser) GetObjectType

func (user IAMUser) GetObjectType() string

GetObjectType returns the type of IAM object

func (IAMUser) GetUsers

func (user IAMUser) GetUsers() []string

GetUsers returns an empty string slice

func (IAMUser) HasAccessKeys

func (user IAMUser) HasAccessKeys(svc *iam.Client) bool

HasAccessKeys checks if a user has access keys

func (IAMUser) HasUsedPassword

func (user IAMUser) HasUsedPassword() bool

HasUsedPassword checks if the user has used their password

type IPAddressInfo

type IPAddressInfo struct {
	IPAddress      string `json:"ip_address"`
	UsageType      string `json:"usage_type"`
	AttachmentInfo string `json:"attachment_info"`
	PublicIP       string `json:"public_ip,omitempty"`
}

IPAddressInfo contains information about individual IP addresses

type IPFinderResult

type IPFinderResult struct {
	IPAddress      string                  `json:"ip_address"`
	ENI            *types.NetworkInterface `json:"eni,omitempty"`
	ResourceType   string                  `json:"resource_type"`
	ResourceName   string                  `json:"resource_name"`
	ResourceID     string                  `json:"resource_id"`
	VPC            VPCInfo                 `json:"vpc"`
	Subnet         SubnetInfo              `json:"subnet"`
	SecurityGroups []SecurityGroupInfo     `json:"security_groups"`
	RouteTable     RouteTableInfo          `json:"route_table"`
	IsSecondaryIP  bool                    `json:"is_secondary_ip"`
	Found          bool                    `json:"found"`
}

IPFinderResult contains the result of IP address search

func FindIPAddressDetails

func FindIPAddressDetails(svc *ec2.Client, ipAddress string) IPFinderResult

FindIPAddressDetails searches for an IP address across ENIs and returns detailed information Searches both primary and secondary IP addresses on all ENIs

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

Logger interface for logging operations

type NamingPattern

type NamingPattern struct {
	Pattern   string
	Variables map[string]string
}

NamingPattern represents a naming pattern for profile generation

func NewNamingPattern

func NewNamingPattern(pattern string) (*NamingPattern, error)

NewNamingPattern creates a new naming pattern with validation

func TestPattern

func TestPattern(pattern string) (*NamingPattern, []string, error)

TestPattern tests a naming pattern with sample data

func (*NamingPattern) GenerateProfileName

func (np *NamingPattern) GenerateProfileName(accountID, accountName, accountAlias, roleName, region string) (string, error)

GenerateProfileName generates a profile name using the pattern and provided values

func (*NamingPattern) Validate

func (np *NamingPattern) Validate() error

Validate checks if the naming pattern is valid

type OperationType

type OperationType int

OperationType represents the type of operation in a transaction

const (
	// OpAdd represents an add operation
	OpAdd OperationType = iota
	// OpUpdate represents an update operation
	OpUpdate
	// OpRemove represents a remove operation
	OpRemove
)

OperationType constants represent different types of operations in a transaction

func (OperationType) String

func (ot OperationType) String() string

String returns the string representation of the operation type

type OrganizationEntry

type OrganizationEntry struct {
	ID       string
	Name     string
	Arn      string
	Type     string
	Children []OrganizationEntry
}

OrganizationEntry is a helper struct for Organization resources

func GetFullOrganization

func GetFullOrganization(svc *organizations.Client) OrganizationEntry

GetFullOrganization returns the root entry of the organization with all children fleshed out

func (*OrganizationEntry) String

func (entry *OrganizationEntry) String() string

type Profile

type Profile struct {
	Name              string             `json:"name" yaml:"name"`
	Region            string             `json:"region" yaml:"region"`
	SSOStartURL       string             `json:"sso_start_url" yaml:"sso_start_url"`
	SSORegion         string             `json:"sso_region" yaml:"sso_region"`
	SSOAccountID      string             `json:"sso_account_id" yaml:"sso_account_id"`
	SSORoleName       string             `json:"sso_role_name" yaml:"sso_role_name"`
	SSOSession        string             `json:"sso_session" yaml:"sso_session"`
	Output            string             `json:"output" yaml:"output"`
	OtherProperties   map[string]string  `json:"other_properties" yaml:"other_properties"`
	ResolvedSSOConfig *ResolvedSSOConfig `json:"resolved_sso_config,omitempty" yaml:"resolved_sso_config,omitempty"`
}

Profile represents a profile in AWS config file

func (*Profile) IsLegacySSO

func (p *Profile) IsLegacySSO() bool

IsLegacySSO returns true if the profile uses legacy SSO format

func (*Profile) IsSSO

func (p *Profile) IsSSO() bool

IsSSO returns true if the profile is configured for SSO

func (*Profile) ToConfigString

func (p *Profile) ToConfigString() string

ToConfigString converts a Profile to AWS config file format

func (*Profile) Validate

func (p *Profile) Validate() error

Validate checks if the profile is valid

type ProfileConflict

type ProfileConflict struct {
	DiscoveredRole   DiscoveredRole `json:"discovered_role" yaml:"discovered_role"`
	ExistingProfiles []Profile      `json:"existing_profiles" yaml:"existing_profiles"`
	ProposedName     string         `json:"proposed_name" yaml:"proposed_name"`
	ConflictType     ConflictType   `json:"conflict_type" yaml:"conflict_type"`
}

ProfileConflict represents a detected conflict between discovered role and existing profile

func (*ProfileConflict) Validate

func (pc *ProfileConflict) Validate() error

Validate checks if the profile conflict is valid

type ProfileConflictDetector

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

ProfileConflictDetector handles the logic for detecting profile conflicts between discovered AWS roles and existing AWS CLI profiles. It provides efficient conflict detection using pre-built indexes and cached SSO configuration resolution.

The detector implements a sophisticated conflict detection algorithm that: - Matches profiles based on SSO configuration rather than profile names - Supports both legacy and modern SSO profile formats - Uses efficient O(1) lookups through profile indexing - Pre-resolves and caches SSO configurations for performance - Classifies conflicts by type (same role vs same name)

Conflict Detection Algorithm: 1. Pre-resolve all SSO configurations for existing profiles 2. For each discovered role, generate the proposed profile name 3. Find existing profiles that match the role's SSO configuration 4. Find existing profiles that have the same name as proposed 5. Classify conflicts and return detailed conflict information

Performance Optimizations: - Profile lookup index for O(1) profile searches by account ID and name - Pre-resolved SSO configuration cache to avoid repeated resolution - Efficient memory allocation with capacity estimation - Batch processing of conflict detection operations

Example usage:

detector := NewProfileConflictDetector(configFile, namingPattern)
conflicts, err := detector.DetectConflicts(discoveredRoles)
if err != nil {
    // handle error
}

for _, conflict := range conflicts {
    fmt.Printf("Conflict: %s -> %s (%s)\n",
        conflict.DiscoveredRole.RoleName,
        conflict.ProposedName,
        conflict.ConflictType.String())
}

func NewProfileConflictDetector

func NewProfileConflictDetector(configFile *AWSConfigFile, namingPattern *NamingPattern) *ProfileConflictDetector

NewProfileConflictDetector creates a new profile conflict detector with optimized performance features including profile indexing and SSO configuration caching.

The constructor performs several initialization steps: 1. Creates the detector with provided config file and naming pattern 2. Builds an efficient profile lookup index for O(1) searches 3. Pre-resolves and caches SSO configurations for all existing profiles 4. Sets up a default logger (can be overridden with SetLogger)

Parameters:

  • configFile: AWS config file containing existing profiles to check against
  • namingPattern: Pattern used to generate profile names for discovered roles

Returns:

  • *ProfileConflictDetector: Initialized detector ready for conflict detection

Performance Notes: - Profile index creation is O(n) where n is the number of existing profiles - SSO configuration pre-resolution is O(n) but saves time during conflict detection - Memory usage scales linearly with the number of existing profiles

Error Handling: - If profile index creation fails, detector falls back to linear search - If SSO resolution fails for a profile, it's skipped with a warning - Detector remains functional even with partial initialization failures

func (*ProfileConflictDetector) AnalyzeRole

func (pcd *ProfileConflictDetector) AnalyzeRole(role DiscoveredRole) (*ProfileConflict, error)

AnalyzeRole checks a single discovered role for conflicts with existing profiles. This method implements the core conflict detection logic for individual roles.

The analysis process follows these steps: 1. Validates the discovered role has all required fields 2. Generates the proposed profile name using the configured naming pattern 3. Searches for existing profiles that match the role's SSO configuration 4. Searches for existing profiles that have the same name as proposed 5. Combines and deduplicates conflicting profiles 6. Classifies the type of conflict detected 7. Creates and validates the conflict object

Parameters:

  • role: The discovered role to analyze for conflicts

Returns:

  • *ProfileConflict: Detailed conflict information if conflicts found, nil otherwise
  • error: Any error encountered during role analysis

Conflict Detection Logic: - Role Match: Compares SSO start URL, account ID, and role name - Name Match: Compares proposed profile name with existing profile names - Supports both legacy SSO format and modern SSO session format - Uses cached SSO configurations for efficient matching

Error Handling: - Invalid discovered role data returns validation error - Profile name generation failures return validation error - Profile matching failures are logged but don't fail the analysis - Invalid conflict objects return validation error

Performance Notes: - Uses profile index for O(1) lookups when available - Falls back to linear search if index is unavailable - Leverages pre-resolved SSO configuration cache - Efficient memory allocation for conflict data structures

func (*ProfileConflictDetector) ClassifyConflict

func (pcd *ProfileConflictDetector) ClassifyConflict(existingProfiles []Profile, proposedName string, role DiscoveredRole) ConflictType

ClassifyConflict determines the type of conflict detected between a discovered role and existing profiles. This classification helps determine the appropriate resolution strategy.

Conflict Classification Logic: 1. Same Role Conflict: An existing profile already points to the same AWS role

  • Matches on SSO start URL, account ID, and role name
  • Indicates duplicate role configuration with potentially different profile names
  • Resolution typically involves replacing or renaming the existing profile

2. Same Name Conflict: The proposed profile name already exists

  • Matches on profile name but points to a different AWS role
  • Indicates naming collision between different roles
  • Resolution typically involves generating a different name or skipping

The method prioritizes Same Role conflicts over Same Name conflicts when both conditions are present, as role conflicts are more significant for functionality.

Parameters:

  • existingProfiles: List of existing profiles that conflict with the discovered role
  • proposedName: The proposed name for the new profile
  • role: The discovered role being analyzed

Returns:

  • ConflictType: The type of conflict detected (ConflictSameRole or ConflictSameName)

Error Handling: - Profile matching failures are logged as warnings but don't affect classification - Defaults to ConflictSameRole if classification cannot be determined - Handles both legacy and modern SSO profile formats transparently

Example scenarios: - Same Role: Existing "prod-admin" profile points to same role as discovered "production-AdministratorAccess" - Same Name: Existing "prod-admin" profile points to different role than discovered "prod-admin"

func (*ProfileConflictDetector) DetectConflicts

func (pcd *ProfileConflictDetector) DetectConflicts(discoveredRoles []DiscoveredRole) ([]ProfileConflict, error)

DetectConflicts analyzes all discovered roles for conflicts with existing profiles. This is the main entry point for conflict detection and implements the complete conflict detection workflow.

The method processes each discovered role through the following steps: 1. Validates the discovered role data 2. Generates the proposed profile name using the naming pattern 3. Searches for existing profiles that match the role's SSO configuration 4. Searches for existing profiles that have the same name as proposed 5. Classifies the type of conflict detected 6. Creates detailed conflict information for resolution

Parameters:

  • discoveredRoles: Slice of roles discovered through SSO enumeration

Returns:

  • []ProfileConflict: Slice of detected conflicts with detailed information
  • error: Any error encountered during conflict detection

Performance Characteristics: - Time complexity: O(n) where n is the number of discovered roles - Space complexity: O(c) where c is the number of conflicts (typically << n) - Uses pre-built indexes and caches for efficient profile lookups

Error Handling: - Individual role analysis failures are logged as warnings and skipped - Only critical errors (e.g., invalid input) cause the method to fail - Partial results are returned even if some roles fail analysis

Conflict Types Detected: - Same Role: Existing profile points to the same AWS role - Same Name: Proposed profile name already exists but points to different role

Example usage:

conflicts, err := detector.DetectConflicts(discoveredRoles)
if err != nil {
    return fmt.Errorf("conflict detection failed: %w", err)
}

if len(conflicts) > 0 {
    fmt.Printf("Found %d conflicts requiring resolution\n", len(conflicts))
}

func (*ProfileConflictDetector) GenerateConflictSummary

func (pcd *ProfileConflictDetector) GenerateConflictSummary(conflicts []ProfileConflict) string

GenerateConflictSummary creates a human-readable summary of all conflicts

func (*ProfileConflictDetector) SetLogger

func (pcd *ProfileConflictDetector) SetLogger(logger Logger)

SetLogger sets a custom logger

type ProfileGenerationResult

type ProfileGenerationResult struct {
	TemplateProfile     TemplateProfile         `json:"template_profile" yaml:"template_profile"`
	DiscoveredRoles     []DiscoveredRole        `json:"discovered_roles" yaml:"discovered_roles"`
	GeneratedProfiles   []GeneratedProfile      `json:"generated_profiles" yaml:"generated_profiles"`
	ConflictingProfiles []string                `json:"conflicting_profiles" yaml:"conflicting_profiles"`
	SuccessfulProfiles  []string                `json:"successful_profiles" yaml:"successful_profiles"`
	Errors              []ProfileGeneratorError `json:"errors" yaml:"errors"`

	// Enhanced conflict resolution information
	DetectedConflicts []ProfileConflict    `json:"detected_conflicts" yaml:"detected_conflicts"`
	ResolutionActions []ConflictAction     `json:"resolution_actions" yaml:"resolution_actions"`
	ReplacedProfiles  []ProfileReplacement `json:"replaced_profiles" yaml:"replaced_profiles"`
	SkippedRoles      []DiscoveredRole     `json:"skipped_roles" yaml:"skipped_roles"`
	BackupPath        string               `json:"backup_path" yaml:"backup_path"`
}

ProfileGenerationResult represents the comprehensive result of the profile generation process. It contains all information about what was discovered, what conflicts were detected, how they were resolved, and what profiles were ultimately generated.

This result structure supports the enhanced conflict resolution workflow by tracking: - Original discovered roles and template profile used - Conflicts detected between discovered roles and existing profiles - Actions taken to resolve each conflict (replace, skip, create) - Final generated profiles and any errors encountered - Backup information for recovery purposes

The result can be used to generate detailed reports and provide user feedback about the profile generation process.

func (*ProfileGenerationResult) AddError

AddError adds an error to the result. This method is used internally during profile generation to accumulate errors that occur during the process.

func (*ProfileGenerationResult) GenerateConflictReport

func (pgr *ProfileGenerationResult) GenerateConflictReport() string

GenerateConflictReport creates a detailed operation summary for conflict resolution

func (*ProfileGenerationResult) HasErrors

func (pgr *ProfileGenerationResult) HasErrors() bool

HasErrors returns true if there are any errors in the result. This is a convenience method for checking if the profile generation encountered any errors during execution.

func (*ProfileGenerationResult) Summary

func (pgr *ProfileGenerationResult) Summary() string

Summary returns a summary of the profile generation result

func (*ProfileGenerationResult) Validate

func (pgr *ProfileGenerationResult) Validate() error

Validate checks if the profile generation result is valid and internally consistent. It validates the template profile, all discovered roles, and all generated profiles to ensure the result represents a valid profile generation operation.

This validation is useful for testing and ensuring data integrity throughout the profile generation workflow.

Returns the first validation error encountered, or nil if all components are valid.

type ProfileGenerator

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

ProfileGenerator handles the complete profile generation workflow with enhanced conflict resolution capabilities. It orchestrates the entire process from template profile validation through role discovery to final profile generation and conflict resolution.

The ProfileGenerator implements a comprehensive workflow: 1. Template Profile Validation: Ensures the template profile is valid for SSO 2. Role Discovery: Enumerates accessible roles through SSO APIs 3. Conflict Detection: Identifies conflicts with existing profiles 4. Conflict Resolution: Applies user-specified resolution strategy 5. Profile Generation: Creates new profiles for non-conflicted roles 6. Configuration Update: Writes profiles to AWS config file

Conflict Resolution Strategies: - ConflictPrompt: Interactive prompts for each conflict (default) - ConflictReplace: Automatically replace existing profiles - ConflictSkip: Skip roles that have existing profiles

Key Features: - Supports both legacy and modern SSO profile formats - Efficient conflict detection with caching and indexing - Atomic operations with backup and recovery - Comprehensive error handling and recovery - Detailed progress reporting and logging - File locking for concurrent access protection

Error Recovery: - Automatic backup creation before modifications - Rollback capability on partial failures - Graceful handling of malformed configurations - Detailed error context for troubleshooting

Example usage:

generator, err := NewProfileGenerator(
    "my-sso-template",
    "{account_name}-{role_name}",
    false, // not auto-approve
    "", // default config file
    ConflictPrompt,
    awsConfig,
)
if err != nil {
    return err
}

result, err := generator.GenerateProfilesWorkflow()
if err != nil {
    return err
}

fmt.Println(result.GenerateConflictReport())

func NewProfileGenerator

func NewProfileGenerator(templateProfile, namingPattern string, autoApprove bool, outputFile string, conflictStrategy ConflictResolutionStrategy, awsConfig aws.Config) (*ProfileGenerator, error)

NewProfileGenerator creates a new profile generator with comprehensive validation and initialization of all required components for the profile generation workflow.

The constructor performs extensive validation and setup: 1. Validates required parameters (template profile name) 2. Sets default naming pattern if not provided 3. Validates the naming pattern syntax 4. Creates AWS service clients (SSO, STS, IAM) 5. Initializes role discovery service 6. Sets up default logger (can be overridden)

Parameters:

  • templateProfile: Name of existing SSO profile to use as template (required)
  • namingPattern: Pattern for generating profile names (defaults to "{account_name}-{role_name}")
  • autoApprove: Whether to skip user confirmation prompts
  • outputFile: Custom output file path (empty for default ~/.aws/config)
  • conflictStrategy: How to handle conflicts with existing profiles
  • awsConfig: AWS SDK configuration for API authentication

Returns:

  • *ProfileGenerator: Initialized generator ready for profile generation
  • error: Validation or initialization error

Validation Rules: - Template profile name cannot be empty - Naming pattern must be valid (contains recognized placeholders) - AWS configuration must be valid for SSO operations

Error Handling: - Returns ValidationError for invalid parameters - Returns initialization errors from AWS service clients - Provides detailed error context for troubleshooting

Default Values: - Naming pattern: "{account_name}-{role_name}" if not specified - Logger: Default console logger (can be overridden with SetLogger) - Conflict detector: Initialized lazily when first needed

Example usage:

generator, err := NewProfileGenerator(
    "my-sso-profile",           // template profile
    "{account_name}-{role_name}", // naming pattern
    false,                      // require user approval
    "",                         // use default config file
    ConflictPrompt,             // prompt for conflicts
    awsConfig,                  // AWS configuration
)
if err != nil {
    return fmt.Errorf("failed to create generator: %w", err)
}

func (*ProfileGenerator) AppendToConfig

func (pg *ProfileGenerator) AppendToConfig(profiles []GeneratedProfile) error

AppendToConfig appends profiles to the AWS config file

func (*ProfileGenerator) DetectProfileConflicts

func (pg *ProfileGenerator) DetectProfileConflicts(discoveredRoles []DiscoveredRole) ([]ProfileConflict, error)

DetectProfileConflicts detects conflicts between discovered roles and existing profiles

func (*ProfileGenerator) DiscoverRoles

func (pg *ProfileGenerator) DiscoverRoles(templateProfile *TemplateProfile) ([]DiscoveredRole, error)

DiscoverRoles discovers all accessible roles using the template profile

func (*ProfileGenerator) FilterRolesByConflicts

func (pg *ProfileGenerator) FilterRolesByConflicts(discoveredRoles []DiscoveredRole, conflicts []ProfileConflict) (conflictedRoles []DiscoveredRole, nonConflictedRoles []DiscoveredRole)

FilterRolesByConflicts separates discovered roles into conflicted and non-conflicted groups

func (*ProfileGenerator) FormatProgressMessage

func (pg *ProfileGenerator) FormatProgressMessage(phase string, message string, details map[string]any) string

FormatProgressMessage creates a formatted progress message for display

func (*ProfileGenerator) GenerateConflictReport

func (pg *ProfileGenerator) GenerateConflictReport(conflicts []ProfileConflict, result *ConflictResolutionResult) string

GenerateConflictReport creates a detailed report of conflict resolution actions

func (*ProfileGenerator) GenerateProfiles

func (pg *ProfileGenerator) GenerateProfiles(templateProfile *TemplateProfile, discoveredRoles []DiscoveredRole) ([]GeneratedProfile, error)

GenerateProfiles generates profiles from discovered roles

func (*ProfileGenerator) GenerateProfilesForNonConflictedRoles

func (pg *ProfileGenerator) GenerateProfilesForNonConflictedRoles(nonConflictedRoles []DiscoveredRole) ([]GeneratedProfile, error)

GenerateProfilesForNonConflictedRoles generates profiles for roles without conflicts

func (*ProfileGenerator) GenerateProfilesWorkflow

func (pg *ProfileGenerator) GenerateProfilesWorkflow() (*ProfileGenerationResult, error)

GenerateProfilesWorkflow executes the complete profile generation workflow with enhanced conflict resolution capabilities. This is the main orchestration method that coordinates all phases of profile generation.

Workflow Phases: 1. Template Profile Validation

  • Loads and validates the template profile from AWS config
  • Ensures profile is properly configured for SSO
  • Validates SSO configuration format (legacy or modern)

2. Role Discovery

  • Validates SSO token access
  • Enumerates all accessible accounts and roles
  • Applies retry logic for transient failures

3. Conflict Detection

  • Analyzes discovered roles against existing profiles
  • Identifies role-based and name-based conflicts
  • Classifies conflicts for appropriate resolution

4. Conflict Resolution

  • Applies configured resolution strategy
  • Handles user interaction for prompt strategy
  • Tracks all resolution actions taken

5. Profile Generation

  • Generates profiles for non-conflicted roles
  • Creates profiles for resolved conflicts
  • Validates all generated profiles

6. Configuration Update (if auto-approved)

  • Creates backup of existing configuration
  • Writes new profiles to AWS config file
  • Provides rollback on failures

Returns:

  • *ProfileGenerationResult: Comprehensive result with all workflow information
  • error: Critical error that prevented workflow completion

Result Information: - Template profile used and discovered roles - Detected conflicts and resolution actions taken - Generated profiles and successful operations - Replaced profiles and skipped roles - Backup path for recovery - Detailed error information

Error Handling Strategy: - Each phase captures errors in the result object - Critical errors stop workflow execution - Non-critical errors are logged and workflow continues - Partial results are always returned for analysis

Recovery and Rollback: - Automatic backup creation before any modifications - Rollback capability on partial failures - Detailed error context for manual recovery - Preservation of original configuration on errors

Example usage:

result, err := generator.GenerateProfilesWorkflow()
if err != nil {
    fmt.Printf("Workflow failed: %v\n", err)
    if result != nil {
        fmt.Printf("Partial results: %s\n", result.Summary())
    }
    return err
}

fmt.Printf("Generated %d profiles successfully\n", len(result.GeneratedProfiles))
if len(result.DetectedConflicts) > 0 {
    fmt.Printf("Resolved %d conflicts\n", len(result.DetectedConflicts))
}

func (*ProfileGenerator) GetConflictStrategy

func (pg *ProfileGenerator) GetConflictStrategy() ConflictResolutionStrategy

GetConflictStrategy returns the current conflict resolution strategy

func (*ProfileGenerator) GetNamingPattern

func (pg *ProfileGenerator) GetNamingPattern() string

GetNamingPattern returns the naming pattern

func (*ProfileGenerator) GetOutputFile

func (pg *ProfileGenerator) GetOutputFile() string

GetOutputFile returns the output file path

func (*ProfileGenerator) GetProfileGenerationSummary

func (pg *ProfileGenerator) GetProfileGenerationSummary(result *ProfileGenerationResult) string

GetProfileGenerationSummary returns a summary of the profile generation

func (*ProfileGenerator) GetProgressInfo

func (pg *ProfileGenerator) GetProgressInfo(result *ProfileGenerationResult) map[string]any

GetProgressInfo returns information about the current progress of profile generation

func (*ProfileGenerator) GetTemplateProfile

func (pg *ProfileGenerator) GetTemplateProfile() string

GetTemplateProfile returns the template profile name

func (*ProfileGenerator) IsAutoApprove

func (pg *ProfileGenerator) IsAutoApprove() bool

IsAutoApprove returns whether auto-approval is enabled

func (*ProfileGenerator) PreviewProfiles

func (pg *ProfileGenerator) PreviewProfiles(profiles []GeneratedProfile) error

PreviewProfiles displays profiles for user review

func (*ProfileGenerator) PromptForConflictResolution

func (pg *ProfileGenerator) PromptForConflictResolution(conflict ProfileConflict) (ConflictAction, error)

PromptForConflictResolution prompts the user for conflict resolution action

func (*ProfileGenerator) ResolveConflicts

func (pg *ProfileGenerator) ResolveConflicts(conflicts []ProfileConflict) (*ConflictResolutionResult, error)

ResolveConflicts resolves conflicts based on the configured strategy

func (*ProfileGenerator) SetConflictStrategy

func (pg *ProfileGenerator) SetConflictStrategy(strategy ConflictResolutionStrategy)

SetConflictStrategy sets the conflict resolution strategy

func (*ProfileGenerator) SetLogger

func (pg *ProfileGenerator) SetLogger(logger Logger)

SetLogger sets a custom logger

func (*ProfileGenerator) ValidateConfiguration

func (pg *ProfileGenerator) ValidateConfiguration() error

ValidateConfiguration validates the generator configuration

func (*ProfileGenerator) ValidateTemplateProfile

func (pg *ProfileGenerator) ValidateTemplateProfile() (*TemplateProfile, error)

ValidateTemplateProfile validates the template profile configuration

type ProfileGeneratorError

type ProfileGeneratorError struct {
	Type    ErrorType
	Message string
	Cause   error
	Context map[string]any
}

ProfileGeneratorError represents a structured error for profile generation operations

func NewAPIError

func NewAPIError(message string, cause error) ProfileGeneratorError

NewAPIError creates a new API error

func NewAuthError

func NewAuthError(message string, cause error) ProfileGeneratorError

NewAuthError creates a new authentication error

func NewFileSystemError

func NewFileSystemError(message string, cause error) ProfileGeneratorError

NewFileSystemError creates a new filesystem error

func NewNetworkError

func NewNetworkError(message string, cause error) ProfileGeneratorError

NewNetworkError creates a new network error

func NewValidationError

func NewValidationError(message string, cause error) ProfileGeneratorError

NewValidationError creates a new validation error

func (ProfileGeneratorError) Error

func (e ProfileGeneratorError) Error() string

Error implements the error interface

func (ProfileGeneratorError) Unwrap

func (e ProfileGeneratorError) Unwrap() error

Unwrap implements the error unwrapping interface

func (ProfileGeneratorError) WithContext

func (e ProfileGeneratorError) WithContext(key string, value any) ProfileGeneratorError

WithContext adds context information to the error

type ProfileLookupIndex

type ProfileLookupIndex struct {
	ByName    map[string]Profile   // Profile name -> Profile
	BySSO     map[string][]Profile // SSO config key -> Profiles
	ByAccount map[string][]Profile // Account ID -> Profiles
	ByRole    map[string][]Profile // Role name -> Profiles
}

ProfileLookupIndex provides efficient lookup indices for profile searching

func (*ProfileLookupIndex) FindByAccount

func (index *ProfileLookupIndex) FindByAccount(accountID string) []Profile

FindByAccount finds profiles by account ID using the index

func (*ProfileLookupIndex) FindByRole

func (index *ProfileLookupIndex) FindByRole(roleName string) []Profile

FindByRole finds profiles by role name using the index

func (*ProfileLookupIndex) FindBySSO

func (index *ProfileLookupIndex) FindBySSO(startURL, region, accountID, roleName string) []Profile

FindBySSO finds profiles by SSO configuration using the index

func (*ProfileLookupIndex) HasName

func (index *ProfileLookupIndex) HasName(profileName string) bool

HasName checks if a profile name exists using the index

type ProfileNameConflictResolver

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

ProfileNameConflictResolver handles profile name conflicts

func NewProfileNameConflictResolver

func NewProfileNameConflictResolver(existingNames []string) *ProfileNameConflictResolver

NewProfileNameConflictResolver creates a new conflict resolver

func (*ProfileNameConflictResolver) GetAllConflicts

func (resolver *ProfileNameConflictResolver) GetAllConflicts() map[string]int

GetAllConflicts returns all conflicts as a map

func (*ProfileNameConflictResolver) GetConflictCount

func (resolver *ProfileNameConflictResolver) GetConflictCount(name string) int

GetConflictCount returns the number of conflicts for a given name

func (*ProfileNameConflictResolver) ResolveConflict

func (resolver *ProfileNameConflictResolver) ResolveConflict(desiredName string) string

ResolveConflict resolves naming conflicts by appending unique identifiers

type ProfileReplacement

type ProfileReplacement struct {
	OldProfile Profile          `json:"old_profile" yaml:"old_profile"`
	NewProfile GeneratedProfile `json:"new_profile" yaml:"new_profile"`
	OldName    string           `json:"old_name" yaml:"old_name"`
	NewName    string           `json:"new_name" yaml:"new_name"`
}

ProfileReplacement represents a profile that was replaced during conflict resolution

func (*ProfileReplacement) Validate

func (pr *ProfileReplacement) Validate() error

Validate checks if the profile replacement is valid

type ResolvedSSOConfig

type ResolvedSSOConfig struct {
	StartURL  string `json:"start_url" yaml:"start_url"`
	Region    string `json:"region" yaml:"region"`
	AccountID string `json:"account_id" yaml:"account_id"`
	RoleName  string `json:"role_name" yaml:"role_name"`
}

ResolvedSSOConfig represents the resolved SSO configuration for profile matching

func (*ResolvedSSOConfig) Validate

func (r *ResolvedSSOConfig) Validate() error

Validate checks if the resolved SSO config is valid

type RoleDiscovery

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

RoleDiscovery handles discovery of accessible roles using OIDC tokens

func NewRoleDiscovery

func NewRoleDiscovery(ssoClient *sso.Client, stsClient *sts.Client, iamClient *iam.Client) (*RoleDiscovery, error)

NewRoleDiscovery creates a new role discovery instance using OIDC tokens

func (*RoleDiscovery) CleanExpiredTokens

func (rd *RoleDiscovery) CleanExpiredTokens() (int, error)

CleanExpiredTokens removes expired tokens from the cache

func (*RoleDiscovery) ClearAccountCache

func (rd *RoleDiscovery) ClearAccountCache()

ClearAccountCache clears the account name cache

func (*RoleDiscovery) ClearAliasCache

func (rd *RoleDiscovery) ClearAliasCache()

ClearAliasCache clears the account alias cache

func (*RoleDiscovery) DiscoverAccessibleRoles

func (rd *RoleDiscovery) DiscoverAccessibleRoles(templateProfile *TemplateProfile) ([]DiscoveredRole, error)

DiscoverAccessibleRoles discovers all accessible roles using OIDC token approach

func (*RoleDiscovery) DiscoverRolesWithRetry

func (rd *RoleDiscovery) DiscoverRolesWithRetry(templateProfile *TemplateProfile, maxRetries int) ([]DiscoveredRole, error)

DiscoverRolesWithRetry discovers roles with exponential backoff retry

func (*RoleDiscovery) GetAccountAlias

func (rd *RoleDiscovery) GetAccountAlias(accountID string) (string, error)

GetAccountAlias retrieves the account alias for a given account ID

func (*RoleDiscovery) GetAccountInfo

func (rd *RoleDiscovery) GetAccountInfo(accountID string) (string, error)

GetAccountInfo retrieves account information, using cache when available

func (*RoleDiscovery) GetAuthGuideMessage

func (rd *RoleDiscovery) GetAuthGuideMessage(startURL, region string) string

GetAuthGuideMessage returns a helpful message for authentication issues

func (*RoleDiscovery) GetCachedAccountAliases

func (rd *RoleDiscovery) GetCachedAccountAliases() map[string]string

GetCachedAccountAliases returns a copy of the cached account aliases

func (*RoleDiscovery) GetCachedAccountNames

func (rd *RoleDiscovery) GetCachedAccountNames() map[string]string

GetCachedAccountNames returns a copy of the cached account names

func (*RoleDiscovery) GetTokenCacheInfo

func (rd *RoleDiscovery) GetTokenCacheInfo() (map[string]any, error)

GetTokenCacheInfo returns information about the SSO token cache

func (*RoleDiscovery) SetLogger

func (rd *RoleDiscovery) SetLogger(logger Logger)

SetLogger sets a custom logger

func (*RoleDiscovery) TestConnection

func (rd *RoleDiscovery) TestConnection(templateProfile *TemplateProfile) error

TestConnection tests the connection to SSO with the given profile

func (*RoleDiscovery) ValidateTokenAccess

func (rd *RoleDiscovery) ValidateTokenAccess(templateProfile *TemplateProfile) error

ValidateTokenAccess validates that we can access SSO with the given profile

type RouteTableInfo

type RouteTableInfo struct {
	ID     string   `json:"id"`
	Name   string   `json:"name"`
	Routes []string `json:"routes"`
}

RouteTableInfo contains route table information for IP finder

type S3Bucket

type S3Bucket struct {
	Account                        string
	ACLs                           []types.Grant
	EncryptionRules                []types.ServerSideEncryptionRule
	HasEncryption                  bool
	IsPublic                       bool
	LoggingBucket                  string
	LoggingEnabled                 bool
	Name                           string
	OpenACLs                       bool
	Owner                          string
	Policy                         string
	PublicAccessBlockConfiguration types.PublicAccessBlockConfiguration
	PublicPolicy                   bool
	Region                         string
	Replication                    types.ReplicationConfiguration
	Tags                           map[string]string
	Versioning                     bool
	VersioningMFAEnabled           bool
}

S3Bucket represents detailed information about an S3 bucket including security, encryption, and configuration settings

func GetBucketDetails

func GetBucketDetails(svc *s3.Client) []S3Bucket

GetBucketDetails retrieves detailed information for all S3 buckets including encryption, versioning, and policies

func (*S3Bucket) GetReplicationStrings

func (bucket *S3Bucket) GetReplicationStrings() []string

GetReplicationStrings returns a slice of string representations of the bucket's replication rules

type SSOAccount

type SSOAccount struct {
	AccountID          string
	AccountAssignments []SSOAccountAssignment
}

SSOAccount represents an AWS account managed by AWS

func (*SSOAccount) GetPrincipalIDsForPermissionSet

func (account *SSOAccount) GetPrincipalIDsForPermissionSet(permissionset SSOPermissionSet) []string

GetPrincipalIDsForPermissionSet returns the ids of the principals that have been assigned to the provided permission set

type SSOAccountAssignment

type SSOAccountAssignment struct {
	PrincipalType string
	PrincipalID   string
	PermissionSet *SSOPermissionSet
}

SSOAccountAssignment represents which principals are tied to an account using which permission set

type SSOInstance

type SSOInstance struct {
	IdentityStoreID string
	Arn             string
	// PermissionSets contains the permission sets the instance has
	PermissionSets []SSOPermissionSet
	// Accounts contains the accounts with permission sets, those permission sets, and who has access
	Accounts map[string]SSOAccount
}

SSOInstance is the top level representation of an SSO Instance

func GetSSOAccountInstance

func GetSSOAccountInstance(svc *ssoadmin.Client) SSOInstance

GetSSOAccountInstance retrieves the SSO Account Instance and all its data

func (*SSOInstance) GetAccountList

func (instance *SSOInstance) GetAccountList() []string

GetAccountList returns a list of the account numbers in the SSO Instance

func (*SSOInstance) GetPermissionSetList

func (instance *SSOInstance) GetPermissionSetList() []string

GetPermissionSetList returns a list of the permission sets in the SSO Instance

type SSOPermissionSet

type SSOPermissionSet struct {
	Arn             string
	Name            string
	Description     string
	CreatedAt       time.Time
	SessionDuration string
	Accounts        []SSOAccount
	ManagedPolicies []SSOPolicy
	InlinePolicy    string
	Instance        *SSOInstance
}

SSOPermissionSet is the representation of a permission set

func (*SSOPermissionSet) GetAssignmentIDsByAccount

func (permissionset *SSOPermissionSet) GetAssignmentIDsByAccount(accountnr string) []string

GetAssignmentIDsByAccount returns the assigment's principal IDs

func (*SSOPermissionSet) GetManagedPolicyNames

func (permissionset *SSOPermissionSet) GetManagedPolicyNames() []string

GetManagedPolicyNames returns a slice containing the names of the policies attached to the permission set

type SSOPolicy

type SSOPolicy struct {
	Arn  string
	Name string
}

SSOPolicy represents a Managed Policy

type SSOSession

type SSOSession struct {
	Name        string `json:"name" yaml:"name"`
	SSOStartURL string `json:"sso_start_url" yaml:"sso_start_url"`
	SSORegion   string `json:"sso_region" yaml:"sso_region"`
}

SSOSession represents an SSO session configuration

func (*SSOSession) Validate

func (s *SSOSession) Validate() error

Validate checks if the SSO session is valid

type SSOTokenCache

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

SSOTokenCache handles access to AWS SSO token cache

func NewSSOTokenCache

func NewSSOTokenCache() (*SSOTokenCache, error)

NewSSOTokenCache creates a new SSO token cache

func (*SSOTokenCache) CleanExpiredTokens

func (stc *SSOTokenCache) CleanExpiredTokens() (int, error)

CleanExpiredTokens removes expired tokens from the cache

func (*SSOTokenCache) GetAllCachedTokens

func (stc *SSOTokenCache) GetAllCachedTokens() ([]*CachedToken, error)

GetAllCachedTokens returns all cached SSO tokens

func (*SSOTokenCache) GetAuthGuideMessage

func (stc *SSOTokenCache) GetAuthGuideMessage(startURL, region string) string

GetAuthGuideMessage returns a helpful message for authentication issues

func (*SSOTokenCache) GetCacheInfo

func (stc *SSOTokenCache) GetCacheInfo() (map[string]any, error)

GetCacheInfo returns information about the SSO token cache

func (*SSOTokenCache) IsTokenValid

func (stc *SSOTokenCache) IsTokenValid(token *CachedToken) bool

IsTokenValid checks if a token is valid and not expired

func (*SSOTokenCache) LoadTokenForProfile

func (stc *SSOTokenCache) LoadTokenForProfile(startURL, region string) (*CachedToken, error)

LoadTokenForProfile loads cached token for a specific SSO profile

func (*SSOTokenCache) SetLogger

func (stc *SSOTokenCache) SetLogger(logger Logger)

SetLogger sets a custom logger

func (*SSOTokenCache) ValidateProfileToken

func (stc *SSOTokenCache) ValidateProfileToken(profile *TemplateProfile) error

ValidateProfileToken validates that a cached token exists for the given profile

type SecurityGroupInfo

type SecurityGroupInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

SecurityGroupInfo contains security group information for IP finder

type SubnetInfo

type SubnetInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	CIDR string `json:"cidr"`
}

SubnetInfo contains subnet information for IP finder

type SubnetUsageInfo

type SubnetUsageInfo struct {
	ID           string          `json:"id"`
	Name         string          `json:"name"`
	CIDR         string          `json:"cidr"`
	VPCId        string          `json:"vpc_id"`
	VPCName      string          `json:"vpc_name"`
	Tags         []types.Tag     `json:"tags,omitempty"`
	IsPublic     bool            `json:"is_public"`
	TotalIPs     int             `json:"total_ips"`
	AvailableIPs int             `json:"available_ips"`
	UsedIPs      int             `json:"used_ips"`
	IPDetails    []IPAddressInfo `json:"ip_details,omitempty"`
}

SubnetUsageInfo contains detailed subnet usage information

type TemplateProfile

type TemplateProfile struct {
	Name         string `json:"name" yaml:"name"`
	Region       string `json:"region" yaml:"region"`
	SSOStartURL  string `json:"sso_start_url" yaml:"sso_start_url"`
	SSORegion    string `json:"sso_region" yaml:"sso_region"`
	SSOSession   string `json:"sso_session" yaml:"sso_session"`
	SSOAccountID string `json:"sso_account_id" yaml:"sso_account_id"`
	SSORoleName  string `json:"sso_role_name" yaml:"sso_role_name"`
	IsSSO        bool   `json:"is_sso" yaml:"is_sso"`
	IsValid      bool   `json:"is_valid" yaml:"is_valid"`
}

TemplateProfile represents a template profile configuration used as the basis for generating new AWS CLI profiles. It contains the SSO configuration and other settings that will be applied to all generated profiles.

The template profile must be an existing SSO profile in the AWS config file and serves as the authentication context for discovering available roles and accounts.

Example usage:

template := &TemplateProfile{
    Name: "my-sso-profile",
    SSOStartURL: "https://my-org.awsapps.com/start",
    SSORegion: "us-east-1",
    IsSSO: true,
}
if err := template.Validate(); err != nil {
    // handle validation error
}

func (*TemplateProfile) IsLegacyFormat

func (tp *TemplateProfile) IsLegacyFormat() bool

IsLegacyFormat returns true if the profile uses the legacy SSO format. Legacy format uses sso_account_id and sso_role_name directly in the profile, while new format uses sso_session to reference a separate SSO session configuration.

Legacy format example:

[profile my-profile]
sso_start_url = https://my-org.awsapps.com/start
sso_region = us-east-1
sso_account_id = 123456789012
sso_role_name = AdministratorAccess

New format example:

[profile my-profile]
sso_session = my-session
sso_account_id = 123456789012
sso_role_name = AdministratorAccess

func (*TemplateProfile) Validate

func (tp *TemplateProfile) Validate() error

Validate checks if the template profile is valid for profile generation. It ensures all required fields are present and the profile is properly configured for SSO.

Validation rules: - Profile name must not be empty - Profile must be configured for SSO (IsSSO = true) - SSO start URL and region are required - Either SSO session (new format) or account ID + role name (legacy format) must be present

Returns a ProfileGeneratorError with detailed context if validation fails.

type Transaction

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

Transaction represents a transactional operation on the config file

func (*Transaction) AddProfile

func (tx *Transaction) AddProfile(name string, profile Profile) error

AddProfile adds a profile operation to the transaction

func (*Transaction) Commit

func (tx *Transaction) Commit() error

Commit applies all transaction operations to the file system

func (*Transaction) GetOperationSummary

func (tx *Transaction) GetOperationSummary() string

GetOperationSummary returns a human-readable summary of transaction operations

func (*Transaction) GetOperations

func (tx *Transaction) GetOperations() []TransactionOperation

GetOperations returns a copy of all operations in the transaction

func (*Transaction) RemoveProfile

func (tx *Transaction) RemoveProfile(name string) error

RemoveProfile adds a profile removal operation to the transaction

func (*Transaction) ReplaceProfile

func (tx *Transaction) ReplaceProfile(oldName, newName string, newProfile Profile) error

ReplaceProfile adds a profile replacement operation to the transaction

func (*Transaction) Rollback

func (tx *Transaction) Rollback() error

Rollback reverts all transaction operations

func (*Transaction) UpdateProfile

func (tx *Transaction) UpdateProfile(name string, newProfile Profile) error

UpdateProfile adds a profile update operation to the transaction

type TransactionOperation

type TransactionOperation struct {
	Type        OperationType
	ProfileName string
	OldProfile  *Profile
	NewProfile  *Profile
	Description string
}

TransactionOperation represents a single operation within a transaction

type TransitGateway

type TransitGateway struct {
	ID          string
	AccountID   string
	Name        string
	RouteTables map[string]TransitGatewayRouteTable
}

TransitGateway is a struct for managing TransitGateway objects

func GetAllTransitGateways

func GetAllTransitGateways(svc *ec2.Client) []TransitGateway

GetAllTransitGateways returns an array of all Transit Gateways in the account

type TransitGatewayAttachment

type TransitGatewayAttachment struct {
	ID           string
	ResourceType string
	ResourceID   string
}

TransitGatewayAttachment reflects a Transit Gateway Attachment

func GetSourceAttachmentsForTransitGatewayRouteTable

func GetSourceAttachmentsForTransitGatewayRouteTable(routetableID string, svc *ec2.Client) []TransitGatewayAttachment

GetSourceAttachmentsForTransitGatewayRouteTable returns all the source attachments attached to a Transit Gateway route table

type TransitGatewayRoute

type TransitGatewayRoute struct {
	State        string
	CIDR         string
	Attachment   TransitGatewayAttachment
	ResourceType string
	RouteType    string
}

TransitGatewayRoute reflects a Transit Gateway Route object

func GetActiveRoutesForTransitGatewayRouteTable

func GetActiveRoutesForTransitGatewayRouteTable(routetableID string, svc *ec2.Client) []TransitGatewayRoute

GetActiveRoutesForTransitGatewayRouteTable returns all routes that are currently active for a Transit Gateway route table

func GetBlackholeRoutesForTransitGatewayRouteTable

func GetBlackholeRoutesForTransitGatewayRouteTable(routetableID string, svc *ec2.Client) []TransitGatewayRoute

GetBlackholeRoutesForTransitGatewayRouteTable returns all routes that are currently active for a Transit Gateway route table

type TransitGatewayRouteTable

type TransitGatewayRouteTable struct {
	ID                     string
	Name                   string
	Routes                 []TransitGatewayRoute
	SourceAttachments      []TransitGatewayAttachment
	DestinationAttachments []TransitGatewayAttachment
}

TransitGatewayRouteTable is a struct for managing Transit Gateway route table objects

type VPCHolder

type VPCHolder struct {
	ID        string
	AccountID string
}

VPCHolder represents basic information about a VPC

type VPCInfo

type VPCInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	CIDR string `json:"cidr"`
}

VPCInfo contains VPC information for IP finder

type VPCOverview

type VPCOverview struct {
	VPCs    []VPCUsageInfo  `json:"vpcs"`
	Summary VPCUsageSummary `json:"summary"`
}

VPCOverview represents the complete VPC usage analysis

func GetVPCUsageOverview

func GetVPCUsageOverview(svc *ec2.Client) VPCOverview

GetVPCUsageOverview retrieves comprehensive VPC usage information

type VPCRoute

type VPCRoute struct {
	DestinationCIDR   string
	State             string
	DestinationTarget string
}

VPCRoute represents a Route object DestinationTarget shows the target, regardless of the type

type VPCRouteTable

type VPCRouteTable struct {
	Vpc     VPCHolder
	ID      string
	Routes  []VPCRoute
	Subnets []string
	Default bool
}

VPCRouteTable contains the relevant information for a Route Table

func GetAllVPCRouteTables

func GetAllVPCRouteTables(svc *ec2.Client) []VPCRouteTable

GetAllVPCRouteTables returns all the Routetables in the account and region

type VPCUsageInfo

type VPCUsageInfo struct {
	ID      string            `json:"id"`
	Name    string            `json:"name"`
	CIDR    string            `json:"cidr"`
	Tags    []types.Tag       `json:"tags,omitempty"`
	Subnets []SubnetUsageInfo `json:"subnets"`
}

VPCUsageInfo contains detailed information about a single VPC

type VPCUsageSummary

type VPCUsageSummary struct {
	TotalVPCs      int `json:"total_vpcs"`
	TotalSubnets   int `json:"total_subnets"`
	TotalIPs       int `json:"total_ips"`
	UsedIPs        int `json:"used_ips"`
	AWSReservedIPs int `json:"aws_reserved_ips"`
	ServiceIPs     int `json:"service_ips"`
	AvailableIPs   int `json:"available_ips"`
}

VPCUsageSummary contains aggregate VPC usage statistics

type VpcPeering

type VpcPeering struct {
	RequesterVpc VPCHolder
	AccepterVpc  VPCHolder
	PeeringID    string
}

VpcPeering represents a VPC Peering object

func GetAllVpcPeers

func GetAllVpcPeers(svc *ec2.Client) []VpcPeering

GetAllVpcPeers returns the peerings that are present in this region of this account

Jump to

Keyboard shortcuts

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