Commit Graph
61 Commits
Author SHA1 Message Date
Vũ Thế Huy e38dba5f11 feat(cognito): support Google identity provider federation (#5868)
* feat(cognito): support Google identity provider federation

* fix(cognito): synchronize federated provisioning, support linked users and retain discovery endpoints

* fix(cognito): preserve stored provider identity for standard OIDC federation

* fix(cognito): refuse disabled users during federated sign-in
2026-10-18 09:20:48 -04:00
Alessandro Lattao 9ea977cafa fix(cognito): give an email sign-in code eight digits (#5873)
Floci issued six digits for every code. Measured on AWS (eu-west-1,
2026-10-16), through a Custom Email Sender that printed what Cognito
handed it: the USER_AUTH EMAIL_OTP sign-in codes were 06988020, 50415180
and 81488702, eight digits, while the sign-up, resent, forgotten-password,
UpdateUserAttribute and VerifyUserAttribute codes had six. A client that
checks the length, or a test that reads the code from a message, sees the
difference.

Only the email sign-in code changes. MFA codes (SMS_MFA, EMAIL_MFA) and
SMS_OTP keep six digits: they were not measured, and nothing here
guesses. The Cognito tests now read codes through one CognitoCodes
helper, in place of the six copies of the same extraction they carried.
2026-10-17 09:14:04 -04:00
outofplace d0e0af502b feat(cognito): support SMS and email MFA challenges (#5104)
SetUserPoolMfaConfig validated SmsMfaConfiguration and
EmailMfaConfiguration but stored neither, SMSMfaSettings was ignored,
and no MFA code was ever sent, so a user who picked SMS or email as a
second factor signed in without one.

- SetUserPoolMfaConfig stores both configurations, GetUserPoolMfaConfig
  returns them, and OFF drops them. SmsMfaConfiguration also sets the
  pool's SmsAuthenticationMessage and SmsConfiguration.
- A pool offers SMS MFA once it has an SmsMfaConfiguration or an
  SmsConfiguration from CreateUserPool or UpdateUserPool, as AWS makes
  SMS an MFA factor for any pool with an SMS configuration.
- SetUserMFAPreference and AdminSetUserMFAPreference store
  SMSMfaSettings. Turning SMS or email MFA on for a user without a
  phone_number or email fails with InvalidParameterException.
  UserMFASettingList and PreferredMfaSetting report SMS_MFA.
- After a password or SRP first factor, the user's factors follow the
  developer guide's MFA logic: with OPTIONAL the factors the user turned
  on, with ON every factor the pool offers and the user can receive. The
  preferred factor's challenge follows, the only factor's, or
  SELECT_MFA_TYPE between several.
- SMS_MFA sends a code through SNS with SmsAuthenticationMessage. Email
  MFA is the EMAIL_OTP challenge, a code through SES with
  EmailMfaConfiguration's subject and message, which also carry the
  USER_AUTH EMAIL_OTP sign-in code once set. Both fire the CustomMessage
  trigger with CustomMessage_Authentication, and a right code marks the
  phone number or email address verified.
- In USER_AUTH, a user with such a factor in an optional-MFA pool is
  offered only password challenges.

Closes #5182
2026-10-15 23:38:41 -04:00
Daniël van Ziel 3ad8c25a4f fix(cognito): validate email attributes before storing users (#5460)
* fix(cognito): validate email attributes before storing users

* fix(cognito): reject escaped and quoted email separators

* fix(cognito): preserve blank attribute deletion on updates

* test(cognito): use inline mocks for final verification services
2026-10-15 09:52:59 -04:00
jwoa95andPriamo 17c40cecbd fix(cognito): reject token validity outside AWS's limits (#5160)
* fix(cognito): reject token validity outside AWS's limits

CreateUserPoolClient and UpdateUserPoolClient accepted any positive token
validity, so a client with one-minute access and ID tokens, or a
20-minute refresh token, worked locally and failed on deploy. AWS allows
access and ID tokens between 5 minutes and 1 day and refresh tokens
between 60 minutes and 3,650 days, in each token's TokenValidityUnits
unit (hours for access and ID tokens, days for refresh tokens, by
default). A client outside them now fails with InvalidParameterException
"Invalid range for token validity.", the message AWS returns.

floci.services.cognito.enforce-token-validity-limits (env
FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS, default true) turns
the check off for tests that want tokens shorter than AWS allows.

* test(scheduler): start recurring test schedules in the future

Since #5610 a rate schedule's first occurrence is its creation time, so
a schedule is due the moment it exists. The application's own dispatcher
keeps ticking every 10 seconds during @QuarkusTest and sees every
schedule, so a tick that lands between CreateSchedule and the test's own
dispatcher fires the schedule once more than the test expects.

Four tests create an enabled rate(1 minute) schedule and count exact
deliveries: recurringScheduleStartsOneExecutionPerOccurrence,
stepFunctionsDeleteScheduleStopsFutureOccurrence,
rateScheduleDeliversEachOccurrenceWithItsScheduledTime and
executionIdsDifferBetweenOccurrences. They now create the schedule
through SchedulerTestHarness.createRecurringSchedule, which sets a
StartDate a day ahead, and tick past it on their scoped dispatcher. The
application's dispatcher skips a schedule before its StartDate, and the
test profile and its tick interval stay as they are.

* test(compat): poll OpenSearch domain readiness every 250 ms against Floci

OpenSearchTest waited for the domain to finish processing in its own loop
that slept 5 s between checks and swallowed InterruptedException. Floci
flips Processing to false on its own 3 s readiness poll, so the test
could sit up to 5 s past the moment the domain was ready.

The wait now goes through TestFixtures.await, polling every 250 ms
against Floci and keeping the 5 s cadence against real AWS, with the
same 3 minute timeout.

* fix(opensearch): run domain containers under an init process so a stop ends them at once

The OpenSearch image's entrypoint is a bash script that starts the server
as its child instead of exec'ing it. Running as PID 1, that script ignores
SIGTERM, so every DeleteDomain, and every shutdown for each domain, waited
out the whole 5 s stop timeout before Docker sent SIGKILL. The server
never saw the SIGTERM either way.

Domain containers now run under Docker's init process, which takes the
SIGTERM and ends the container at once. Stopping a ready 2.11.1 container
took 5.27 s (exit 137) without it and 0.26 s (exit 143) with it, and
DeleteDomain in the compatibility OpenSearchTest took 5.3 s.

The two startDomain tests' shared setup moves into one helper, which the
new init test uses too.

* fix(cognito): keep a RefreshTokenValidity of 0 at 30 days in any unit

AWS replaces a RefreshTokenValidity of 0 with "the default value of 30
days". Floci stored the bare number 30 in the client's refresh token
unit, so a client with RefreshToken=minutes issued 30-minute refresh
tokens. With the token validity limits, any later UpdateUserPoolClient
that left the validity alone re-checked that stored 30 minutes and
failed with "Invalid range for token validity.", for a client Floci had
accepted.

A 0 now becomes 30 days in the client's refresh token unit (2592000
seconds, 43200 minutes, 720 hours or 30 days), on create and on update,
and the limits check runs on that normalized value. Also imports UUID on
a test line that spelled it out in full.

* fix(cognito): reset the settings UpdateUserPoolClient omits to their defaults

AWS: "If you don't provide a value for an attribute, Amazon Cognito sets
it to its default value." The developer guide adds that an update with
one parameter "sets all others to a default value". Floci kept the
stored value of every setting the request left out, so a client could
end up with a combination AWS never produces: an AccessTokenValidity of
60 kept from a minutes client, read in the hours of a units-only update,
was refused as out of range, where AWS resets the validity and accepts.

CreateUserPoolClient and UpdateUserPoolClient now build their settings
in one place, with a new client's default for each one the request
omits, and the update copies them onto the stored client. ClientName is
the exception: the API documents no default for it, so an update without
one keeps the name. The id, the secrets, the dates and the branding are
not settings and stay as they are. An explicitly empty list still clears
the setting.

The AuthSessionValidity tests and the boto3 compatibility test that
asserted the old keep-on-omit behaviour now expect the 3-minute default.

* test: share one self-signed and one user-cert TLS profile across the TLS integration tests

CustomDomainTlsIntegrationTest, TlsEnsureHostIntegrationTest, TlsHttp2HostRoutingIntegrationTest and EcrTlsDataPlaneDockerIntegrationTest each declared a self-signed TLS profile whose static block wrote its own CA-issued leaf before boot, and under @QuarkusTest that leaf is the one served. They now share SelfSignedTlsProfile, which writes one leaf for all four: the SANs TlsConfigSource uses by default, without 127.0.0.1, plus the API Gateway custom domain the HTTP/2 test routes to. The custom domain and ensure-host tests connect by IP and expect a name the leaf doesn't cover yet to be refused, and the JDK falls back to the peer address when the SNI name doesn't match, so a 127.0.0.1 SAN would let those handshakes through. The leaf and its metadata are written fresh every run, which also drops hostnames an earlier run learned at runtime, and the container CA bundle the ECR test relied on is written beside them.

TlsIntegrationTest and TlsUserCertIntegrationTest declared the same user-provided certificate setup apart from paths. They share UserCertTlsProfile, which keeps the certificate file carrying its private key, since TlsUserCertIntegrationTest checks /_floci/ca.pem never echoes it.

Both profiles live in the config test package, beside every class that uses them and the package-private default SAN list, and expose their paths as compile-time constants, so a test can read them without initializing the profile class and rerunning its static block under the running application.

Sharing an application also means no class may leave anything behind for the next. TlsHttp2HostRoutingIntegrationTest now removes the bucket, CloudFront public key, key group and distribution, and the REST API, domain name and base path mapping it creates. EcrTlsDataPlaneDockerIntegrationTest deletes the manifest it pushes, TlsIntegrationTest its queue and TlsUserCertIntegrationTest its parameter. CustomDomainTlsIntegrationTest and TlsEnsureHostIntegrationTest already end with a state reset, which keeps the configured names from the profile's metadata, so neither changes the leaf a later class is served.

The ECR test's registry container also outlived every run: keep-running-on-shutdown defaults to true and the test config never overrides it, and the next application to start adopted the container by name, a developer's own Floci registry included. SelfSignedTlsProfile now names it in the run's sidecar namespace, which SidecarContainersProfile exposes for this, and stops it at shutdown. The test checks for Docker through SidecarContainersProfile.requireDockerAndImage, so a registry a killed run left behind is removed like any other abandoned sidecar.

Part of #4542.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-10-14 17:40:23 -04:00
Hector Ventura 9df4ffbfa1 fix(cognito): refuse user pool custom domains in GovCloud and EUSC (#5614)
* fix(cognito): refuse user pool custom domains in GovCloud

The AWS GovCloud (US) User Guide lists "Custom domains for user pools are
not available" among the Cognito differences
(https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-cog.html),
but CreateUserPoolDomain and UpdateUserPoolDomain treated a
CustomDomainConfig the same in every partition. In a GovCloud region the
request only failed later, on the us-east-1 certificate check, with a
message about the certificate rather than about the feature.

Both operations now refuse a CustomDomainConfig when the request region is
in aws-us-gov, before the certificate is looked at, with an
InvalidParameterException, which the cognito-idp model declares for both.
No source shows AWS's message, so the wording is Floci's own, as for the
API Gateway EDGE gate. Prefix domains keep working in GovCloud. EUSC is
left as it is because no source covers it, and China and the ISO
partitions have no user pools.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(cognito): refuse user pool custom domains in EUSC too

The European Sovereign Cloud guide lists user pool custom domains as not
available, in the same words as the GovCloud guide, so a
CustomDomainConfig in eusc-de-east-1 is now refused with
InvalidParameterException instead of falling through to the us-east-1
certificate check.

The issued-certificate ACM stub the user pool domain unit tests each
carried a copy of moves to one helper, CognitoCertificateStubs.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
2026-10-14 00:45:05 -04:00
jwoa95 641bf980d0 fix(cognito): send the AdminCreateUser invitation with a temporary password (#5155)
AdminCreateUser without TemporaryPassword created a CONFIRMED user with no
password and sent nothing. It now follows the AdminCreateUser reference:

- Without TemporaryPassword a password meeting the pool's policy is
  generated and the user starts in FORCE_CHANGE_PASSWORD. A pool offering
  EMAIL_OTP or SMS_OTP (above Lite) creates a CONFIRMED user without one,
  which needs an email or phone_number for an offered factor and every
  attribute the schema marks as required.
- Without MessageAction the invitation goes to each of
  DesiredDeliveryMediums (default SMS) the user can be reached on, through
  the dispatcher's SES/SNS path and the pool's EmailConfiguration sender.
  The text comes from the CustomMessage_AdminCreateUser trigger, the pool's
  InviteMessageTemplate, or AWS's default. A message without {####} is not
  delivered to a user with a password.
- SUPPRESS sends nothing. RESEND sets a new temporary password, the
  requested one or a generated one, and sends the invitation again.
- The invitation is sent before anything is stored, so a failed delivery
  (CodeDeliveryFailureException) creates no user, keeps a resent user's
  previous password and leaves a ForceAliasCreation alias in place.
- MessageAction and DesiredDeliveryMediums outside their enums are refused
  with InvalidParameterException.
- AWS::Cognito::UserPoolUser passes DesiredDeliveryMediums, ValidationData
  and ClientMetadata through.

Closes #5144
2026-10-12 19:01:22 -04:00
Mario Toffia 2d7ebcb51c feat(cognito): accept the refresh_token grant on the OAuth token endpoint (#4948)
POST /cognito-idp/oauth2/token, and /oauth2/token on a custom domain, now
renew a session with grant_type=refresh_token through the refresh that
GetTokensFromRefreshToken uses, answering as AWS does. As on AWS, the
grant requires neither ALLOW_REFRESH_TOKEN_AUTH nor any OAuth setting on
the client. The client is checked before the token: a Basic header names
it whatever the body says. A public client's Basic credentials are
refused, and its body client_secret is ignored. Errors are 400 without
WWW-Authenticate: invalid_client for a missing or unknown client, a
public client's Basic credentials with an empty secret, or another pool's
client on a custom domain; invalid_client with invalid_client_secret for
a missing or wrong secret, or a public client's Basic credentials with a
secret; invalid_request with invalid_refresh_token for an empty or absent
token; and invalid_grant for a token that is not valid, expired, revoked,
or another client's. The answer has access_token, expires_in, token_type,
and an id_token exactly when the original sign-in issued one, and no
refresh_token, as rotation is not implemented. A request without
grant_type is now invalid_request with no description, as on AWS.

A code grant's refresh token now carries its granted scopes, base64url
encoded in a field after the family id, so a refresh keeps them instead of
falling back to aws.cognito.signin.user.admin, and the pre token
generation trigger is told them. API sign-ins and tokens minted before
this change have no such field and refresh as before. A refresh keeps the
sign-in's auth_time and origin_jti. InitiateAuth REFRESH_TOKEN_AUTH and
GetTokensFromRefreshToken mint the same tokens as the token endpoint.

As on AWS, a refresh of a grant holding a scope the client no longer
allows is refused rather than narrowed: invalid_grant on the token
endpoint, and NotAuthorizedException "Client is not allowed to request
these scopes" on both APIs. The refresh token is parsed from both ends,
so a username holding a pipe refreshes too.

GetTokensFromRefreshToken and InitiateAuth REFRESH_TOKEN_AUTH now refuse a
refresh token issued to another client with NotAuthorizedException
"Refresh Token has different Client".
2026-10-12 16:34:25 -04:00
outofplaceandPriamo 5092713a6e feat(cognito): support passkeys (WebAuthn) registration and sign-in (#5102)
* feat(cognito): register passkeys and sign in with WEB_AUTHN

* test(cognito): cover passkeys with the Java SDK

* docs(cognito): document passkey registration and sign-in

* fix(cognito): check passkey counters under the user lock and tighten passkey origins

* fix(cognito): turn passkey MFA on per user and page passkeys with a cursor

* fix(cognito): verify passkeys without webauthn4j and gate passkey MFA on tier

Drops the webauthn4j dependency and its native-image entries. Cognito
recognizes only ES256 and RS256 passkeys and does not enforce
attestation, so jackson-dataformat-cbor decodes the attestation object,
the authenticator data and the COSE key, and java.security checks the
signature. The attestation statement is no longer verified.

The helpers the verifier needs live in core.common, and the existing
copies across main and test code now call them:
- PublicKeys builds a public key from its raw components, for the JWT
  verifiers of API Gateway and Verified Permissions, SshPublicKeys, and
  the CloudFront and SES curve lookups.
- Digests.sha256 and Digests.sha256Hex replace every one-shot SHA-256
  digest and the private hex helpers built on one, including the two
  public sha256Hex methods on SigV4RequestValidator; incremental and
  streaming digests keep MessageDigest.
- Base64Url.encode, for bytes or the UTF-8 bytes of a string, replaces
  every unpadded base64url encode and the private helpers wrapping it.
- DomainNames.isWithin replaces the same-domain-or-subdomain check in
  SES, ACM, Route 53, the embedded DNS server, the TLS certificate
  manager and the Cognito message dispatcher.
Every replacement produces the same bytes as the code it replaces.

Turning passkey MFA on now also needs a pool in the Essentials tier or
higher, and in an optional-MFA pool a user with software-token MFA keeps
WEB_AUTHN when passkey MFA is on, as the AWS MFA table describes.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-10-12 15:27:36 -04:00
Mario Toffia 1a0afce7ec feat(cognito): serve the OAuth token revocation endpoint (#4936)
POST /cognito-idp/oauth2/revoke, and /oauth2/revoke on a custom domain,
revoke a refresh token through RevokeToken and answer as AWS's revocation
endpoint does, as measured: 200 with no body for a revoked, already
revoked or invalid token; 400 invalid_request for a missing token or a
client with revocation disabled; 400 unsupported_token_type for an access
or ID token; and 401 invalid_client with WWW-Authenticate: Basic for
missing or bad client credentials, a client of another pool, or a token
issued to another client. Unlike the token endpoint, a client secret is
taken only from the Basic header.

On a custom domain, the Cognito filter now answers a path under /oauth2/
that Cognito does not serve with AWS's JSON 404, and a served path called
with another method with an empty 405, so neither reaches S3 as a key of a
bucket named cognito-idp.
2026-10-11 19:38:32 -04:00
danielxoi bcfb9c786c fix(cognito): surface sign-in denials with the exception classes Cognito uses (#5223)
* fix(cognito): surface sign-in denials with the exception classes Cognito uses

A disabled user was rejected with UserNotConfirmedException ("User is disabled");
Cognito returns NotAuthorizedException with "User is disabled.". A PreAuthentication
trigger that returned an error payload surfaced as NotAuthorizedException; Cognito
returns UserLambdaValidationException with "PreAuthentication failed with error
<errorMessage>.", the same mapping floci already applied to PreSignUp on
AdminCreateUser. PreSignUp on SignUp is aligned the same way (it reported
NotAuthorizedException "PreSignUp trigger denied signup: ...").

The five duplicated eligibility checks now share requireSignInEligible /
requireEnabled, and the three blocking triggers share blockingTriggerFailure.
Integration tests that pass against AWS failed on these two codes.

* test(cognito): cover trigger invocation failures and assert the SDK exception classes

PreAuthentication and PreSignUp now get cases for an uninvokable function
(UnexpectedLambdaException) and a malformed response
(InvalidLambdaResponseException). A new sdk-test-java compat test asserts
NotAuthorizedException for a disabled user and UserLambdaValidationException
for a PreAuthentication trigger that raises, through the AWS SDK v2 client.

* test(cognito): drop the em-dash from the compat test display name
2026-10-06 23:28:03 -04:00
outofplace a5db3975c4 feat(cognito): support TOTP MFA when MFA is optional (#5101)
* feat(cognito): store software-token MFA preferences and report MFA settings

* feat(cognito): challenge users with TOTP turned on when MFA is optional

* docs(cognito): document optional TOTP MFA and MFA preferences

* fix(cognito): report required TOTP and keep email-code sign-in for email MFA users

* docs(cognito): describe required TOTP reporting and the USER_AUTH choice
2026-10-06 17:33:00 -04:00
jwoa95 45f45e590e fix(cognito): send email from the pool's EmailConfiguration sender (#5150)
* fix(cognito): send email from the pool's EmailConfiguration sender

Cognito email always came from no-reply@verificationemail.com. It now
follows EmailConfigurationType: with DEVELOPER, From when set, otherwise
the SourceArn identity's address; with COGNITO_DEFAULT, the SourceArn
address. A domain identity takes its address from From. Without a
SourceArn, the default address is kept.

* test(cognito): read captured mail without the ?email= filter

* fix(cognito): send from the configured sender only when SES has verified it

A pool's EmailConfiguration sender is now used only when its SourceArn
names an SES identity in the pool's account that SES has verified in the
SourceArn Region (the pool's Region for a wildcard Region), and a From
that supplies the sender is one mailbox at that address or in that
domain. Anything else sends from no-reply@verificationemail.com and logs
a warning, so a pool can no longer send as an address its account has
not verified.

When From has a sender name, the bare address now goes in ReturnPath.
SES takes Source as the default return path, so the captured message's
ReturnPath, and the envelope sender handed to the SMTP relay, was
"Name <address>". The relay's mail client happened to strip the name
from MAIL FROM; the envelope no longer depends on that.

* style(cognito): use one parameterised message in the sender fallback log

* fix(cognito): accept subdomains of a domain identity and match email identities exactly

A verified SES domain covers its subdomains, so a From in one of them now sends instead of falling back. Email address identities are case sensitive, domain part included, so the From must equal the identity. The SourceArn must also be in the user pool's partition, not only its account.

* refactor(ses): keep one definition of a verified identity

SesService.isVerifiedIdentity now delegates to SesIdentityService.isIdentityVerified, made package-private, instead of repeating its check.
2026-10-06 13:51:51 -04:00
jwoa95 69b4d17c67 fix(cognito): run the PreSignUp trigger on AdminCreateUser (#5149)
* fix(cognito): run the PreSignUp trigger on AdminCreateUser

AWS invokes the pre sign-up trigger when AdminCreateUser creates a user,
with triggerSource PreSignUp_AdminCreateUser, the request's ValidationData
and ClientMetadata, and ignores the response's autoConfirmUser,
autoVerifyEmail and autoVerifyPhone. A trigger error refuses the user.

The trigger runs before anything is stored, so a refused ForceAliasCreation
request no longer moves the alias off the existing user.

* fix(cognito): invoke PreSignUp outside the user lock on AdminCreateUser

AdminCreateUser held the lock stripe of the requested username while
the pre sign-up trigger ran. A function that called back into the pool
for an identifier on the same stripe, such as AdminCreateUser for the
same username, waited for that lock until the invocation timed out.

The trigger now runs with no lock held. A taken username or alias is
still refused before the trigger is invoked, and the checks run again
under the lock once it accepts, so a user created while the trigger ran
still fails the request with UsernameExistsException.

With ForceAliasCreation, the alias holder was read before the trigger
and written back after it, which could undo a change made to the holder
in the meantime or restore a deleted holder. The holder is now looked up
under the lock after the trigger, just before its alias is moved.

* fix(cognito): run PreSignUp once per in-flight AdminCreateUser username

With the pre sign-up trigger running outside the user lock, two
overlapping AdminCreateUser requests for the same free username could
both pass the existence check and both invoke the trigger. The later
one was then refused under the lock after its function had already run,
or failed with the function's own error instead of
UsernameExistsException.

AdminCreateUser now claims the username before checking it and gives
the claim up once the user is stored or the request fails. An
overlapping request for the same username, including one the function
makes for the username it was given, is refused with
UsernameExistsException before it invokes the trigger.
2026-10-06 08:18:14 -04:00
iam-ssrivastav 8ea033d9fd feat(cognito): implement DeleteUser self-service API action (#4493) 2026-10-04 20:09:58 -04:00
jwoa95 45b7be9362 feat(cognito): offer an email code on managed login (#4765)
* feat(cognito): offer an email code on managed login

Managed login could not sign in a user of a passwordless pool: /login was
a username and password form only. When the pool's SignInPolicy allows
EMAIL_OTP and the client allows USER_AUTH, the page now asks for the
username first, offers the factors that user has (PASSWORD and
EMAIL_OTP), and for EMAIL_OTP sends a code through the USER_AUTH
EMAIL_OTP challenge, so it arrives in Floci's SES. A correct code signs
the user in as the password does: a session cookie and a redirect to the
callback with code and state, redeemed at /oauth2/token with PKCE. The
USER_AUTH session travels in a hidden field. A wrong code shows the code
field again and keeps the session for another try. An unknown user is
asked for a code like anyone else, but nothing is sent and no code signs
them in. Pools and clients without choice-based sign-in keep the
password form unchanged.

USER_AUTH ignored the sign-in policy for existing users, so a pool that
allowed only EMAIL_OTP still offered PASSWORD and PASSWORD_SRP. The
available challenges are now narrowed to AllowedFirstAuthFactors, whose
PASSWORD covers both password challenges, and a PREFERRED_CHALLENGE or
SELECT_CHALLENGE answer outside it is refused as an unavailable one is.
A pool with no sign-in policy is not narrowed.

/oauth2/authorize now carries login_hint to /login, on Floci's host and
on a custom domain, and /login fills the username field with it, as AWS
documents.

Refs #4759

* fix(cognito): harden the managed login email-code step

The step after the username told accounts apart. The page looked each
user up, so a user with one factor skipped the choice others got, a user
who could not sign in was told why, and the USER_AUTH session in the code
form named the user it was for. The page now offers the policy's factors
to every username, and a user who is unknown, cannot sign in, or has no
verified email gets the same code field, with no message sent. Why a user
cannot sign in shows only after a correct code. Asking again within the
resend limit shows the code field for the code already sent, instead of
an error only a real user could get. USER_AUTH session tokens no longer
carry the username.

The same code could sign in twice: requests answering one session with
its code at once could all pass the check before any removed the
session. The code is now checked and the session spent under the lock
that every read and removal of a session takes, RespondToAuthChallenge's
included, so one request signs in and the others find the session spent.

A correct code spends the session, so a failure after it, such as a
failing PostAuthentication trigger or a user who cannot sign in, now goes
back to the username step with the reason, instead of showing a code
field that can no longer work.

Refs #4759

* fix(cognito): redeem an email or SMS sign-in code once across sessions

Every live EMAIL_OTP or SMS_OTP session of a user takes the user's one
sign-in code, and the code store reads a code before it deletes it. Two
of a user's sessions answered with the code at once through
RespondToAuthChallenge could both pass the check and both sign in. Such
a second session is easier to come by now that asking the sign-in page
for a code again within the resend limit opens one. RespondToAuthChallenge
now checks the code under the lock the sign-in page checks it under, so
one session signs in and the other gets CodeMismatchException. Nothing
held under that lock calls a Lambda trigger.

Refs #4759

* fix(cognito): redeem verification codes under a per-user lock

Redeeming an email or SMS sign-in code held the lock shared by every
USER_AUTH session while the code store read and wrote the code, which in
persistent storage mode is a disk write, so one user's slow redemption
held up other users' sign-ins. That lock now guards the session maps
alone.

The code store now redeems a code once by itself: consume() takes a lock
striped by the code's pool, user and purpose, and calls nothing but the
store under it, so no trigger runs and no other lock is taken there.
Sign-up, password reset and attribute verification codes gain the same:
each is redeemed once and every wrong attempt counts, where concurrent
requests could redeem one twice or undercount its attempts before. Of
several requests answering a user's sessions with one code at once, one
signs in and the rest get CodeMismatchException. The sign-in page looks
its session up, redeems the code, then removes the session, and still
signs in if RespondToAuthChallenge spent the session meanwhile, since
only one of them can have redeemed the code.

Refs #4759

* fix(cognito): issue and invalidate verification codes in turn with redemption

Only consume() took the code store's per-key lock, so redeeming the old
code could read it, let a resend write the new one, and then delete the
new one, leaving the user a code that never works. issue() and the two
invalidations now take the same stripe, so each of them and consume()
see the code as the one before left it.

Refs #4759

* fix(cognito): offer the choice for a preferred challenge the user cannot take

USER_AUTH refused a PREFERRED_CHALLENGE that the sign-in policy leaves
out or the user has not set up with InvalidParameterException. AWS
answers it as it answers InitiateAuth without one: SELECT_CHALLENGE and
the challenges the user can take, which is what clients expect on the
main sign-in path. Floci now does the same, and refuses only a name
Cognito does not support, with AWS's message listing the ones it does.
An unknown user whose client prevents user existence errors gets the
same answer as a known user: the preferred challenge when the policy
allows it, and the choice when it does not. A SELECT_CHALLENGE answer
outside the choice is still refused.

Refs #4759

* fix(cognito): default a pool's sign-in policy to PASSWORD alone

AWS's DescribeUserPool reports a SignInPolicy of
{"AllowedFirstAuthFactors": ["PASSWORD"]} for a pool created without one,
on any tier, and USER_AUTH offers that pool's users password challenges
alone. Floci stored no policy and did not narrow such a pool, so it
offered EMAIL_OTP and SMS_OTP that AWS would not. CreateUserPool now
stores the default, UpdateUserPool keeps the policy when the request
omits Policies and puts the default back when its Policies has no
SignInPolicy, and a pool persisted without one is treated as PASSWORD
alone.

Refs #4759

* test(cognito): pass login_hint in the scope tests from main
2026-10-01 16:40:31 -04:00
jwoa95 f1d718cae2 fix(cognito): scope OAuth tokens to the requested scopes (#4771)
* fix(cognito): scope OAuth tokens to the requested scopes

* fix(cognito): require the admin scope on access-token operations

* fix(cognito): bind an authorization code to the scopes granted at authorize

* fix(cognito): keep the provider's requested scopes apart from Cognito's grant
2026-10-01 13:54:01 -04:00
jwoa95 31038ee2a4 feat(cognito): add GetUserAuthFactors (#4764)
* feat(cognito): add GetUserAuthFactors

* fix(cognito): refuse access tokens with no scope claim where a scope is required

* fix(cognito): use AWS's message for a missing access-token scope
2026-09-30 21:45:10 -05:00
Aniket Shukla 45b00779b7 fix(cognito): fail authentication when token triggers fail (#4727)
* fix(cognito): fail authentication when token triggers fail

* fix(cognito): reject empty Lambda trigger responses
2026-09-30 13:29:20 -04:00
XuJian 433893d298 feat(cognito): support software-token MFA setup and challenges (#4620)
* feat(cognito): require TOTP MFA after primary authentication

* test(cognito): verify TOTP MFA with Java SDK

* fix(cognito): reject disabled users completing TOTP challenges

* fix(cognito): preserve new-password trigger through TOTP

* fix(cognito): gate custom password auth with required MFA

* fix(cognito): limit failed TOTP verification attempts

* fix(cognito): report code mismatch for invalid TOTP setup
2026-09-29 19:43:09 -05:00
vladislav doster e51119679c docs: correct spelling (#4491)
Signed-off-by: Vladislav Doster <mvdoster@gmail.com>
2026-09-28 17:51:19 -05:00
Aniket Shukla c0cb49facc fix(cognito): persist app client AuthSessionValidity (#4481)
* fix(cognito): persist app client AuthSessionValidity

* test(cognito): cover session validity through the SDK

* fix(cognito): align session validity validation with AWS errors
2026-09-26 16:47:30 -05:00
Emmanuel Olowosulu b4d8483348 fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code (#4438)
* fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code

Managed login and federated sign-in both mint their tokens at
POST /oauth2/token, which called generateAuthResult directly and so never
invoked the pre token generation trigger. A pool whose trigger adds claims
got them from InitiateAuth but not from a hosted-UI sign-in, so an
application that authorizes on a custom claim rejected every token a browser
obtained while the same user's tokens from InitiateAuth were accepted.

Redemption now mints through a hosted-auth path that fires the trigger with
triggerSource TokenGeneration_HostedAuth, which is what AWS uses for a
sign-in through the hosted UI, for a pool's own users and federated users
alike. The authorization request's nonce is applied after the trigger's
claims so a trigger cannot displace it; AWS likewise does not let this
trigger override nonce.

* fix(cognito): pass the requested scopes to the hosted-auth trigger

Review feedback. The authorization code stores the scopes the authorize
request asked for, but the hosted-auth trigger call sent an empty list, so a
V2 lambda that branches on requested scopes had nothing to branch on. Thread
the code's scopes through to the trigger event. The other call sites keep
sending an empty list, which is what their non-OAuth flows carry.

Also replace the em-dashes in the new comments, per AGENTS.md.

* fix(cognito): narrow the trigger's scopes to the client's allowed set

Review feedback. An authorization request names its own scopes and nothing
checks them against the client's AllowedOAuthScopes when the code is issued,
so a stored code can carry a scope the client may not use. Passing those
straight through meant a V2 trigger could grant claims, or add scopes, from a
scope the client was never entitled to request.

The hosted-auth path now narrows the requested scopes to the client's allowed
set before the trigger is told about them, dropping the rest the way AWS
ignores a scope that is not associated with the client. The narrowing lives in
the service method rather than at the call site, so every caller gets it.

* style(cognito): brace the new conditionals

Review feedback. AGENTS.md requires braces in all conditionals, and the four
early returns in the claims-merge helpers omitted them.
2026-09-26 16:43:52 -05:00
Niels Kootstra 8b9f441bb4 fix(cognito): expire auth challenge sessions (#4417)
* fix(cognito): expire auth challenge sessions

InitiateAuth and RespondToAuthChallenge session tokens for SRP, custom
auth, and USER_AUTH never expired, so an abandoned challenge session
lingered in memory forever and could still be completed long after
AWS would have rejected it. Track when each session was issued and
reject expired ones with the NotAuthorizedException Cognito returns
in that case, purging expired entries whenever a new one is created.

AWS defaults AuthSessionValidity to 3 minutes (configurable 3-15 via
CreateUserPoolClient); UserPoolClient does not yet store a per-client
override, so every client uses the 3 minute default for now.

* fix(cognito): stamp custom auth tokens when they are issued

A CUSTOM_AUTH session's issue time was recorded before the
DefineAuthChallenge and CreateAuthChallenge triggers ran, so a slow
trigger shortened the session handed to the client. The issue time
also lived on the flow state shared across rounds, so minting the next
round's token refreshed the old token while it was still in the map.

Each custom auth token now carries its own issue time, stamped when it
is stored, and every issuance path (including both continuations)
purges expired tokens first.

* style(cognito): brace the custom auth session lookup

* test(cognito): use the shared MutableClock

* docs(cognito): document auth challenge session expiry

* chore: rerun CI

* chore: rerun CI
2026-09-26 16:10:19 -05:00
jwoa95 eb039eb71c feat(cognito): serve managed login for native users with PKCE (#4238)
GET /oauth2/authorize with identity_provider=COGNITO, or none, now signs
in the pool's own users through managed login instead of requiring a
federated provider. It redirects to a plain sign-in form at
/cognito-idp/login (/login on a custom domain), which checks the
password as USER_PASSWORD_AUTH does, sets a pool-scoped `cognito`
session cookie and redirects to the callback with code and state. A
browser with a live session skips the form.

/oauth2/token enforces PKCE (S256 only, as on AWS) when the
authorization request sent a code_challenge, for managed login and
federated sign-in alike, and refuses a code_verifier for a code issued
without one (RFC 9700). The ID token carries the request's nonce.

/cognito-idp/logout (/logout on a custom domain) ends the session and
redirects to a registered LogoutURL, or back to the sign-in form for
the redirect_uri form of the request. Discovery advertises
code_challenge_methods_supported.

Closes #4218
2026-09-23 16:35:35 -04:00
Priamo Germosen 06007deea8 fix(cognito): default ExplicitAuthFlows to refresh, SRP and custom auth (#4081)
A user pool client created without ExplicitAuthFlows was treated as allowing every auth flow, where AWS defaults such a client to ALLOW_REFRESH_TOKEN_AUTH, ALLOW_USER_SRP_AUTH and ALLOW_CUSTOM_AUTH. USER_PASSWORD_AUTH against a no-list client succeeded on Floci and is refused on AWS.

Apply that default at auth time, in the existing gate added by #3974. CreateUserPoolClient, UpdateUserPoolClient and DescribeUserPoolClient keep storing and returning exactly what was normalized, empty when unset, matching AWS: Terraform's Cognito acceptance tests confirm the empty read-back for both an omitted list and an explicit empty one, and materialising the default into storage would fail Terraform apply with an inconsistent-result error.

Tests and compatibility fixtures that created a no-list client and then signed in with a flow outside the default now enable that flow on their client.
2026-09-22 07:41:58 -05:00
Matheus André db9bd692cb docs(cognito): drop ADMIN_USER_SRP_AUTH from the supported AuthFlow list (#4028)
The value does not exist in AWS: botocore's AuthFlowType enum has no
ADMIN_USER_SRP_AUTH member, so no SDK can send it. Advertising it invites
templates and client calls that real AWS rejects. The case label in
CognitoAuthFlowHandler stays as tolerance.

Closes #3996
2026-09-21 08:45:38 -04:00
Priamo Germosen a12bf8c96c feat(cognito): enforce app client ExplicitAuthFlows in InitiateAuth and AdminInitiateAuth (#3974)
ExplicitAuthFlows was stored but never checked, so a client that only allowed SRP still accepted USER_PASSWORD_AUTH. When a client lists flows, reject any flow it does not enable with InvalidParameterException. Legacy values (USER_PASSWORD_AUTH, ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY) are honored, and clients created without a list stay ungated.

The Java compatibility test signed in with ADMIN_USER_PASSWORD_AUTH on a client that never enabled it; add ALLOW_ADMIN_USER_PASSWORD_AUTH to that client.
2026-09-20 21:04:55 -05:00
Priamo Germosen 2d56d85e9e fix(cognito): accept USER_SRP_AUTH in AdminInitiateAuth (#3973)
AdminInitiateAuth documents USER_SRP_AUTH as a valid AuthFlow, but only the ADMIN_USER_SRP_AUTH spelling, which is not an AuthFlowType value, was mapped. Accept the SDK spelling alongside it.
2026-09-20 16:56:58 -04:00
Priamo Germosen 803d0ed0ed feat(cognito): support the USER_AUTH choice-based auth flow (#3930)
Implements InitiateAuth/AdminInitiateAuth AuthFlow=USER_AUTH (#3926):
USERNAME plus optional PREFERRED_CHALLENGE, offering PASSWORD,
PASSWORD_SRP, EMAIL_OTP and SMS_OTP depending on what the user has
(password hash, SRP verifier, verified email, verified phone). With
no PREFERRED_CHALLENGE, the response carries AvailableChallenges and
ChallengeName=SELECT_CHALLENGE; with one, it goes straight to that
challenge. RespondToAuthChallenge handles SELECT_CHALLENGE (ANSWER
names the chosen factor, and may already carry that factor's own
answer to complete in one round trip), PASSWORD, PASSWORD_SRP, and
EMAIL_OTP/SMS_OTP.

PASSWORD and PASSWORD_SRP reuse authenticateWithPassword and
handleUserSrpAuth unchanged rather than reimplementing verification:
a USER_AUTH client responding with PASSWORD/SRP_A needs exactly the
same checks those flows already perform, so PASSWORD_SRP hands off to
the existing PASSWORD_VERIFIER challenge with zero new SRP logic.
EMAIL_OTP/SMS_OTP reuse the existing VerificationCodeService/
CognitoMessageDispatcher pair already used for SignUp/ForgotPassword
codes, adding EMAIL_OTP/SMS_OTP as new VerificationCode.Purpose
values distinct from SMS_MFA so a sign-in code can't be replayed
against another purpose's consume() call.

Also gates USER_AUTH on the pool's tier: AWS requires Essentials or
higher, and UserPool.userPoolTier already models this (defaulting to
ESSENTIALS), so a LITE-tier pool is rejected. SMS_OTP uses
SmsAuthenticationMessage, the template AWS documents for "SMS OTP and
MFA authentication" (CreateUserPool docs), not the signup/
verification template.

Security and correctness fixes found in review:
- handleUserAuth now validates SECRET_HASH before looking up the user
  or issuing a challenge, closing a hole where a caller with no
  secret could trigger a real OTP send and read the masked
  destination without proving it holds the client secret.
- issueSignInOtp now maps VerificationCodeException through
  mapVerificationCodeException (so a rate-limited retry surfaces as
  LimitExceededException, not a generic CodeDeliveryFailureException
  that hid the real cause), and invalidates the just-issued code
  before reporting a real dispatch failure, so the rate limiter
  doesn't lock out a retry for a code the user never received,
  matching signUp's existing rollback pattern.

Deliberately not implemented, tracked as follow-ups:
- WEB_AUTHN (passkeys): a much bigger piece per the issue's own
  scoping note, no credential storage/ceremony exists in floci yet.
- The Session from ConfirmSignUp accepted as a first-factor shortcut:
  needs ConfirmSignUp to start minting a redeemable session, a
  separate mechanism from the challenge flow this PR adds.
- Pool-level sign-in policy (AllowedFirstAuthFactors): floci does not
  model per-pool factor restrictions at all today; availability here
  is purely per-user (does the user have this factor configured).
- Session is not looked up on RespondToAuthChallenge: each handler
  independently reverifies its own factor from the request body, the
  same shape the existing NEW_PASSWORD_REQUIRED handler already uses,
  so there is no bypass, just an opaque correlation token rather than
  server-held state.

Verified against botocore's cognito-idp service-2.json (AuthFlowType,
ChallengeNameType, AvailableChallengeListType, the AuthParameters
documentation for USER_AUTH) and the real InitiateAuth/CreateUserPool
API reference pages, including InitiateAuth's worked examples and
CreateUserPool's SmsAuthenticationMessage description.
2026-09-20 09:11:01 -05:00
Priamo Germosen 61f67cc834 fix(cognito): reject unrecognized AuthFlow instead of issuing tokens (#3923)
The default arm of InitiateAuth and AdminInitiateAuth looked the user up by name and issued signed tokens for any AuthFlow value it did not recognize, with no credential check. Reject those values with InvalidParameterException. ADMIN_NO_SRP_AUTH is a valid AdminInitiateAuth flow that previously only worked through that arm, so it now goes through password authentication.
2026-09-19 19:38:40 -05:00
David 1e8485830c fix(cognito): refuse DeleteUserPool while deletion protection is active (#3961)
DeletionProtection was stored and round-tripped but never read on the
delete path, so a protected pool was deleted like any other and a
CloudFormation DeleteStack owning one succeeded. AWS refuses with
InvalidParameterException until UpdateUserPool switches the flag to
INACTIVE, and the stack reports DELETE_FAILED with that reason.

The check reads the pool store directly: describeUserPool would turn a
delete of a missing id into ResourceNotFoundException (a separate
divergence) and generate signing keys as a side effect.

Closes #3948
2026-09-19 19:53:48 -04:00
Vũ Thế Huy f004aeaad5 feat(cognito): implement federated sign-in (#3748)
* feat(cognito): add federation transaction stores

* fix(cognito): atomically consume federation state

* feat(cognito): support OIDC provider exchange

* fix(cognito): validate OIDC federation providers

* fix(cognito): validate OIDC endpoint schemes

* feat(cognito): add federated oauth routes

* fix(cognito): preserve oauth state and codes

* feat(cognito): implement federated sign-in coverage

* chore: remove internal task report

* fix(cognito): use Cognito IdP callback for federation

* fix(cognito): use provider callback for token exchange
2026-09-17 09:00:11 -04:00
Daniel ZwickerandPriamo Germosen a03c4d6160 feat(cognito): support pending user attribute verification (#2531)
* feat(cognito): support pending attribute verification

* fix(cognito): omit UserAttributeUpdateSettings when a pool never configured it

DescribeUserPool/CreateUserPool/UpdateUserPool always serialized
UserAttributeUpdateSettings as an empty object for pools that never set it,
where AWS omits absent optional members entirely. UserPoolAddOns right above
it already handles this correctly (an unconfigured pool omits the key rather
than returning {} or null, confirmed by Terraform re-planning the block into
and out of existence); UserAttributeUpdateSettings now follows the same
pattern.

* test(cognito): replace var with explicit AWS SDK response types

AGENTS.md's Types and names rule bans var in local declarations; the compat
test used it for four locals whose concrete AWS SDK type is the thing under
review here (CodeDeliveryDetailsType, UpdateUserAttributesResponse).

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-09-14 11:50:16 -04:00
Daniel ZwickerandPriamo Germosen 36c3ee4e22 feat(cognito): implement VerifyUserAttribute (#2018)
* feat(cognito): implement VerifyUserAttribute

* fix(cognito): align attribute verification with AWS

* fix(cognito): require access-token scope on VerifyUserAttribute

verifyUserAttribute() extracted username/pool/jti from the caller's token
but never checked token_use or scope, so a valid ID token could reach the
same code-consuming, attribute-mutating path as an access token. AWS
requires an access token carrying the aws.cognito.signin.user.admin scope
for this operation (API_VerifyUserAttribute.html).

Adds a token_use check (unconditional) and a scope check that only rejects
a token when it explicitly carries a scope list missing the required
scope. Most access tokens this simulator issues carry no scope claim at
all (scopes are only modeled through the V2 Pre-Token-Generation Lambda
override), so treating an absent claim as unrestricted keeps every normal
login flow working, while an access token with an explicit, non-conforming
scope list is now rejected.

Adds unit coverage for all three cases (ID token rejected, access token
missing the scope rejected, access token with the scope accepted) plus a
wire-level regression for the ID-token case.

* fix(cognito): scope consumed-code tombstone to attribute verification

VerificationCodeService.consume() retained a consumed-code tombstone for
every purpose, so a reused code answers ExpiredCodeException instead of
the original CodeMismatchException. That behavior was validated against a
real Cognito pool for VerifyUserAttribute, but the service is shared with
ConfirmSignUp (SIGNUP_CONFIRMATION) and ConfirmForgotPassword
(PASSWORD_RESET), so the same change silently altered their reused-code
error too, without the same validation.

Scopes the tombstone to EMAIL_ATTRIBUTE_VERIFICATION and
PHONE_ATTRIBUTE_VERIFICATION only. SIGNUP_CONFIRMATION and PASSWORD_RESET
go back to deleting on consume, restoring their original, previously
validated NOT_FOUND/CodeMismatchException behavior on reuse.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-09-14 11:05:25 -04:00
Brian Taylor 2a4ca61baf fix(cognito): delete a user pool's records with the pool (#2949)
* fix(cognito): delete a user pool's app clients, revocations and codes

#3419 took users and resource servers out with the pool, closing the half of
#2864 that was reported. Three more record types are the same defect and were
left behind: app clients, revoked token records and outstanding verification
codes.

On AWS a pool id is never reused, so nothing can inherit an orphan. Here
floci:override-id makes ids caller-chosen and therefore reusable, and a pool
recreated on a pinned id picks up whatever the deleted pool left.

Reproduced by pinning us-east-1_orphanprobe1, populating it, deleting the pool
and recreating it on the same id. The client leak is the serious one: the
deleted pool's client id kept resolving against the new pool, carrying a secret
the new pool's caller never saw.

  clients: ["c1"]
  describe-user-pool-client --client-id c1a93e3fc698451d96ed406adb -> c1

Clients are keyed by client id alone, so they are found by their userPoolId
field rather than a key prefix. Revoked tokens and verification codes have
their keys collected before deleting so the backing key set is not modified
while it is being iterated.

confirmSignUpNamesDeletedUserPoolInResourceNotFoundMessage, added by #2936,
built its orphaned client by deleting the client's pool, which this cascade
now prevents. It is renamed and reaches the same defensive path by dropping the
pool record alone, and a second case pins the new behaviour: a client id from a
deleted pool is gone with it.

Refs #2864

* fix(cognito): bound the delete cascade by pool ownership, not key prefix

floci:override-id makes pool ids caller-chosen, and validateOverrideId
permits a colon. Two live pools can therefore be named so that one id
plus the key separator is a prefix of the other, and the revoked-token
and verification-code cascades deleted by the matched key, so deleting
the shorter pool erased the longer one's records. For revoked tokens
that reinstated tokens the surviving pool had revoked.

Both records carry their own userPoolId, so ownership is now settled by
that field rather than by the key prefix. The other cascades reconstruct
the key from the pool id being deleted and so never reached across a
boundary; they are left alone.

A jti can itself contain a colon (global revocations use
global:{username}), so bounding the prefix by the separator would not
have been sufficient either.
2026-09-12 23:39:32 -04:00
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
Mario Toffia b4d80a5596 feat(cognito): route custom domains by Host (#3095)
* feat(cognito): route /oauth2 requests on a custom domain by Host

CognitoCustomDomainFilter (PreMatching, priority 12) resolves the request
Host against the domain store and rewrites /oauth2/token and
/oauth2/userInfo onto the /cognito-idp/oauth2 handlers. The pool the domain
belongs to travels in a request property, so the controllers pin exactly the
pool the filter matched and a caller cannot supply it. The token endpoint
refuses a client of another pool with invalid_client and userInfo refuses a
token of another pool with invalid_token, as AWS does. The lookups scan
every account because an OAuth call carries no SigV4 account.

The discovery document advertises https://<domain>/oauth2/... for a pool
with a custom domain. S3VirtualHostFilter skips a request the Cognito
filter routed, the way it already skips CloudFront ones, since a custom
domain under a Floci suffix looks like a bucket host.

* docs(cognito): custom domain routing

* fix(cognito): run custom domain requests in the domain's account and keep domain names unique

A request on a custom domain carries no AWS credential, so AccountContextFilter
put it in the default account and the client, pool and user lookups missed a
domain created under another account. The Cognito filter now pins the domain's
account in a request property that AccountContextFilter honours before header
resolution. Domain creation checks the name across every account, as AWS's
single domain namespace does, and a name two accounts already hold from older
data is not routed.

Also adds the OAuth contract tests for the routed endpoints (client_secret_post,
error codes, token claims, userInfo refusals, unserved paths, prefix domains,
interleaved requests on several threads) in a second integration class.

* fix(cognito): make the domain uniqueness check and write one step

Two accounts creating the same custom domain at once both passed the
cross-account scan and wrote under their own account-prefixed keys, leaving a
name that routing then refused as ambiguous. The check and the write now run
under one lock, the way identity-provider mutations already do. A 16-thread
unit race and a two-account integration race pin exactly one owner.
2026-09-05 16:56:01 -04:00
Mario Toffia d771783afb feat(cognito): check the custom domain certificate in ACM and mark it in use (#3035)
* feat(cognito): require an issued ACM certificate for a custom domain and track it as in use

CreateUserPoolDomain and UpdateUserPoolDomain stored any CertificateArn
as given. The certificate must now exist in ACM, in us-east-1, with
status ISSUED, as AWS requires; anything else is rejected with AWS's
InvalidParameterException message.

While a domain uses a certificate, ACM lists the domain's CloudFront
distribution under InUseBy and DeleteCertificate refuses with
ResourceInUseException. Deleting the domain, or moving it to another
certificate, releases the old one. AcmService gains addInUseBy and
removeInUseBy for this; the refusal on delete already existed.

DeleteStack deleted resources in reverse insertion order, so a
certificate added by a later update was deleted before the domain that
still used it and the stack ended in DELETE_FAILED. Resources are now
deleted in reverse dependency order from the stack's template, as on
AWS, with insertion order as the fallback when the template cannot be
read.

* feat(cognito): register the certificate before storing the domain and require a certificate ARN

Review follow-ups:

- The domain was stored before it was registered on its certificate,
  so a certificate deleted between the check and the registration left
  a stored domain that ACM did not protect. Registration now comes
  first on create, and a changed certificate is checked and registered
  before an update touches the domain; the old certificate is released
  after the store. A certificate that disappears in that window fails
  with the same InvalidParameterException as a missing one.
- The ARN check accepted any ACM resource. It now also requires the
  resource to be certificate/<id>, before ACM is asked.
2026-09-05 10:06:53 -04:00
Mario Toffia f3c251ef20 feat(cognito): provision AWS::Cognito::UserPoolDomain (#3005)
* feat(cognito): provision AWS::Cognito::UserPoolDomain

The type was a stub: the stack turned green, but Fn::GetAtt
CloudFrontDistribution resolved to the literal
LogicalId.CloudFrontDistribution, so a Route 53 alias record for a
custom domain pointed at that text.

CognitoCfnProvisioner creates the domain through the existing
CreateUserPoolDomain. Ref is the domain name and CloudFrontDistribution
is the CloudFront name DescribeUserPoolDomain reports. A changed Domain
or UserPoolId replaces the domain; any other change is applied in place
through the new UpdateUserPoolDomain operation, so the distribution a
DNS alias points at survives a certificate change, as on AWS. Delete
uses the pool id recorded at create time and tolerates an already
deleted domain.

UpdateUserPoolDomain is also exposed on the Cognito API, with the same
response shape as CreateUserPoolDomain.

* feat(cognito): treat null domain settings as absent and pin the same-name replacement failure

Review follow-ups for AWS::Cognito::UserPoolDomain:

- A JSON null inside CustomDomainConfig was copied as the text "null",
  which would have passed for a certificate ARN. Null values are now
  skipped, so the service rejects the missing ARN as it should.
- ManagedLoginVersion on CreateUserPoolDomain and UpdateUserPoolDomain
  treated an explicit null as 0, overwriting the stored version. Null
  now counts as omitted, and a value of another JSON type is a
  SerializationException, as on AWS.
- Moving an unchanged domain to another pool fails on the create,
  because domain names are unique across pools and the replacement is
  created before the original is deleted, exactly as on AWS. The unit
  test that mocked this path as a success is replaced by one that pins
  the failure and checks the original domain is left in place.

* test(cognito): cover domain replacement, prefix domains and SecurityPolicy updates

The stack test now also renames the domain through UpdateStack, asserting the old domain is gone and the new one has its own distribution, and a second stack proves a prefix domain resolves Fn::GetAtt CloudFrontDistribution to an empty string rather than the literal attribute name. The service test covers a SecurityPolicy change and that an omitted policy is kept. The in-place check reads ctx.reusesPriorEntity(domain), as the sibling provisioners do.

* test(cognito): provision the stack test's certificate through AWS::CertificateManager::Certificate

With the ACM provisioner merged, the stack test now declares the certificate as a resource and references it with Fn::GetAtt, the way CDK does. Rotating to a new certificate resource updates the domain in place and removes the old certificate once nothing references it. A wildcard name keeps a domain rename from replacing the certificate.
2026-09-04 00:55:19 -05:00
Brian Taylor 906717a510 feat(cognito): implement SetUserPoolMfaConfig (#2831)
* feat(cognito): implement SetUserPoolMfaConfig

The action was unrouted, so the dispatcher answered UnsupportedOperation
and any caller configuring pool MFA failed. GetUserPoolMfaConfig already
existed but reported only MfaConfiguration, so a software-token setting
could not round-trip even once it could be set.

SetUserPoolMfaConfig now stores the MFA mode and the software-token
setting, and both actions answer with the shape measured on the live
service: only configured factors appear, so SoftwareTokenMfaConfiguration
is omitted until it is set.

SMS, email and WebAuthn MFA are accepted and deliberately not stored —
Floci has no path to deliver those factors, and retaining the config
would claim a capability that does not exist.

* test(cognito): cover MFA configuration through the AWS SDK

The integration test drives the endpoint over raw HTTP, so nothing
exercised the new action through a real SDK client. Adds coverage for
the three cases that matter to a caller: an unconfigured pool reports
OFF with no software-token member, a set round-trips through Get, and an
invalid MfaConfiguration is rejected.

* fix(cognito): follow the measured SetUserPoolMfaConfig semantics

Three behaviours were taken from the API reference and turned out wrong
when measured against the live service:

  - an absent MfaConfiguration means OFF, not "leave the current mode
    alone", so a pool set to OPTIONAL is reset by a request that omits it
  - turning MFA off drops the factor configuration with it; the service
    answers OFF alone afterwards
  - sending a factor while the effective mode is OFF is rejected with
    "can't turn off MFA and configure an MFA together"

The enum in the validation message is also ordered [OPTIONAL, OFF, ON],
as the service emits it. Two tests asserted the previous guesses and
passed, which is how a guess becomes apparent evidence; both now pin the
measured behaviour.

* fix(cognito): apply the MFA factor rules to email and SMS, not just the software token

Review flagged that a request combining an effective OFF mode with
EmailMfaConfiguration or SmsMfaConfiguration was accepted, since only
SoftwareTokenMfaConfiguration was read. Measured against the live
service, and the finding holds for email and SMS but not for WebAuthn:

  - OFF + EmailMfaConfiguration is rejected with the same message as
    OFF + SoftwareTokenMfaConfiguration
  - OFF + WebAuthnConfiguration returns 200 and echoes the block back
  - the rule fires on the member being present, not on Enabled: OFF
    alongside SoftwareTokenMfaConfiguration{Enabled:false} is rejected

The same pass turned up the mirror rule, which was also missing: ON or
OPTIONAL with none of the three factors present is rejected with
"SMS MFA, Email MFA, or Software Token MFA must be enabled". Despite
that wording it is again presence, not value - ON alongside
SoftwareTokenMfaConfiguration{Enabled:false} is accepted - and WebAuthn
does not satisfy it, so it sits outside both rules in both directions.

One existing test set ON with no factor at all, which the live service
refuses; it now sends a factor.

* test(cognito): read the MFA config tests in their execution order

The methods were laid out 1, 2, 3, 4, 5, 8, 6, 10, 7, 9, 11, 12, 13, an
artifact of adding cases across three review rounds. The chain is stateful,
so a reader following the pool through it had to jump around the file.

Pure move: the methods are reordered to match their @Order values, no
annotation value and no test body is changed, so the execution order is
exactly what it was.

* chore(cognito): drop the em-dashes this branch introduced

AGENTS.md asks for none in any content. Seven had leaked into the MFA
prose: the docs table row, two service comments, the handler javadoc and
two in the test class. Replaced with colons and commas, no wording change
beyond the punctuation.

Pre-existing em-dashes elsewhere in these files are left alone.

* revert: "chore(cognito): drop the em-dashes this branch introduced"

This reverts commit d7a0ad10. The rule it cited does not exist: AGENTS.md
says nothing about em-dashes, and the repo uses them throughout, including
in CONTRIBUTING.md's own commit-type table and in the pull request template.
I asserted a house style that is not the house style, so the prose goes back
to how it read when you reviewed it.

Nothing in this PR's behaviour was affected either way. The @Order fix in
63086a30 is unrelated and stands.

* chore(cognito): drop the em-dashes this branch introduced

Reinstates d7a0ad10, which b4a283e3 reverted in error.

The rule is real: AGENTS.md line 333, under Documentation Style, "No
em-dashes anywhere, in any content. Use colons, commas, or periods." I
grepped this branch's copy of AGENTS.md rather than origin/main and found
nothing, so I concluded it did not exist. It was added in 10a70ba1 on
31 Aug, after this branch's merge base at b0fe8311, which is why the
branch's copy predates it.

Seven occurrences on six lines: the docs table row, two comments in
CognitoService, the handler javadoc and two in the test class. Punctuation
only, no wording change. Pre-existing em-dashes elsewhere in these files
are left alone, since the rule is about content this branch adds.
2026-09-03 00:16:01 -04:00
Aniket Shukla c30ca8fb5f fix(cognito): name missing user pools in errors (#2936)
* fix(cognito): name missing user pools in errors

* test(cognito): address missing pool review
2026-09-03 00:12:14 -04:00
Brian Taylor 0a3bc030f6 feat(cognito): implement identity provider configuration CRUD (#2858)
* feat(cognito): implement identity provider configuration CRUD

CreateIdentityProvider, DescribeIdentityProvider, ListIdentityProviders,
UpdateIdentityProvider and DeleteIdentityProvider were unsupported, so
infrastructure tooling could not manage a user pool's federated providers.

Stores provider configuration alongside the other user pool sub-resources and
matches the response and update semantics measured against the live API:

- IdpIdentifiers is echoed by create and update only when the request supplied
  the member, whatever the stored value; describe always returns it
- AttributeMapping defaults to username -> sub when the member is absent at
  create, while an explicitly empty map is stored as given
- members a request omits are preserved rather than cleared
- a duplicate provider name raises DuplicateProviderException
- ListIdentityProviders returns name/type/date summaries, never ProviderDetails

Federated sign-in itself is out of scope: Floci has no /oauth2/authorize or
/oauth2/idpresponse endpoint, so providers are stored configuration only.

* test(cognito): match identity provider exceptions on the SDK error name

`rejects.toThrow(/re/)` matches the error message, but the JS SDK maps the wire
`__type` onto `error.name` and puts the AWS text in `message`, so the duplicate
provider assertion never matched. Assert the name, and pin the enum text with
an explicit message matcher.

* fix(cognito): delete a pool's identity providers with the pool, and update a copy

Two review findings, both reproduced first.

DeleteUserPool left provider records behind. A pool recreated on a pinned id
(`floci:override-id`) then inherited the dead pool's providers, ProviderDetails
client_secret included. Pool deletion now removes them the way it already
removes groups.

UpdateIdentityProvider mutated the instance the store handed back, so two
concurrent updates could interleave into a state matching neither request. It
now writes a copy, which makes the losing update simply lose — what AWS does.

* fix(cognito): serialise identity provider mutations

UpdateIdentityProvider is a read-modify-write: it copies the stored provider,
applies only the members the request supplied and writes the whole record back.
Two overlapping updates copied the same base, so the later write restored the
other's omitted members to their stale values and silently dropped an update.

Live Cognito merges omitted members rather than clearing them, and applies that
merge atomically, so both updates survive there. One lock now guards every
mutating path, since create (check-then-put) and delete (check-then-act) carry
the same race, matching the existing identityLinkLock idiom.

The regression test runs two writers touching different optional members across
25 rounds; it fails on the first round with the lock reverted.

* fix(cognito): guard the pool deletion provider cascade with the same lock

DeleteUserPool clears a pool's identity providers outside identityProviderLock,
so a create or update interleaving with the cascade could reinstate a provider
for a pool that is going away. It now takes the same lock as the mutations it
races, closing the last unguarded path in that set.

* fix(cognito): recheck the pool under the lock when creating a provider

CreateIdentityProvider validated the pool before taking identityProviderLock and
never rechecked it, so a DeleteUserPool whose cascade ran in between left the
create writing a provider for a pool that no longer exists. It now reasserts the
pool inside the lock, immediately before the duplicate check and the write.

UpdateIdentityProvider needs no equivalent: the cascade deletes the provider, so
its own lookup throws ResourceNotFoundException. The outer validation stays where
it is to keep error ordering unchanged for ordinary single-request calls.
2026-09-02 12:00:26 -04:00
Brian Taylor 1e4e8b9ee8 feat(cognito): implement managed login branding (#2869)
* feat(cognito): implement managed login branding

CreateManagedLoginBranding, DescribeManagedLoginBranding,
DescribeManagedLoginBrandingByClient, UpdateManagedLoginBranding and
DeleteManagedLoginBranding were unsupported, so a config declaring
`aws_cognito_managed_login_branding` could not be applied against Floci.

A branding belongs to one app client and is stored on it. Behaviour matches what
the live API does:

- a second branding for the same client raises ManagedLoginBrandingExistsException
- ManagedLoginBrandingId must be a version 4 UUID, checked before the lookup
- Settings is omitted from the response when the caller supplied none, while
  Assets is always returned
- members an update omits are left unchanged

Settings is stored opaquely rather than validated against AWS's unpublished
schema, and ReturnMergedResources does not merge Cognito's default corpus.

Closes #2856

* fix(cognito): reject malformed CreateManagedLoginBranding members

Create coerced an absent UseCognitoProvidedValues to false and silently ignored a
wrongly typed Settings or Assets, so a malformed request produced persisted state.

Measured against AWS:

  neither UseCognitoProvidedValues nor Settings -> InvalidParameterException:
      useCognitoProvidedValues or settings should be specified (but not both)
  Assets of the wrong type   -> SerializationException: Unexpected field type
  UseCognitoProvidedValues of the wrong type -> accepted, not rejected

Create now enforces the first rule and type-checks Settings and Assets. A
non-boolean UseCognitoProvidedValues is still accepted, because AWS accepts it.

AWS answers a wrongly typed Settings with a 500 InternalErrorException; Floci
returns the same client error it returns for Assets rather than reproducing that,
and the divergence is documented.

* fix(cognito): check Assets elements before converting them

The Assets reader validated only the outer array, so a scalar element reached
Jackson's convertValue and escaped as a 500 InternalFailure. This is the same
class of bug as the LogConfigurations one, which I fixed in that reader without
applying it here.

AWS separates the two failures, and they differ from the LogConfigurations rules:

  [1, 2] / ["str"] -> SerializationException: Unexpected value type in payload
  [null]           -> InvalidParameterException: 1 validation error detected:
                      Value '[null]' at 'assets' failed to satisfy constraint:
                      Member must satisfy constraint: [Member must not be null]

A null element is rejected here, where LogConfigurations drops it.

* fix(cognito): match AWS branding source validation

A managed login branding request must select exactly one source of branding,
and the same rule governs create and update. Measured against Cognito in
ap-southeast-1:

  useCognitoProvidedValues  settings   result
  absent                    absent     InvalidParameterException
  true                      absent     accepted
  false                     absent     InvalidParameterException
  absent                    present    accepted
  true                      present    InvalidParameterException
  false                     present    accepted

Create rejected only the neither case, update validated nothing at all, so
naming both members and updating with no source both succeeded where the
service rejects them. Presence of the member is not the test: false selects no
source, which is why it needs settings alongside it.

Reading the flag had to move with it. AWS coerces a JSON string rather than
rejecting it, storing true for "true" and for "yes" and false for "false",
while Jackson maps every string except "true" to false. That turned "yes" into
a request selecting no source, so the coercion now follows the service.

* fix(cognito): reject malformed UseCognitoProvidedValues types

Jackson's asBoolean() maps a number, a JSON null, an object and an array all to
false, so a malformed flag alongside valid Settings passed source validation and
persisted as branding state that was never requested.

Measured against Cognito in ap-southeast-1: 1, null, {} and [] are each a
SerializationException, with or without Settings, while omitting the member is
accepted and stores false. Only booleans and strings are read now, strings still
coerced the way the service coerces them, and everything else raises
SerializationException the way SesController already does.

* fix(cognito): bound managed login branding assets at 40

Neither create nor update checked the documented 40-item maximum on Assets, so
an oversized request was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  create 40 assets            passes the bound, reaches the source rule
  create 41 assets            InvalidParameterException, length constraint
  create 41 + unknown client  the length error, not the missing client
  update 41 + malformed id    2 validation errors, the length one first
  update malformed id alone   1 validation error, before the pool lookup

The asset and branding-id checks now run before anything is looked up and
share one message, matching those last three rows. DescribeManagedLoginBranding
ran its pool lookup ahead of the branding-id check, which the fourth row shows
is the wrong way round, so it moved with them.

The length message embeds the request model's toString. The blob renders as the
decoded buffer, confirmed at three payload sizes; the decoder used here is the
lenient one so that building a rejection cannot itself fail.
2026-09-02 11:50:47 -04:00
Brian Taylor b8f1e22c74 feat(cognito): implement log delivery configuration (#2867)
* feat(cognito): implement log delivery configuration

SetLogDeliveryConfiguration and GetLogDeliveryConfiguration were unsupported, so a
config declaring `aws_cognito_log_delivery_configuration` could not be applied
against Floci.

The configuration is stored on the user pool and validated the way the live API
validates it:

- LogLevel accepts ERROR or INFO, EventSource accepts userNotification or
  userAuthEvents, both reported with AWS's 1-based member path
- every entry must name a CloudWatch, Firehose or S3 destination
- Set replaces the list rather than merging, so an empty list clears it
- Get always returns LogConfigurations, as [] when nothing is configured

Floci stores the configuration and delivers nothing: the destination is neither
written to nor required to exist, and the pricing-tier gate AWS applies to
userAuthEvents is not reproduced.

Closes #2855

* fix(cognito): reject a null LogConfigurations instead of clearing the configuration

SetLogDeliveryConfiguration treated an omitted, null or wrongly typed
LogConfigurations as an empty replacement, so a malformed request returned 200
and erased the pool's stored configuration.

AWS rejects all three. An omitted or null member fails validation, and a value of
the wrong JSON type fails deserialization:

  omitted / null -> InvalidParameterException: 1 validation error detected: Value
                    null at 'logConfigurations' failed to satisfy constraint:
                    Member must not be null
  wrong type     -> SerializationException: Expected list or null

Also drops two em-dashes from the docs, per AGENTS.md.

* fix(cognito): translate malformed LogConfigurations elements the way AWS does

A scalar inside the array reached Jackson's convertValue directly, so an
IllegalArgumentException escaped as a 500 InternalFailure instead of a client
error, and a null element would have failed on the validation loop.

AWS answers both without a 500:

  [1, 2] / ["a string"] -> SerializationException: Expected null
  [null]                -> 200, the null element is dropped

Elements are now checked before conversion: nulls are skipped and non-objects
raise SerializationException.

* fix(cognito): bound LogConfigurations and reject a repeated event source

SetLogDeliveryConfiguration validated each element but never checked the list
itself, so a request with three or more well-formed configurations, or two
naming the same event source, was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  3 well-formed configs   InvalidParameterException, length constraint on
                          'logConfigurations', max 2
  2 duplicate sources     InvalidParameterException, "appear more then once"
  3 configs, one bad enum 2 validation errors, the length one reported first
  unknown pool, bad enum  the validation error, not ResourceNotFoundException
  0 configs               200 OK

The shape checks now run before the pool lookup, matching that last row, and
collect every violation into one message instead of throwing on the first.
The duplicate and missing-destination complaints share one message with the
missing-destination clause first, and each event source is named once however
many configurations carry it, as measured.

"more then once" is the service's own spelling, kept so the message matches.

The length message embeds the request model's toString, which the emulator now
reproduces for all three destination shapes and for an absent destination.
2026-09-02 11:44:18 -04:00
BingEdward 7513b2241b docs(cognito): add UpdateResourceServer to the Resource Servers table (#2873)
UpdateResourceServer is dispatched by CognitoJsonHandler and implemented in
CognitoService, but the hand-maintained Resource Servers table in
docs/services/cognito.md did not list it.

Fixes #2854
2026-09-01 09:36:04 -04:00
lex00 ed167135ff feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain) (#2742)
* feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain)

Adds the domain family Cognito was missing, which blocks any estate using
aws_cognito_user_pool_domain (e.g. an ALB authenticate-cognito listener).
Supports both an Amazon Cognito prefix domain and a custom domain backed by
an ACM certificate ARN, matching the documented request and response shapes.
Domain names are globally unique across pools; a missing domain reports
ResourceNotFoundException on Describe/Delete, consistent with the rest of
the Cognito handler's not-found behavior.

* fix(cognito): refuse DeleteUserPool while a domain is configured

The DeleteUserPool API reference documents this refusal: a pool with a
hosted UI or custom domain answers InvalidParameterException ("User pool
cannot be deleted. It has a domain configured that should be deleted
first.") rather than deleting and stranding the globally-unique domain
name.
2026-08-29 23:58:59 -04:00
Abhigya 1ca19c722a fix(cognito): AWS-accurate UsernameAttributes pools — UUID username, alias sign-in, and token/revocation parity (#1849)
* feat: mint UUID username with mutable email alias for UsernameAttributes pools

* fix(cognito): align token claims, alias-exists, read-attributes, and not-found status with AWS

* fix(cognito): align token claims, alias-exists, read-attributes, not-found status, and canonical-username revocation with AWS

* fix(cognito): accept canonical UUID on RESEND, harden migration sub-minting and email validation)

* fix(cognito): AliasExistsException guard check

* test(cloudformation): expect 400 for Cognito ResourceNotFoundException

Align the post-deletion DescribeUserPool/DescribeUserPoolClient assertions
with the AWS-accurate 400 status now returned for Cognito
ResourceNotFoundException.

* fix(cognito): bind CUSTOM_AUTH challenge USERNAME to the session user

RespondToAuthChallenge validated SECRET_HASH against the caller-supplied
USERNAME while resolving the user from the session, so the two were allowed
to disagree. That reduced SECRET_HASH from a per-user binding to a bare
proof-of-client-secret check, and let callers pass locally against requests
real Cognito rejects.

Resolve the supplied USERNAME the same way sign-in does and require it to
match the session user; aliases still work since the caller may legitimately
send the email while the session holds the UUID.

Also compare SECRET_HASH with MessageDigest.isEqual instead of String.equals
so the MAC comparison does not short-circuit on the first differing byte,
matching the SRP path in CognitoSrpHelper.
2026-08-24 14:43:49 -04:00
Feyikemi Ogunsanya 24cdabb257 feat(cognito): add GetUserAttributeVerificationCode support (#1898)
* feat(cognito): issue attribute verification codes in CognitoService

* feat(cognito): dispatch GetUserAttributeVerificationCode in CognitoJsonHandler

* test(cognito): add GetUserAttributeVerificationCode happy path

* test(cognito): cover invalid token and unverifiable attribute errors

* docs(cognito): document GetUserAttributeVerificationCode

* fix(cognito): key attribute verification codes per attribute

* fix(cognito): match AWS error messages for GetUserAttributeVerificationCode

Real Cognito returns "Invalid Access Token", "Invalid attribute name.
Only phone_number and email can be verified.", and attribute-specific
"User does not have a valid registered email address" / "...phone
number" messages, per AWS-parity comparison in PR #1898 review.

* fix(cognito): match AWS destination masking format for verification codes

Real Cognito masks as "z***@b***" for email (first char of local part
and domain, three asterisks, no TLD retained) and "+********8920" for
phone (leading "+", asterisks, last four digits kept), per AWS-parity
comparison in PR #1898 review. Applies to both attribute-verification
and forgot-password/account-recovery delivery masking, which share
these helpers.

* test(cognito): assert exact AWS-parity error messages and mask format

Tighten GetUserAttributeVerificationCode assertions from loose
containsString checks to the exact wording and masking AWS returns,
so a regression in either silently drifting from AWS again is caught.

* test(cognito): cover re-issuing verification code for a verified attribute

AWS permits requesting a fresh GetUserAttributeVerificationCode code
for an attribute that is already verified, as long as its value has
not changed. Nothing in the current issuance path checks the
*_verified flag, so this locks in that AWS-parity behavior.

* style(cognito): drop redundant comment in attribute verification test

The method name already conveys the AWS behavior being tested, per
AGENTS.md's guidance to prefer self-explanatory code over comments.
2026-08-17 00:27:15 -05:00
soreavis 0203bc7f7e feat(cognito): add AdminLinkProviderForUser (#2166)
* feat(cognito): add AdminLinkProviderForUser

Linking a federated identity to an existing user pool user returned
400 UnsupportedOperation, because the action had no arm in the
CognitoJsonHandler switch and fell through to the default case.

Add the action to the handler and service. The link is recorded as an
entry in the destination user's `identities` attribute, matching the
JSON array AWS documents: userId, providerName, providerType, issuer,
primary and dateCreated. CognitoUser.attributes is already a free-form
map and AdminGetUser emits every attribute as a UserAttribute, so the
linked identity surfaces without a model change.

dateCreated is stored in epoch milliseconds. That differs from the
seconds this service uses for its own user timestamps, but it is what
AWS emits in the identities attribute and the ID token claim.

providerType is only set when the source provider name is one of the
provider types AWS also uses as a name (Facebook, Google,
LoginWithAmazon, SignInWithApple). SAML and OIDC types, and issuer, are
properties of a registered IdP, which the emulator does not model, so
they stay null rather than being guessed.

A source identity may be linked to at most one user per pool; a
conflicting link throws AliasExistsException, a documented error of
this operation.

Source provider names are not validated against a configured IdP, and
the five-identity cap is not enforced. Both are noted as deliberate
divergences in the pull request.

Closes #1563

* fix(cognito): validate link fields and serialize the uniqueness check

AdminLinkProviderForUser accepted requests with a missing SourceUser
ProviderName or ProviderAttributeValue: path().asText() turns absent
fields into empty strings, so a bad request returned 200 and persisted
an identity with an empty providerName or userId. Require the three
fields up front and answer InvalidParameterException, matching how
this service already reports missing required input.

The uniqueness check and the write could also interleave: two
concurrent links of the same source identity to different users could
both pass the scan before either wrote. Wrap the check and the write
in synchronized (pool), the pattern the tag operations already use.

* fix(cognito): serialize identity links on a stable monitor

The uniqueness check locked the UserPool object, but updateUserPool
replaces the stored instance (convertValue copy + poolStore.put), so
two links racing an update could hold different monitors and both pass
the scan. Serialize on a dedicated lock instead, declared beside the
one method it guards.

Dropping the describeUserPool lookup also changes the unknown-pool
error source: adminGetUser reports it as ResourceNotFoundException 400,
which is how every sibling admin user mutator already reports it.

Verified with an 8-thread probe linking the same source identity to
eight users: one winner and seven AliasExistsException with the lock,
eight winners without it.
2026-08-07 17:30:11 -05:00