Files
floci/docs/services/cognito.md
T
Mario Toffia 67bbd2cf13 feat: serve custom domains over TLS as soon as they are created (#3086)
* feat(tls): record runtime-learned hostnames in the certificate metadata

* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime

Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.

* feat(tls): keep runtime-learned hostnames across a boot regeneration

* test(tls): ensureHost is visible to the next TLS handshake without a restart

* docs(tls): custom domains learned at runtime

* test(tls): pin the certificate contracts of a runtime reissue

The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.

* fix(tls): retry a failed listener reload and keep served names across a boot

A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.

At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.

The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.

Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.

* fix(tls): carry a name whose reload failed into later reissues and resets

The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.

Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.

* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA

RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.

The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.

AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.

* refactor(acm): drop the cosmetic Amazon issuer generator

CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.

* docs(acm): certificates chain to the local CA

Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.

* test(acm): the SDK compatibility suite validates the certificate against its chain

GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.

* docs(acm): say when the CA is created and what Issuer reports

ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.

* test(acm): pin key size, an imported chain and the persisted chain

The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.

* test(acm): the python compatibility suite verifies the certificate against its chain

The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.

* fix(acm): write EC private keys as PKCS#8 and classify keys by interface

JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.

Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.

* test(acm): AcmServiceTest pins issuance from the local CA

Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.

* feat(apigateway): serve a custom domain over TLS as soon as it is created

CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.

* feat(iot): serve a customer-managed domain over TLS as soon as it is configured

CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.

* feat(cognito): serve a custom domain over TLS as soon as it is created

CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.

* docs: custom domains are served over TLS on creation

One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.

* test(compat): custom domain reachable over TLS trusting only the ACM chain

RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.

* docs(tls): say which ensureHost outcomes are logged as warnings

* test: pin the custom domain TLS hooks against the service contracts

Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.

* test(acm): build the InUseBy test service with the local CA

AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.

* test(cognito): request an issued ACM certificate in the custom domain TLS tests

Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.

* test(cognito): a concurrent create does not wait for the TLS reload

The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
2026-09-05 22:05:40 -04:00

21 KiB

Cognito

Protocol: JSON 1.1 (X-Amz-Target: AWSCognitoIdentityProviderService.*) Endpoint: POST http://localhost:4566/

Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys.

CreateUserPool supports overiding several values using user-pool tags only at creation time:

  • floci:override-id, to pin the resulting UserPool.Id.
  • floci:override-cognito-client-id
    • set to use-name to use the client name as client ID.
    • set to append-to-name:-somestring to append a string to the client name to be used as client ID.
    • set to prepend-to-name:somestring- to prepend a string to the client name to be used as client ID.
  • floci:override-cognito-client-secret, to set the secret for all clients created in this userpool.

Floci strips reserved floci:* tags from stored and returned UserPoolTags on both create and update paths, so the tag namespace acts as an input-only control channel and is never persisted as user-visible metadata.

Standalone TagResource rejects reserved floci:* keys. ListTagsForResource and UntagResource operate on the persisted user-pool tag map.

An action given a user pool ID that does not resolve returns ResourceNotFoundException with the live service's wording, User pool <poolId> does not exist., so tooling that matches Cognito error text behaves the same way locally.

Supported Actions

User Pools

Action Description
CreateUserPool Creates a local user pool, applying supported floci:* creation-time overrides from tags.
DescribeUserPool Returns the stored user pool configuration.
ListUserPools Lists local user pools visible in the request region.
UpdateUserPool Updates mutable user pool settings and persisted user-pool tags.
DeleteUserPool Deletes a local user pool and its related state.
GetUserPoolMfaConfig Returns the pool's MFA mode and, once configured, its software-token setting.
SetUserPoolMfaConfig Sets MfaConfiguration (OFF/ON/OPTIONAL) and SoftwareTokenMfaConfiguration. An absent MfaConfiguration means OFF, and turning MFA off drops the factor configuration with it. Validation follows the live service: OFF alongside a software-token, email or SMS factor is rejected, and ON/OPTIONAL with none of those three is rejected, in both cases on the member being present, not on its Enabled value. WebAuthnConfiguration sits outside both rules, as it does in AWS. SMS, email and WebAuthn configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have.

User Pool Tags

Action Description
TagResource Adds user-visible tags to a user pool and rejects reserved floci:* tag keys.
UntagResource Removes tags from a user pool's persisted tag map.
ListTagsForResource Returns the persisted user-pool tags.

User Pool Clients

Action Description
CreateUserPoolClient Creates an app client for a user pool, including optional generated secret handling.
DescribeUserPoolClient Returns the stored app client configuration.
ListUserPoolClients Lists app clients for a user pool.
DeleteUserPoolClient Deletes an app client from a user pool.

Resource Servers

Action Description
CreateResourceServer Registers a resource server and scopes for a user pool.
DescribeResourceServer Returns a registered resource server.
ListResourceServers Lists resource servers for a user pool.
UpdateResourceServer Updates a resource server's name and scopes.
DeleteResourceServer Deletes a resource server from a user pool.

Identity Providers

Action Description
CreateIdentityProvider Registers a federated identity provider on a user pool.
DescribeIdentityProvider Returns a registered identity provider.
ListIdentityProviders Lists a user pool's providers as name/type/date summaries.
UpdateIdentityProvider Updates a provider's details, attribute mapping or identifiers.
DeleteIdentityProvider Deletes an identity provider from a user pool.

Providers are stored configuration only. Floci does not perform the federated sign-in flow: there is no /oauth2/authorize or /oauth2/idpresponse endpoint, so a registered provider cannot be used to authenticate. This covers infrastructure tooling that creates and reads provider configuration, not federated login.

Two deliberate divergences from AWS, both consequences of not calling out to a third party:

  • No create-time validation of ProviderDetails. AWS resolves an OIDC provider's oidc_issuer discovery document while handling CreateIdentityProvider, and rejects the call when it is unreachable. Floci stores ProviderDetails opaquely and makes no outbound request, so it also does not enforce the per-provider-type required keys.
  • No injected provider defaults. AWS adds keys such as attributes_url_add_attributes to an OIDC provider's stored details; Floci returns only what was supplied.

AttributeMapping and IdpIdentifiers follow AWS's update semantics: a member the request omits is left unchanged, and an explicitly empty map or list is what clears it. IdpIdentifiers is echoed by CreateIdentityProvider and UpdateIdentityProvider only when the request supplied it, whatever the stored value, while DescribeIdentityProvider always returns it.

User Pool Domains

Action Description
CreateUserPoolDomain Creates a Cognito prefix domain, or a custom domain when CustomDomainConfig.CertificateArn is given. As on AWS, the certificate must exist in ACM in us-east-1 with status ISSUED; the domain is listed under the certificate's InUseBy until it is deleted.
DescribeUserPoolDomain Returns a domain's description, including CloudFrontDistribution for custom domains.
UpdateUserPoolDomain Replaces a custom domain's certificate or changes the managed login version in place. The domain keeps its CloudFrontDistribution, and its InUseBy entry moves to the new certificate.
DeleteUserPoolDomain Deletes a domain from its user pool.

Custom domains

A domain created with CustomDomainConfig answers the OAuth endpoints on that host, as on AWS:

POST https://auth.example.localhost.floci.io/oauth2/token
GET  https://auth.example.localhost.floci.io/oauth2/userInfo

Requests are matched on the Host header, so the name must resolve to Floci (any *.localhost.floci.io does) and, for https, TLS must be enabled. The domain pins its user pool and the account that created it, since these requests carry no AWS credential: a client_id from another pool is refused with invalid_client, and an access token issued by another pool with invalid_token. Domain names are unique across all accounts, as on AWS. The pool's openid-configuration advertises the custom-domain URLs when one exists. Prefix domains (<prefix>.auth.<region>.amazoncognito.com) are stored but not routed, since that hostname never reaches Floci. /oauth2/authorize, /login and /logout are not served on any host.

With TLS enabled, a custom domain (CustomDomainConfig set) is added to Floci's server certificate as soon as it is created, so https://<domain> verifies without a restart; see TLS for the accepted suffixes. A prefix domain is served under amazoncognito.com on AWS, not by Floci, and is left alone.

Log Delivery

Action Description
SetLogDeliveryConfiguration Replaces a user pool's log delivery configuration.
GetLogDeliveryConfiguration Returns a user pool's log delivery configuration.

LogLevel accepts ERROR or INFO, and EventSource accepts userNotification or userAuthEvents. LogConfigurations holds at most 2 entries, and an event source may appear only once across them. Each entry must name a destination: CloudWatchLogsConfiguration, FirehoseConfiguration or S3Configuration, and a request that omits one is rejected the way AWS rejects it. Set replaces the whole list rather than merging, so an empty LogConfigurations is what clears it, and Get always returns the member, as [] when nothing is configured.

The length and enum checks run before the pool is looked up, so an oversized or malformed request naming a pool that does not exist reports the request problem rather than ResourceNotFoundException, and every violation of them is reported in one message.

Floci stores the configuration and never delivers anything to the destination: the log group, delivery stream or bucket is not written to, and is not required to exist. Two further divergences, both deliberate:

  • No pricing-tier gate. AWS refuses userAuthEvents on a pool in the ESSENTIALS tier with FeatureUnavailableInTierException; Floci accepts either event source whatever UserPoolTier says.
  • No destination validation. AWS checks the ARN it is handed; Floci stores it as given.

Admin User Management

Action Description
AdminCreateUser Creates or resends setup for a user in a user pool.
AdminGetUser Returns a user's stored attributes and status.
AdminDeleteUser Deletes a user from a user pool.
AdminSetUserPassword Sets a user's password and permanent-password status.
AdminUpdateUserAttributes Updates attributes for a user in a user pool.
AdminLinkProviderForUser Links an external IdP identity to an existing user's identities attribute.

User Operations

Action Description
SignUp Creates a self-service user for an app client.
ConfirmSignUp Confirms a pending self-service signup.
GetUser Returns attributes for the authenticated access-token user.
GetUserAttributeVerificationCode Issues a verification code for the authenticated user's email or phone_number attribute.
UpdateUserAttributes Updates attributes for the authenticated access-token user.
ChangePassword Changes the authenticated user's password.
ForgotPassword Starts the local forgot-password flow for a user.
ConfirmForgotPassword Completes the forgot-password flow by setting a replacement password.

Authentication

Action Description
InitiateAuth Authenticates app-client users through supported user-password and SRP-style flows.
AdminInitiateAuth Starts an admin authentication flow for a user pool user.
RespondToAuthChallenge Responds to supported Cognito auth challenges.

User Listing

Action Description
ListUsers Lists users stored in a user pool.

Groups

Action Description
CreateGroup Creates a group in a user pool.
GetGroup Returns a user-pool group.
UpdateGroup Updates a user-pool group's stored settings.
ListGroups Lists groups in a user pool.
ListUsersInGroup Lists users assigned to a group.
DeleteGroup Deletes a group from a user pool.
AdminAddUserToGroup Adds a user to a group.
AdminRemoveUserFromGroup Removes a user from a group.
AdminListGroupsForUser Lists the groups assigned to a user.

Managed Login Branding

Action Description
CreateManagedLoginBranding Creates the branding for an app client.
DescribeManagedLoginBranding Returns a branding by its id.
DescribeManagedLoginBrandingByClient Returns the branding attached to an app client.
UpdateManagedLoginBranding Updates a branding's settings, assets or provided-values flag.
DeleteManagedLoginBranding Deletes a branding from its app client.

CreateManagedLoginBranding must name either UseCognitoProvidedValues or Settings; a request with neither is rejected. One branding per app client: a second CreateManagedLoginBranding for the same client is rejected with ManagedLoginBrandingExistsException. ManagedLoginBrandingId must be a version 4 UUID, and a malformed one is rejected before the lookup, as AWS does. Assets holds at most 40 entries on create and on update. Settings is omitted from the response when the caller supplied none, while Assets is always returned. Members an update omits are left unchanged.

The asset-count and branding-id checks run before the pool, client or branding is looked up, so an oversized request naming something that does not exist reports the request problem rather than ResourceNotFoundException, and an update violating both reports them in one message with the asset list first.

Branding is presentation for the hosted UI, which Floci does not serve, so it is stored and returned rather than rendered. Two divergences follow from that:

  • Settings is stored opaquely. AWS validates it against a deep schema, rejecting unknown properties with Invalid settings provided. Validation errors: [{property: $.components...., errorType: UnknownProperty}]. That schema is not published, so Floci accepts any object.
  • A wrongly typed Settings returns a client error. AWS answers that particular input with InternalErrorException and a 500; Floci returns SerializationException: Unexpected field type, which is what AWS returns for a wrongly typed Assets. Reproducing someone else's 500 seemed worse than being consistent.
  • ReturnMergedResources is not honoured. Against AWS it merges Cognito's own default settings and assets into the response: on a pool with 8 configured assets it returns 38. Reproducing that needs Cognito's default corpus, so Floci returns the stored branding either way.

Well-Known And OAuth Endpoints

Endpoint Description
GET /{userPoolId}/.well-known/openid-configuration OpenID discovery document
GET /{userPoolId}/.well-known/jwks.json JSON Web Key Set for JWT validation
POST /cognito-idp/oauth2/token Relaxed OAuth token endpoint for grant_type=client_credentials

POST /cognito-idp/oauth2/token is intentionally emulator-friendly rather than full Cognito parity:

  • It requires an existing client_id.
  • It accepts client_id and client_secret from the form body or Basic auth.
  • It requires a confidential app client created with GenerateSecret=true.
  • It requires AllowedOAuthFlowsUserPoolClient=true and AllowedOAuthFlows=["client_credentials"].
  • It doesn't require a Cognito domain.
  • It returns only access_token, token_type, and expires_in.
  • It validates requested OAuth scopes against the app client's AllowedOAuthScopes and the pool's registered resource-server scopes.
  • It advertises the prefixed token endpoint in /{userPoolId}/.well-known/openid-configuration, or https://<domain>/oauth2/token when the pool has a custom domain (see Custom domains above).

Sign-in Identifiers (UsernameAttributes)

Floci follows real Cognito semantics for pools created with UsernameAttributes (e.g. --username-attributes email):

  • AdminCreateUser/SignUp accept the email (or phone number) as the sign-in value, but the canonical Username is an auto-generated, immutable UUID equal to sub. The supplied email is stored as a mutable alias attribute.
  • ListUsers, AdminGetUser and Lambda trigger event.userName all report the UUID, never the email; the email lives in the email attribute and in event.request.userAttributes.email.
  • Sign-in resolves by the current email alias or the UUID. SECRET_HASH is validated against the exact USERNAME value sent: Base64(HMAC-SHA256(USERNAME + clientId, clientSecret)).
  • In CUSTOM_AUTH / SRP flows, ChallengeParameters.USERNAME echoes the UUID (as real AWS does); the RespondToAuthChallenge SECRET_HASH is validated against the USERNAME sent that round. That USERNAME must still resolve to the session's user — the UUID or any of its current aliases — and a value naming a different user is rejected with NotAuthorizedException.
  • AdminUpdateUserAttributes can change the email; afterwards sign-in works with the new email and fails with the old one, while Username/sub stay fixed.
  • Duplicate email/phone on AdminCreateUser: UsernameExistsException when the incoming alias is unverified, AliasExistsException when it is verified (email_verified=true); pass ForceAliasCreation=true to migrate a verified alias off the previous owner. On AdminUpdateUserAttributes, changing to an in-use alias throws AliasExistsException.

Pools without UsernameAttributes (classic pools, and pools using AliasAttributes) keep the literal Username you supply, unchanged.

Token claims

Floci mirrors AWS's access-token / ID-token split:

  • Access token: sub, username (the UUID), scope (aws.cognito.signin.user.admin for API sign-in), client_id, cognito:groups, jti/origin_jti. It does not carry cognito:username or user attributes like email.
  • ID token: sub, cognito:username, aud, and readable user attributes (email, email_verified, phone_number, custom:*, ...). Attribute claims are filtered by the app client's ReadAttributes (an unset/empty list means all attributes are readable).

Not-found errors (ResourceNotFoundException, UserNotFoundException) return HTTP 400, matching the Cognito JSON protocol.

Configuration

Variable Default Description
FLOCI_SERVICES_COGNITO_ENABLED true Enable or disable the service

Examples

export AWS_ENDPOINT_URL=http://localhost:4566

# Create a user pool
POOL_ID=$(aws cognito-idp create-user-pool \
  --pool-name MyApp \
  --query UserPool.Id --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Create an app client
CLIENT_ID=$(aws cognito-idp create-user-pool-client \
  --user-pool-id $POOL_ID \
  --client-name my-client \
  --generate-secret \
  --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-flows client_credentials \
  --allowed-o-auth-scopes notes/read notes/write \
  --query UserPoolClient.ClientId --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Retrieve the generated client secret
CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client \
  --user-pool-id $POOL_ID \
  --client-id $CLIENT_ID \
  --query UserPoolClient.ClientSecret --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Register a resource server and scopes
aws cognito-idp create-resource-server \
  --user-pool-id $POOL_ID \
  --identifier notes \
  --name "Notes API" \
  --scopes ScopeName=read,ScopeDescription="Read notes" ScopeName=write,ScopeDescription="Write notes" \
  --endpoint-url $AWS_ENDPOINT_URL

# Create a user
aws cognito-idp admin-create-user \
  --user-pool-id $POOL_ID \
  --username alice@example.com \
  --temporary-password Temp1234! \
  --endpoint-url $AWS_ENDPOINT_URL

# Set a permanent password
aws cognito-idp admin-set-user-password \
  --user-pool-id $POOL_ID \
  --username alice@example.com \
  --password Perm1234! \
  --permanent \
  --endpoint-url $AWS_ENDPOINT_URL

# Authenticate
aws cognito-idp initiate-auth \
  --auth-flow USER_PASSWORD_AUTH \
  --client-id $CLIENT_ID \
  --auth-parameters USERNAME=alice@example.com,PASSWORD=Perm1234! \
  --endpoint-url $AWS_ENDPOINT_URL

# Create a group
aws cognito-idp create-group \
  --user-pool-id $POOL_ID \
  --group-name admin \
  --description "Admin group" \
  --endpoint-url $AWS_ENDPOINT_URL

# Add user to group
aws cognito-idp admin-add-user-to-group \
  --user-pool-id $POOL_ID \
  --group-name admin \
  --username alice@example.com \
  --endpoint-url $AWS_ENDPOINT_URL

# List groups for user
aws cognito-idp admin-list-groups-for-user \
  --user-pool-id $POOL_ID \
  --username alice@example.com \
  --endpoint-url $AWS_ENDPOINT_URL

# Fetch the pool discovery document
curl -s "$AWS_ENDPOINT_URL/$POOL_ID/.well-known/openid-configuration"

# Get a machine access token from the OAuth endpoint
curl -s \
  -X POST "$AWS_ENDPOINT_URL/cognito-idp/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "scope=notes/read notes/write"

JWT Validation

Tokens issued by Floci can be validated using the discovery and JWKS endpoints:

http://localhost:4566/$POOL_ID/.well-known/openid-configuration
http://localhost:4566/$POOL_ID/.well-known/jwks.json

Tokens include the cognito:groups claim as a JSON array when the authenticated user belongs to one or more groups.

Tokens issued by Cognito auth flows and the OAuth token endpoint use the emulator base URL plus the pool id:

http://localhost:4566/$POOL_ID

This keeps the issuer, discovery document, JWKS URL, and token endpoint internally consistent for local JWT validation while supporting LocalStack-style confidential clients and resource-server-backed scopes.