test_utils

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EspUserKMSKeyARN          = "arn:aws:kms:test:000000000000:key/espuser-test"
	EspUserJWKSParam          = "/espuser/base/user-jwks-test"
	EspUserRefreshSecretParam = "/espuser/signing/refresh-test"
	EspUserRefreshSecret      = "test-refresh-hmac-secret"
	EspUserIssuer             = "https://issuer.test"
)

Default SSM/issuer values shared by the espuser unit tests. Individual specs can override any of these via EspUserBackendOpts when they historically used different literals.

Variables

View Source
var TestJWKUtil = InitCognitoUtils("us-east-1")

Functions

func AssertAutomationExists

func AssertAutomationExists(groupID, automationID string)

AssertAutomationExists checks that an automation with the given ID exists for the group.

func AssertAutomationNotExists

func AssertAutomationNotExists(groupID, automationID string)

AssertAutomationNotExists checks that an automation with the given ID does NOT exist for the group.

func AssertEmptyGetGroupInfoNotification

func AssertEmptyGetGroupInfoNotification(nodeID string)

AssertEmptyGetGroupInfoNotification checks that an empty getGroupInfo notification was sent to the node.

func AssertGroupAutomationWipeInvoked

func AssertGroupAutomationWipeInvoked(functionName, oldGroupID string)

AssertGroupAutomationWipeInvoked checks that the node_data_reset Lambda was invoked with the group-wide wipe payload for oldGroupID: group_delete set and no nodes named.

func AssertGroupIDAttribute

func AssertGroupIDAttribute(nodeID, expectedGroupID string)

AssertGroupIDAttribute checks that the IoT thing group_id attribute equals the expected value.

func AssertGroupIDAttributeCleared

func AssertGroupIDAttributeCleared(nodeID string)

AssertGroupIDAttributeCleared checks that the IoT thing group_id attribute is empty.

func AssertNoAutomationsForGroup

func AssertNoAutomationsForGroup(groupID string)

AssertNoAutomationsForGroup checks that no automations exist for the given group.

func AssertNoAutomationsForNodes

func AssertNoAutomationsForNodes(groupID string, nodeIDs ...string)

AssertNoAutomationsForNodes checks that no automation in the group still references any of nodeIDs, either as a trigger (trigger IDs lead with "nodeID~") or as an action target. Automations naming none of them are expected to survive.

func AssertNoGroupAutomationWipeInvoked

func AssertNoGroupAutomationWipeInvoked(functionName, oldGroupID string)

AssertNoGroupAutomationWipeInvoked is the negative of AssertGroupAutomationWipeInvoked.

func AssertNoUserGroupMappingsForGroup

func AssertNoUserGroupMappingsForGroup(groupID string)

AssertNoUserGroupMappingsForGroup checks that no user_group_mapping entries exist for the group.

func AssertNodeDataResetInvoked

func AssertNodeDataResetInvoked(functionName, nodeID, oldGroupID string)

AssertNodeDataResetInvoked checks that the node_data_reset Lambda was invoked with a payload whose node_ids list contains nodeID and whose old_group_id matches.

func AssertNodeInGroup

func AssertNodeInGroup(groupID, nodeID string, capabilities ...string)

AssertNodeInGroup asserts the full group-node row for nodeID in groupID. Pass the expected capability tags (e.g. "rmng", "matter"); pass none for a row stored without a capabilities attribute (e.g. via ManuallyAddNodeToGroup).

func AssertNodeNotInGroup

func AssertNodeNotInGroup(groupID, nodeID string)

func AssertNodeNotInSubgroup

func AssertNodeNotInSubgroup(groupID, nodeID, subGroupID string)

AssertNodeNotInSubgroup checks if the given node_id is NOT part of the specified subgroup

func AssertNodeServiceDataDeleted

func AssertNodeServiceDataDeleted(nodeID, serviceName string)

AssertNodeServiceDataDeleted checks that a node service field (e.g. "schedule", "trigger") has been removed from the node_details table.

func AssertNodeServiceDataExists

func AssertNodeServiceDataExists(nodeID, serviceName string)

AssertNodeServiceDataExists checks that a node service field (e.g. "schedule", "trigger") still exists in the node_details table.

func AssertNormalizedEqual

func AssertNormalizedEqual(expected, actual interface{})

func AssertRowInDB

