Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ package org.apache.texera.web.resource.auth
import com.typesafe.scalalogging.Logger
import io.dropwizard.auth.Auth
import org.apache.texera.auth.JwtAuth.{jwtClaims, jwtToken}
import org.apache.texera.auth.SessionUser
import org.apache.texera.auth.{InviteOnly, SessionUser}
import org.apache.texera.common.config.UserSystemConfig
import org.apache.texera.common.util.EmailUtil
import org.apache.texera.dao.SqlServer
Expand Down Expand Up @@ -110,12 +110,32 @@ object AuthResource {
.where(DSL.lower(USER.EMAIL).eq(EmailUtil.normalize(email)))
.fetchOneInto(classOf[User])

/**
* The role a sign-up starts with: INACTIVE, waiting for an admin's approval, while invite-only
* is on, and REGULAR, usable at once, while it is off. Read on every call, so a switch on the
* admin settings page applies to the next sign-up.
*
* Callers read it before opening a transaction: the read borrows its own pooled connection, and
* holding one connection while waiting for another is how a burst of sign-ups drains the pool.
*/
def newAccountRole(): UserRoleEnum =
if (InviteOnly.enabled) UserRoleEnum.INACTIVE else UserRoleEnum.REGULAR

/**
* Give an account that is finishing its sign-up the role sign-ups start with. Only INACTIVE is
* replaced: every sign-up starts there, and any other role was set by an admin.
*/
private[auth] def admit(user: User, startingRole: UserRoleEnum): Unit =
if (user.getRole == UserRoleEnum.INACTIVE) user.setRole(startingRole)

/**
* Marks a placeholder account (auto-created for a dataset contributor) as
* claimed, leaving persistence to the caller.
* claimed, leaving persistence to the caller. Claiming is how the placeholder's owner signs
* up, so the account is admitted with `startingRole` (see [[newAccountRole]]).
*/
def claimPlaceholder(user: User): Unit = {
def claimPlaceholder(user: User, startingRole: UserRoleEnum): Unit = {
user.setIsPlaceholder(false)
admit(user, startingRole)
val claimedAt = Instant.now().truncatedTo(ChronoUnit.SECONDS)
user.setComment(
Option(user.getComment).map(_ + "; ").getOrElse("") +
Expand Down Expand Up @@ -203,6 +223,11 @@ class AuthResource {
)
}

// An account from a provider that asserts no address is created INACTIVE whatever the
// invite-only switch says, because it is inert until it has one. Supplying the address is
// where that sign-up finishes, so this is where it is admitted.
val startingRole = newAccountRole()

val user = SqlServer.withTransaction(SqlServer.getInstance().createDSLContext()) { ctx =>
val txUserDao = new UserDao(ctx.configuration())

Expand All @@ -220,11 +245,12 @@ class AuthResource {
Option(fetchUserByEmailIgnoreCase(ctx, email)) match {
case None =>
current.setEmail(email)
admit(current, startingRole)
txUserDao.update(current)
current

case Some(existing) if existing.getIsPlaceholder =>
adoptPlaceholder(ctx, txUserDao, current, existing)
adoptPlaceholder(ctx, txUserDao, current, existing, startingRole)

case Some(_) =>
throw new WebApplicationException(
Expand Down Expand Up @@ -254,7 +280,8 @@ class AuthResource {
ctx: DSLContext,
txUserDao: UserDao,
current: User,
placeholder: User
placeholder: User,
startingRole: UserRoleEnum
): User = {
val callerIsEmpty = current.getRole == UserRoleEnum.INACTIVE
val placeholderHasCredential = ctx.fetchExists(
Expand All @@ -276,7 +303,7 @@ class AuthResource {
// The caller's display name is their own, so it wins over the one whoever listed them as a
// contributor typed.
placeholder.setName(current.getName)
claimPlaceholder(placeholder)
claimPlaceholder(placeholder, startingRole)
txUserDao.update(placeholder)

// This FK has no ON DELETE CASCADE, so the row has to go before the account it points at.
Expand Down Expand Up @@ -370,7 +397,7 @@ class AuthResource {

if (!usernameExists && emailExists && existingByEmail.getIsPlaceholder) {
existingByEmail.setName(username)
claimPlaceholder(existingByEmail)
claimPlaceholder(existingByEmail, newAccountRole())
LocalAuthProvisioner.claimWithLocalCredential(existingByEmail, username, userpassword)
return jwtToken(jwtClaims(existingByEmail))
}
Expand All @@ -384,7 +411,7 @@ class AuthResource {
val user = new User
user.setName(username)
user.setEmail(useremail)
user.setRole(UserRoleEnum.INACTIVE)
user.setRole(newAccountRole())
// Reports losing the race to a concurrent registration of the same handle as a 409.
LocalAuthProvisioner.createLocalAccount(user, username, userpassword)
jwtToken(jwtClaims(user))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ object ExternalAuthProvisioner extends LazyLogging {
}

private def provision(profile: Asserted): User = {
// Read before the transaction opens, as `AuthResource.newAccountRole` asks.
val startingRole = AuthResource.newAccountRole()

SqlServer.withTransaction(SqlServer.getInstance().createDSLContext()) { ctx =>
val txUserDao = new UserDao(ctx.configuration())
val txAuthDao = new AuthProviderDao(ctx.configuration())
Expand Down Expand Up @@ -158,7 +161,7 @@ object ExternalAuthProvisioner extends LazyLogging {
case Some(existing) =>
existing.tap { user =>
val wasPlaceholder = user.getIsPlaceholder
if (wasPlaceholder) AuthResource.claimPlaceholder(user)
if (wasPlaceholder) AuthResource.claimPlaceholder(user, startingRole)
val drifted = refresh(user, profile)
if (drifted || wasPlaceholder) txUserDao.update(user)
}
Expand All @@ -169,7 +172,12 @@ object ExternalAuthProvisioner extends LazyLogging {
// index tolerates repeated NULLs, so several such accounts can coexist.
profile.email.foreach(created.setEmail)
profile.avatar.foreach(created.setAvatar)
created.setRole(UserRoleEnum.INACTIVE)
// Without an address the account is inert, so it starts INACTIVE whatever the
// invite-only switch says; `AuthResource.setEmail` admits it once it has one. An
// INACTIVE caller is also what lets that call hand it a contributor placeholder.
created.setRole(
if (profile.email.isDefined) startingRole else UserRoleEnum.INACTIVE
)
txUserDao.insert(created)
created
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@

package org.apache.texera.web.resource.auth

import org.apache.texera.auth.InviteOnly
import org.apache.texera.common.config.UserSystemConfig
import org.apache.texera.dao.MockTexeraDB
import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER}
import org.apache.texera.dao.{MockTexeraDB, SiteSettings}
import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, SITE_SETTINGS, USER}
import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, UserRoleEnum}
import org.apache.texera.dao.jooq.generated.tables.daos.UserDao
import org.apache.texera.dao.jooq.generated.tables.pojos.User
Expand Down Expand Up @@ -64,11 +65,16 @@ class AppleAuthResourceSpec

// Identity-only accounts have a NULL email, so they are matched by the name they are given
// instead — the Apple `sub`. AUTH_PROVIDER cascades on delete.
private def cleanup(): Unit =
private def cleanup(): Unit = {
getDSLContext
.deleteFrom(USER)
.where(USER.EMAIL.like("%" + emailDomain).or(USER.NAME.like("apple-sub-%")))
.execute()
getDSLContext
.deleteFrom(SITE_SETTINGS)
.where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey))
.execute()
}

// ---- helpers -------------------------------------------------------------

Expand Down Expand Up @@ -113,6 +119,10 @@ class AppleAuthResourceSpec
behavior of "login"

it should "provision an INACTIVE user and an APPLE provider row on a first login" in {
// The role follows the admin's invite-only switch (ExternalAuthProvisionerSpec covers both
// sides); pinned on here so the assertion does not depend on default.conf.
SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, "true", "apple-spec-admin")

loginWith(claims("apple-sub-new", "newcomer" + emailDomain))

val user = userByEmail("newcomer")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@ import ch.qos.logback.classic.{Level, Logger => LogbackLogger}
import ch.qos.logback.core.read.ListAppender
import com.fasterxml.jackson.databind.ObjectMapper
import io.dropwizard.jersey.errors.LoggingExceptionMapper
import org.apache.texera.auth.{JwtAuth, SessionUser}
import org.apache.texera.auth.{InviteOnly, JwtAuth, SessionUser}
import org.apache.texera.common.config.UserSystemConfig
import org.apache.texera.dao.MockTexeraDB
import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER, USER_LAST_ACTIVE_TIME}
import org.apache.texera.dao.{MockTexeraDB, SiteSettings}
import org.apache.texera.dao.jooq.generated.Tables.{
AUTH_PROVIDER,
SITE_SETTINGS,
USER,
USER_LAST_ACTIVE_TIME
}
import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, UserRoleEnum}
import org.apache.texera.dao.jooq.generated.tables.daos.{AuthProviderDao, UserDao}
import org.apache.texera.dao.jooq.generated.tables.pojos.{AuthProvider, User}
Expand Down Expand Up @@ -114,8 +119,19 @@ class AuthResourceSpec
getDSLContext.deleteFrom(USER).where(USER.NAME.startsWith("authspec_")).execute()
// createAdminUser() seeds the configured admin — remove it too so the test starts clean.
getDSLContext.deleteFrom(USER).where(USER.NAME.eq(UserSystemConfig.adminUsername)).execute()
getDSLContext
.deleteFrom(SITE_SETTINGS)
.where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey))
.execute()
}

/**
* Flip the invite-only switch the way the admin settings page does. `cleanup` removes the row,
* so a test that depends on the switch sets it rather than inheriting default.conf's value.
*/
private def setInviteOnly(on: Boolean): Unit =
SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, on.toString, "authspec_admin")

/**
* Seed a user plus the LOCAL auth_provider row it logs in with, mirroring
* `LocalAuthProvisioner.createLocalAccount`.
Expand Down Expand Up @@ -165,6 +181,10 @@ class AuthResourceSpec
private def googleIdClaimOf(token: String): AnyRef =
JwtAuth.jwtConsumer.processToClaims(token).getClaimValue("googleId")

/** The browser decides between the dashboard and the pending-approval screen from this claim. */
private def roleClaimOf(token: String): String =
String.valueOf(JwtAuth.jwtConsumer.processToClaims(token).getClaimValue("role"))

/**
* Runs `body` with a capturing appender on the logger `AuthResource`'s companion writes to, and
* returns the WARN messages it emitted. The level is forced because the root logger governs
Expand Down Expand Up @@ -249,10 +269,13 @@ class AuthResourceSpec

// ─── register ─────────────────────────────────────────────────────────────

"register" should "persist an INACTIVE user with a hashed password and issue a token" in {
"register" should "persist an INACTIVE user with a hashed password and issue a token while invite-only is on" in {
setInviteOnly(on = true)

val response = resource.register(UserRegistrationRequest(uname("reg"), uemail("reg"), "pw"))

subjectOf(response.accessToken) shouldBe uname("reg")
roleClaimOf(response.accessToken) shouldBe "INACTIVE"
val persisted = userDao.fetchByName(uname("reg"))
persisted.size() shouldBe 1
val stored = persisted.get(0)
Expand All @@ -265,6 +288,29 @@ class AuthResourceSpec
encryptor.checkPassword("pw", storedPassword) shouldBe true
}

// Off means sign-up is open. An INACTIVE account here signs in to a dashboard where every request
// is refused, because nothing ever shows it the pending-approval screen.
it should "persist a REGULAR user and issue a REGULAR token while invite-only is off" in {
setInviteOnly(on = false)

val response = resource.register(UserRegistrationRequest(uname("open"), uemail("open"), "pw"))

userDao.fetchByName(uname("open")).get(0).getRole shouldBe UserRoleEnum.REGULAR
roleClaimOf(response.accessToken) shouldBe "REGULAR"
}

// The switch is edited on the admin settings page, so the next sign-up has to see a change without
// a restart.
it should "apply an invite-only change to the very next registration" in {
setInviteOnly(on = true)
resource.register(UserRegistrationRequest(uname("before"), uemail("before"), "pw"))
setInviteOnly(on = false)
resource.register(UserRegistrationRequest(uname("after"), uemail("after"), "pw"))

userDao.fetchByName(uname("before")).get(0).getRole shouldBe UserRoleEnum.INACTIVE
userDao.fetchByName(uname("after")).get(0).getRole shouldBe UserRoleEnum.REGULAR
}

it should "reject an empty username" in {
val ex = intercept[NotAcceptableException](
resource.register(UserRegistrationRequest(" ", uemail("eu"), "pw"))
Expand Down Expand Up @@ -388,6 +434,7 @@ class AuthResourceSpec
)

it should "claim a placeholder account with the matching email" in {
setInviteOnly(on = true)
val placeholder = seedPlaceholder(uname("ghost"), uemail("claim"))

val response =
Expand All @@ -403,6 +450,18 @@ class AuthResourceSpec
claimed.getComment should include("Claimed contributor placeholder at ")
}

// Claiming a placeholder is how its owner signs up, so the account starts where a new one would.
it should "admit a claimed placeholder as REGULAR while invite-only is off" in {
setInviteOnly(on = false)
val placeholder = seedPlaceholder(uname("ghostopen"), uemail("claimopen"))

val response =
resource.register(UserRegistrationRequest(uname("claimeropen"), uemail("claimopen"), "pw"))

userDao.fetchOneByUid(placeholder.getUid).getRole shouldBe UserRoleEnum.REGULAR
roleClaimOf(response.accessToken) shouldBe "REGULAR"
}

it should "allow logging in with the claimed credentials" in {
seedPlaceholder(uname("ghost2"), uemail("claimlogin"))
resource.register(UserRegistrationRequest(uname("claimer2"), uemail("claimlogin"), "secret-pw"))
Expand Down Expand Up @@ -652,6 +711,39 @@ class AuthResourceSpec
emailClaimOf(response.accessToken) shouldBe uemail("fill")
}

// A provider that asserts no address (ORCID) gets an INACTIVE account whatever the switch says,
// because the account is inert until it has an address. Supplying one is where that sign-up
// finishes, so that is where open sign-up admits it.
it should "admit an INACTIVE account as REGULAR once it supplies an address while invite-only is off" in {
setInviteOnly(on = false)
val user = seedEmaillessUser("admit")

val response = resource.setEmail(SetEmailRequest(uemail("admit")), new SessionUser(user))

userDao.fetchOneByUid(user.getUid).getRole shouldBe UserRoleEnum.REGULAR
roleClaimOf(response.accessToken) shouldBe "REGULAR"
}

it should "leave the account INACTIVE, awaiting approval, while invite-only is on" in {
setInviteOnly(on = true)
val user = seedEmaillessUser("await")

val response = resource.setEmail(SetEmailRequest(uemail("await")), new SessionUser(user))

userDao.fetchOneByUid(user.getUid).getRole shouldBe UserRoleEnum.INACTIVE
roleClaimOf(response.accessToken) shouldBe "INACTIVE"
}

// RESTRICTED is an admin's decision about this person, not a sign-up still in progress.
it should "keep a role an admin set when the account supplies its address" in {
setInviteOnly(on = false)
val user = seedEmaillessUser("restricted", role = UserRoleEnum.RESTRICTED)

resource.setEmail(SetEmailRequest(uemail("restricted")), new SessionUser(user))

userDao.fetchOneByUid(user.getUid).getRole shouldBe UserRoleEnum.RESTRICTED
}

it should "reject a malformed address" in {
val user = seedEmaillessUser("bad")

Expand Down Expand Up @@ -756,6 +848,30 @@ class AuthResourceSpec
emailClaimOf(response.accessToken) shouldBe uemail("ghost")
}

it should "admit the adopted placeholder as REGULAR while invite-only is off" in {
setInviteOnly(on = false)
val placeholder = seedPlaceholder(uname("ghostadmit"), uemail("ghostadmit"))
val caller = seedEmaillessUser("adopter")

val response =
resource.setEmail(SetEmailRequest(uemail("ghostadmit")), new SessionUser(caller))

userDao.fetchOneByUid(placeholder.getUid).getRole shouldBe UserRoleEnum.REGULAR
roleClaimOf(response.accessToken) shouldBe "REGULAR"
}

it should "keep the adopted placeholder INACTIVE while invite-only is on" in {
setInviteOnly(on = true)
val placeholder = seedPlaceholder(uname("ghostwait"), uemail("ghostwait"))
val caller = seedEmaillessUser("waiter")

val response =
resource.setEmail(SetEmailRequest(uemail("ghostwait")), new SessionUser(caller))

userDao.fetchOneByUid(placeholder.getUid).getRole shouldBe UserRoleEnum.INACTIVE
roleClaimOf(response.accessToken) shouldBe "INACTIVE"
}

// `user_last_active_time.uid` references "user"(uid) with no ON DELETE CASCADE — the only FK to
// "user" that does not cascade — so discarding the caller's row fails unless that row goes first.
// Any authenticated request can have created it, so the adoption must not depend on its absence.
Expand Down Expand Up @@ -846,6 +962,7 @@ class AuthResourceSpec
}

"register/verify" should "create the account when the mailed code comes back" in {
setInviteOnly(on = true)
verifying.register(UserRegistrationRequest(uname("done"), uemail("done"), "secret"))

val response = verifying.registerVerify(
Expand Down
Loading
Loading