Commit Graph
71 Commits
Author SHA1 Message Date
Daniël van Ziel 0ee1d10659 fix(cognito): refuse a reused TOTP code for SOFTWARE_TOKEN_MFA (#6808)
A software-token code now answers one SOFTWARE_TOKEN_MFA challenge only. The step of the
last accepted code is stored on the user, and a code from that step or an earlier one fails
with ExpiredCodeException, as AWS does (RFC 6238 section 5.2). VerifySoftwareToken does not
record a step, and activating a new authenticator clears it.

Fixes #6804
2026-10-28 07:20:05 -04:00
Aniket Shukla da517acc65 fix(cognito): verify SRP proofs in custom authentication (#6794)
* fix(cognito): verify SRP proofs in custom authentication

* fix(cognito): include password-change challenge parameters
2026-10-28 07:07:12 -04:00
Jimmy Liu Jia b90b671c21 fix(cognito): verify admin contact attribute updates (#6474)
* fix(cognito): verify admin contact attribute updates

* fix(cognito): roll back failed admin contact updates

* fix(cognito): preserve verification during overlapping callbacks

* fix(cognito): scope verification cleanup to issued codes

* fix(cognito): retry undelivered admin attribute codes

* test(cognito): update tracked code fixtures

* fix(cognito): share contact updates after sender failures
2026-10-25 08:59:27 -04:00
Aniket Shukla da9f7e93b1 fix(cognito): keep attribute updates after sender failures (#6493)
* fix(cognito): keep attribute updates after sender failures

* fix(cognito): withdraw stale codes after sender failure

Invalidate prior verification codes when a failed sender handover retains a different active or pending contact destination. Preserve codes for unchanged contacts the send loop never reached.
2026-10-25 07:48:48 -04:00
Aniket Shukla 381ad1f00b fix(cognito): match custom message trigger event fields (#6445) 2026-10-24 19:17:35 -04:00
Aniket Shukla c5ab54d49c fix(cognito): omit absent authentication message metadata (#6440) 2026-10-24 14:10:26 -04:00
Alessandro Lattao 2c5415186a fix(cognito): fire the CustomMessage trigger for UpdateUserAttributes and GetUserAttributeVerificationCode (#6205)
* fix(cognito): fire the CustomMessage trigger for UpdateUserAttributes and GetUserAttributeVerificationCode

Both sent their verification codes without the CustomMessage trigger, so a
pool's function never shaped those messages and never saw the request's
ClientMetadata. They now fire it with CustomMessage_UpdateUserAttribute and
CustomMessage_VerifyUserAttribute.

Measured on Cognito, the event carries the user as stored once the request is
done: the whole update applied, and an email that must be verified before it
changes still the old one while the code goes to the new address. The message
is therefore sent once the update is stored and the user lock is released. The
trigger is synchronous, so holding the lock would also block a function that
calls the pool back for the same user until its invocation timed out, which
SignUp already avoids. Cognito keeps an update whose code it cannot deliver
and answers CodeDeliveryFailureException, and a message that cannot be sent
now does the same.

* fix(cognito): leave nothing behind when an attribute code's message is not sent

Sending an attribute code's message after the user lock opened four ways to
leave a code live that no message carried, or to fail an update already
stored. Each message is now sent on its own: one that cannot be sent has its
code withdrawn, so another can be asked for at once as on Cognito, and the
others still go out. An update that stops before it is stored withdraws the
codes it already issued. The pool, the client and a copy of the stored user
are read while the lock is held, as SignUp captures its trigger's user, so
nothing is looked up once the update is stored.
2026-10-22 06:44:54 -04:00
Mohith 645c97c803 fix(cognito): return USER_ID_FOR_SRP in the SOFTWARE_TOKEN_MFA challenge (#6086)
* fix(cognito): return USER_ID_FOR_SRP in the SOFTWARE_TOKEN_MFA challenge

The SOFTWARE_TOKEN_MFA challenge carried the canonical username under
USERNAME. AWS returns it as USER_ID_FOR_SRP, the key clients read to
build USERNAME and SECRET_HASH for the challenge response, so they could
not answer the challenge.

The challenge now carries USER_ID_FOR_SRP (the sub in a pool with
UsernameAttributes) and FRIENDLY_DEVICE_NAME when one was set, matching
the InitiateAuth API reference example. VerifySoftwareToken keeps the
FriendlyDeviceName on the user and replaces it with each newly verified
authenticator. Every flow that ends in SOFTWARE_TOKEN_MFA shares the
same builder, so password, admin password, SRP, USER_AUTH,
NEW_PASSWORD_REQUIRED and SELECT_MFA_TYPE all get the new parameters.
MFA_SETUP is unchanged.

Fixes #6074

* fix(cognito): reject an over-long FriendlyDeviceName in VerifySoftwareToken

VerifySoftwareToken stored a FriendlyDeviceName of any length and later
returned it in the SOFTWARE_TOKEN_MFA challenge. The service model caps
the member at 131072 characters, and AWS rejects a longer value during
request validation, before the code is checked.

A longer name now fails with InvalidParameterException and the Smithy
length-constraint message, before any session, token or code is looked
at, so the user's authenticator, pending association and remaining
attempts are left as they were. The length counts Unicode code points,
as Smithy's length trait does, so a name of supplementary characters
such as emoji is measured in characters rather than UTF-16 units. An
absent or empty name is unchanged.
2026-10-20 13:02:17 -04:00
jwoa95 d1a2708634 fix(cognito): keep the sign-in's auth_time across managed login sessions and refresh (#5157)
The tokens an authorization code redeems for were stamped with the time of
the redemption, so an authorize that a managed login session let skip the
form reported a fresh sign-in, and so did every refresh of those tokens.

The managed login session now records when the user signed in, the
authorization code carries that time (or the identity provider callback's
for federated sign-in), and the token endpoint mints with it. Refresh tokens
carry it too, so REFRESH_TOKEN_AUTH, GetTokensFromRefreshToken and the token
endpoint's refresh_token grant keep the original auth_time, as AWS
documents: "Refreshing a token doesn't reset the auth_time claim."

The sign-in time is a tagged auth_time= field after the family id, ahead of
the scope field. Refresh tokens minted before keep working and fall back to
the time they were issued.

A pre token generation trigger can no longer suppress or override auth_time,
which AWS lists among the claims a trigger cannot add, modify or suppress.
2026-10-20 11:48:02 -04:00
Alessandro Lattaoandoutof-place 47f570a821 feat(cognito): hand email codes to the CustomEmailSender trigger (#6031)
* feat(cognito): hand email codes to the CustomEmailSender trigger

* test(cognito): decrypt CustomEmailSender codes with the AWS Encryption SDK

* docs(cognito): document the CustomEmailSender trigger

* fix(cognito): fail a CustomEmailSender delivery as Cognito does

Measured on Cognito (eu-west-1, 2026-10-16), with the events a real sender
received:
- CreateUserPool and UpdateUserPool refuse a custom sender trigger without
  a KMSKeyID ("KMSKeyId parameter is required when Custom SMS/Email Lambda
  trigger is used."), and CreateUserPool a key that does not exist
  ("Encountered error when CreateGrant was attempted on the input KMS key -
  Key '<id>' does not exist"), both InvalidParameterException.
- A disabled key fails the request with CodeDeliveryFailureException
  "Caller needs to enable the configured KMS Key", a key pending deletion
  with "Unable to encrypt CustomEmailSender/CustomSMSSender code using the
  configured KMS Key". The sign-up is kept, unlike a failed SES delivery,
  and InitiateAuth answers the same error rather than InternalErrorException.
- A function that is gone, or that Cognito may not invoke, answers
  UnexpectedLambdaException "CustomEmailSender invocation failed due to
  error AccessDeniedException."
- request.clientMetadata is null for every source, InitiateAuth's
  ClientMetadata included, so the parameter that carried it is gone.

The branch also follows main since it was written: CognitoService takes
enforceTokenValidityLimits, and signUp ValidationData and ClientMetadata.

* fix(cognito): withdraw a code the CustomEmailSender could not take

Review of #6031: when the handover failed, the code issued for it stayed
live in SignUp, ForgotPassword and both attribute flows, so asking for a
code again within 30 seconds answered LimitExceededException. Measured
on Cognito (eu-west-1): it hands out a code again at once, on a healthy
pool and once a key that could not encrypt is enabled again, for
ResendConfirmationCode and ForgotPassword alike.

sendThroughCustomEmailSender now withdraws the code before it fails, for
every flow, and the two catches that withdrew it by hand (resend and the
sign-in OTP) leave that to it.

* fix(cognito): hand the CustomEmailSender the request's ClientMetadata

Review of #6031: the developer guide lists ClientMetadata for the
sign-up, forgot-password and sign-in sources, and the branch passed null
for every one on the strength of InitiateAuth alone. Measured on Cognito
(eu-west-1): SignUp, ResendConfirmationCode, ForgotPassword,
GetUserAttributeVerificationCode and UpdateUserAttributes each hand the
function the request's ClientMetadata; only the sign-in code's event has
none, even when InitiateAuth sends one. A request without ClientMetadata
gives null, as measured before.

ResendConfirmationCode, ForgotPassword and the two attribute calls now
take the request's ClientMetadata through the service, with overloads
that keep their previous signatures. resolveTriggerArn's custom sender
branch gets its braces.

---------

Co-authored-by: outof-place <contact@outofplace.space>
2026-10-20 06:44:20 -04:00
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