func AssertRowInDB(tableName string, expectedItem map[string]types.AttributeValue)

func AssertRowNotInDB

func AssertRowNotInDB(tableName string, expectedItem map[string]types.AttributeValue)

func AssertShadowDeleted

func AssertShadowDeleted(nodeID string, groups group_node_db.NodesGroups)

AssertShadowDeleted checks if the shadow for the given node and groups is deleted

func AssertUserTagsCleared

func AssertUserTagsCleared(nodeID string)

AssertUserTagsCleared checks that the iparams shadow exists but has no user tags.

func CheckRowInDB

func CheckRowInDB(tableName string, expectedItem map[string]types.AttributeValue) bool

func ConvertAllFloatToInt

func ConvertAllFloatToInt(data interface{}) interface{}

ConvertAllFloatToInt converts all float64 values to ints if they are whole numbers This is necessary because of floating point and integer comparison issues

func CreateCommonSummaryFile

func CreateCommonSummaryFile(filename string) (*os.File, error)

func GetGroupIDFromName

func GetGroupIDFromName(groupName string) (string, error)

func GetPublishedData

func GetPublishedData(testNode *node.Node, sub_topic string) []byte

func GetPublishedDataForNodeGroup

func GetPublishedDataForNodeGroup(testNode *node.Node, groups group_node_db.NodesGroups) []byte

func GetShadowForNodeGroup

func GetShadowForNodeGroup(testNode *node.Node, groups group_node_db.NodesGroups) node.IoTNodeShadow

GetShadowForNodeGroup returns the shadow state for the given node and groups

func ManuallyAddNodeToGroup

func ManuallyAddNodeToGroup(ctx context.Context, groupID, nodeID string)

func ManuallyAddNodeToGroupWithCapabilities

func ManuallyAddNodeToGroupWithCapabilities(ctx context.Context, groupID, nodeID string, capabilities ...string)

ManuallyAddNodeToGroupWithCapabilities adds a group-node row tagged with capabilities.

func NormalizeObject

func NormalizeObject(data interface{}) interface{}

Helper function to recursively normalize a map or list by sorting list

func OIDCAuthProvider

func OIDCAuthProvider(userID string) string

OIDCAuthProvider builds the CognitoAuthenticationProvider string API Gateway stamps on a request from a federated end user, which routes auth to the OIDC user service (and so to IsAdmin == false). Admin-pool callers carry a ":CognitoSignIn:<id>" provider instead.

func PutParam

func PutParam(ctx context.Context, m *mock.MockSSM, name, value string)

func QuickGetItem

func QuickGetItem(tableName string, key map[string]types.AttributeValue) map[string]types.AttributeValue

func QuickGetItemByIndex

func QuickGetItemByIndex(tableName string, indexName string, keyName string, keyValue string) map[string]types.AttributeValue

func RegisterIoTThing

func RegisterIoTThing(nodeID string)

RegisterIoTThing registers an IoT thing in the mock so attribute operations work.

func SetupCognitoUserPoolClients

func SetupCognitoUserPoolClients(cognitoProviderMock *mock.CognitoProviderMock)

SetupCognitoUserPoolClients initializes Cognito user pool clients for testing This is commonly needed for auth-related tests

func SetupNodeServiceData

func SetupNodeServiceData(nodeID, serviceName string, data interface{})

SetupNodeServiceData writes schedule or trigger data into the node_details table so that deletion can be verified later.

func SetupShadow

func SetupShadow(nodeId string, shadowState node.IoTNodeShadow, groups group_node_db.NodesGroups)

SetupShadow sets up the shadow for the given node and groups

func SetupTestAdminUser

func SetupTestAdminUser(ctx context.Context, userID, email string) (*user.User, *rmngctx.RmngContext)

SetupTestAdminUser sets up an admin user in the Cognito admin pool. Admins are Cognito-only: their identity (custom:user_id) lives entirely in the pool, and membership of that pool is the whole privilege — there is no tier above it. Returns the user object and rmng context for convenience

func SetupTestNonAdminUser

func SetupTestNonAdminUser(ctx context.Context, userID, email string) (*user.User, *rmngctx.RmngContext)

SetupTestNonAdminUser seeds an ordinary end user for authorization tests that must be refused by an admin endpoint. Admin privilege is admin-pool membership, so the only caller an admin endpoint refuses is one resolved through the OIDC end-user path — pair this with OIDCAuthProvider when building the request.

