* fix(cognito): fire PreTokenGeneration for client_credentials tokens
The token endpoint issued client_credentials access tokens without ever
invoking the pool's pre token generation trigger, so claims and scopes a
V3_0 function returned never reached M2M tokens.
As on AWS, the trigger now fires with triggerSource
TokenGeneration_ClientCredentials when PreTokenGenerationConfig's
LambdaVersion is V3_0, and is skipped for V1_0 and V2_0. The event
matches the one AWS documents for the token endpoint: userName
ClientCredentials, the granted scopes, empty userAttributes, a null
groupConfiguration, the request's aws_client_metadata, and a response
whose claimsAndScopeOverrideDetails is null. Only accessTokenGeneration
applies to the token; claims that identify the client (sub, client_id,
token_use, version, iss, exp, iat, jti and the cognito: namespace)
cannot be changed, and an added aud must equal the client ID.
Fixes#7792
* fix(cognito): protect username and scope in client-credentials tokens
Addresses review feedback on the client-credentials pre token generation
trigger.
A V3_0 trigger could add a username claim to a machine access token, and
could replace or suppress the granted scope through claimsToAddOrOverride
and claimsToSuppress. As on AWS, username (along with device_key and
at_hash) is now protected in machine tokens, and scope changes only
through scopesToAdd and scopesToSuppress.
aws_client_metadata with a null value is now refused with
invalid_request, like any other value that is not a string.
* fix(cognito): send version 3 and accept only string metadata for client credentials
The client-credentials pre token generation event now carries version "3",
as in the AWS token endpoint example. aws_client_metadata is read as a JSON
tree and refused unless it is an object whose values are all JSON strings,
so numbers and booleans are no longer coerced to strings.
* fix(cognito): offer configured providers in managed login
Preserve native authentication eligibility and request parameters for federated-only and mixed clients.
Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
* fix(cognito): explain unavailable sign-in providers
Show an actionable managed-login error after every provider is removed, without enabling native credentials.
Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
---------
Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
Record SignIn events for USER_PASSWORD_AUTH, ADMIN_USER_PASSWORD_AUTH,
ADMIN_NO_SRP_AUTH and USER_SRP_AUTH on pools with the Plus feature plan
and threat protection in AUDIT or ENFORCED mode, and list them newest
first with MaxResults and NextToken paging. Other pools get
UserPoolAddOnNotEnabledException. A wrong password is Fail, a sign-in
interrupted by a challenge stays InProgress until it ends in tokens, and
no EventRisk is reported since Floci performs no risk evaluation.
Events are matched to their pool and user by the stored owner, not the
key prefix alone, and a sign-in that ends after its user is deleted
records nothing.
Closes#6137
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
* 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.
* 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.
* 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.
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.
* 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>
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.
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
* 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>
* 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>
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
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".
* 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>
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.
* 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
* 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
* 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.
* 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.
* 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
* 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
* 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
* 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.
* 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
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
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.
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
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.
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.
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.
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.
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