func SetupTestUser

func SetupTestUser(ctx context.Context, userID, email string) (*user.User, *rmngctx.RmngContext)

SetupTestUser seeds a passwordless OIDC end user: an espuser-user-details row keyed by userID (via context) and discoverable by Email. This is how production now resolves end users — ResolveESPUserByID(userID) for a caller and lookupUser(email/phone) for the OIDC service — so no Cognito pool entry is created. Returns the user and its context.

func SetupTestUserWithPhone

func SetupTestUserWithPhone(ctx context.Context, userID, email, phone string) (*user.User, *rmngctx.RmngContext)

SetupTestUserWithPhone is SetupTestUser with a phone number on the user_details entry as well, so tests can exercise the by-phone lookup that share-by-user-name uses. Pass an E.164 number; an empty phone behaves exactly like SetupTestUser.

func SortGroup

func SortGroup(group *group.Group)

func TestSetup

func TestSetup()

Types

type CognitoUtils

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

func InitCognitoUtils

func InitCognitoUtils(region string) *CognitoUtils

func (*CognitoUtils) GetAccessToken

func (cu *CognitoUtils) GetAccessToken(sub string, isAdmin bool) string

func (*CognitoUtils) GetAccessTokenWithAdmin

func (cu *CognitoUtils) GetAccessTokenWithAdmin(sub, email string) string

GetAccessTokenWithAdmin mints an admin-pool access token. Admin-pool membership is the whole admin privilege, so there is no second, more-privileged variant.

func (*CognitoUtils) GetAccessTokenWithWrongIssuer

func (cu *CognitoUtils) GetAccessTokenWithWrongIssuer(sub string) string

func (*CognitoUtils) GetAccessTokenWithWrongTokenUse

func (cu *CognitoUtils) GetAccessTokenWithWrongTokenUse(sub string, isAdmin bool) string

func (*CognitoUtils) GetExpiredAccessToken

func (cu *CognitoUtils) GetExpiredAccessToken(sub string, isAdmin bool) string

func (*CognitoUtils) GetForeignPoolAccessToken

func (cu *CognitoUtils) GetForeignPoolAccessToken(username, victimUserID string) string

GetForeignPoolAccessToken mints an access token in a pool RMNG does not own, carrying victimUserID in custom:user_id.

Use it to assert that a code path binds a token to RMNG's own pool before reading an identity off it. The token is genuine, correctly signed, unexpired, and Cognito-shaped. Only the issuer marks it as foreign, so a caller that skips issuer verification cannot tell it apart from a real one and will act on the victim's identity.

The signing key is absent from GetTestJWKS, and the mock is primed so GetUser succeeds for this token. That combination is deliberate: in production GetUser is an anonymous call carrying no pool ID, so Cognito resolves the token against the attacker's own pool and answers normally. A mock that rejected the token would make the test pass whether or not the verification exists.

func (*CognitoUtils) GetForeignPoolID

func (cu *CognitoUtils) GetForeignPoolID() string

GetForeignPoolID names a Cognito user pool outside RMNG's trust boundary, standing in for one an attacker creates in their own AWS account.

func (*CognitoUtils) GetIdentityToken

func (cu *CognitoUtils) GetIdentityToken(sub string, issuer, tokenUse string, expired bool, isAdmin bool, email string, userID string, originJTIOverride ...string) string

GetIdentityToken mints a signed Cognito-shaped token.

originJTIOverride is optional. Real Cognito stamps the same `origin_jti` on the ID and access tokens issued by one authentication event, so by default this derives it from `sub` — which makes any two tokens for the same user a matched pair, the common case in tests. Pass an override to model tokens from two different sign-ins.

func (*CognitoUtils) GetTestJWKS

func (cu *CognitoUtils) GetTestJWKS() []byte

func (*CognitoUtils) GetTestRegion

func (cu *CognitoUtils) GetTestRegion() string

func (*CognitoUtils) SigningKey

func (cu *CognitoUtils) SigningKey() *rsa.PrivateKey

SigningKey returns the shared test private key so callers can mint OIDC tokens (via jwtutil.NewMinter) that verify against the same JWKS this util publishes.

type ESPUserTokenHarness

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

ESPUserTokenHarness stands up the ESP User OIDC verification path for tests: an httptest JWKS server publishing the signing key's public JWK, ESPUSER_ISSUER pointed at it, and the private key stored in the SSM mock. Mint issues RS256 access tokens that auth.VerifyESPUserToken (and thus user.GetUserIDFromToken's OIDC branch) accepts.

func SetupESPUserTokenHarness

func SetupESPUserTokenHarness(ctx context.Context) *ESPUserTokenHarness

SetupESPUserTokenHarness configures the OIDC verification path. Call after TestSetup (it reuses the SSM mock) and defer Close. It mirrors the userinfo lambda's test setup.

func (*ESPUserTokenHarness) Close

func (h *ESPUserTokenHarness) Close()

Close tears down the JWKS server, clears ESPUSER_ISSUER, and drops the per-process JWKS cache so a later suite that doesn't set up OIDC falls straight through to Cognito.

func (*ESPUserTokenHarness) Mint

func (h *ESPUserTokenHarness) Mint(userID string) string

Mint returns a signed RS256 access token whose sub is userID.

func (*ESPUserTokenHarness) MintPair

func (h *ESPUserTokenHarness) MintPair(userID string) (accessToken, idToken string)

MintPair returns an access token and an id token for one sign-in: both carry userID as sub and share an auth-event id, so a receiver pairing them accepts the two together. Two calls yield two distinct sign-ins, which is what a mismatch spec needs.

func (*ESPUserTokenHarness) MintPairForClient

func (h *ESPUserTokenHarness) MintPairForClient(userID, clientID string) (accessToken, idToken string)

MintPairForClient is MintPair for a named client, so a spec can present a pair minted for an audience other than the first-party one (a voice-assistant or MCP token).

type EspUserBackend

type EspUserBackend struct {
	DBMock             *mock.DynamoDBMock
	SSMMock            *mock.MockSSM
	SESMock            *mock.MockSES
	SigningKey         *rsa.PrivateKey
	Issuer             string
	RefreshSecretParam string
	RefreshSecret      string
	// contains filtered or unexported fields
}

EspUserBackend is the installed mock backend: the DynamoDB/SSM/SES mocks, the generated signing key and the resolved env values. Tests read what they need and defer Close.

func SetupEspUserBackend

func SetupEspUserBackend(ctx context.Context, opts ...EspUserBackendOpts) *EspUserBackend

func (*EspUserBackend) Close

func (b *EspUserBackend) Close()

Close tears down the JWKS server (if any) and drops the per-process JWKS cache so a later spec is not served this run's key. Safe to call when no JWKS server was started.

type EspUserBackendOpts

type EspUserBackendOpts struct {
	Issuer             string
	RefreshSecretParam string
	RefreshSecret      string
	WithJWKS           bool // start an httptest JWKS server and point Issuer at it
	WithSES            bool // install a MockSES client (for dispatch/sender specs)
}

EspUserBackendOpts tunes SetupEspUserBackend. A zero value yields the common defaults.

type TFGroup

type TFGroup struct {
	Nodes           []string              `json:"nodes"`
	SubGroups       map[string]TFSubGroup `json:"sub_grps"`
	SharedPrimary   []string              `json:"shared_primary"`
	SharedSecondary []string              `json:"shared_secondary"`
}

func (*TFGroup) Setup

func (g *TFGroup) Setup(context *rmngctx.RmngContext, grp *group.Group, tfOutput *TFOutput)

type TFOutput

type TFOutput struct {
	UserCtx   map[string]*rmngctx.RmngContext
	Groups    map[string]*group.Group
	SubGroups map[string]*group.SubGroup
}

type TFSubGroup

type TFSubGroup struct {
	Nodes  []string `json:"nodes"`
	Shared []string `json:"shared"`
}

func (*TFSubGroup) Setup

func (s *TFSubGroup) Setup(context *rmngctx.RmngContext, grp *group.Group, sgrp *group.SubGroup)

type TFUser

type TFUser struct {
	Groups map[string]TFGroup `json:"grps"`
}

func (*TFUser) Setup

func (u *TFUser) Setup(ctx *rmngctx.RmngContext, tfOutput *TFOutput)

type TestFormation

type TestFormation struct {
	Users map[string]TFUser `json:"users"`
}

func (*TestFormation) Setup

func (tf *TestFormation) Setup() TFOutput

Jump to

Keyboard shortcuts

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