From 57db3a698be6052f2bd8b74cfe5cf416466694c1 Mon Sep 17 00:00:00 2001 From: Xinyuan Lin Date: Mon, 16 Nov 2026 02:34:13 -0800 Subject: [PATCH 1/8] test: pin invite-only sign-up roles and the admin switch --- .../resource/auth/AppleAuthResourceSpec.scala | 16 ++- .../web/resource/auth/AuthResourceSpec.scala | 125 +++++++++++++++++- .../auth/ExternalAuthProvisionerSpec.scala | 84 +++++++++++- .../auth/GoogleAuthResourceSpec.scala | 16 ++- .../apache/texera/auth/InviteOnlySpec.scala | 78 +++++++++++ .../common/config/DefaultsConfigSpec.scala | 8 ++ .../common/config/UserSystemConfigSpec.scala | 1 - .../apache/texera/dao/SiteSettingsSpec.scala | 22 +++ .../service/resource/ConfigResourceSpec.scala | 35 +++++ .../settings/admin-settings.component.spec.ts | 111 +++++++++++++++- .../login/texera-login.component.spec.ts | 87 +++++++++++- 11 files changed, 565 insertions(+), 18 deletions(-) create mode 100644 common/auth/src/test/scala/org/apache/texera/auth/InviteOnlySpec.scala diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala index 43e39b5d3a8..0f9fa7692b1 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala @@ -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 @@ -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 ------------------------------------------------------------- @@ -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") diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthResourceSpec.scala index d568425cc19..bb86daed245 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthResourceSpec.scala @@ -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} @@ -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`. @@ -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 @@ -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) @@ -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")) @@ -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 = @@ -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")) @@ -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") @@ -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. @@ -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( diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala index 2f35df53f35..7ac0799fc4b 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala @@ -19,8 +19,9 @@ package org.apache.texera.web.resource.auth -import org.apache.texera.dao.MockTexeraDB -import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER} +import org.apache.texera.auth.InviteOnly +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.{AuthProviderDao, UserDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{AuthProvider, User} @@ -76,10 +77,27 @@ class ExternalAuthProvisionerSpec ) ) .execute() + getDSLContext + .deleteFrom(SITE_SETTINGS) + .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) + .execute() } // ---- helpers ------------------------------------------------------------- + /** Flip the invite-only switch the way the admin settings page does; `cleanup` removes it. */ + private def setInviteOnly(on: Boolean): Unit = + SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, on.toString, "provisioner-admin") + + /** A contributor placeholder as DatasetResource creates one: INACTIVE, with no credential. */ + private def seedPlaceholder(name: String, localPart: String): User = { + val placeholder = seedUser(name, localPart) + placeholder.setIsPlaceholder(true) + placeholder.setRole(UserRoleEnum.INACTIVE) + userDao.update(placeholder) + placeholder + } + /** Avatars are complete provider URLs now, so tests that assert on one have to use a URL. */ private def avatarUrl(id: String): String = s"https://lh3.googleusercontent.com/a/$id" @@ -136,7 +154,9 @@ class ExternalAuthProvisionerSpec // ---- new-identity provisioning ------------------------------------------- - "ExternalAuthProvisioner.loginOrProvision" should "create an INACTIVE user and provider row for a brand-new Google identity" in { + "ExternalAuthProvisioner.loginOrProvision" should "create an INACTIVE user and provider row for a brand-new Google identity while invite-only is on" in { + setInviteOnly(on = true) + val user = ExternalAuthProvisioner.loginOrProvision( profile("google-sub-1", "New User", "new" + emailDomain, avatar = Some(avatarUrl("a1"))) ) @@ -151,6 +171,51 @@ class ExternalAuthProvisionerSpec providerIdOf(user.getUid, ProviderTypeEnum.GOOGLE) shouldBe "google-sub-1" } + it should "create a REGULAR user for a brand-new Google identity while invite-only is off" in { + setInviteOnly(on = false) + + val user = ExternalAuthProvisioner.loginOrProvision( + profile("google-sub-open", "Open User", "open" + emailDomain) + ) + + user.getRole shouldBe UserRoleEnum.REGULAR + userDao.fetchOneByUid(user.getUid).getRole shouldBe UserRoleEnum.REGULAR + } + + // Claiming a placeholder is how its owner signs up, so it starts where a new account would. + it should "admit a claimed INACTIVE placeholder as REGULAR while invite-only is off" in { + setInviteOnly(on = false) + val placeholder = seedPlaceholder("Ghost", "admitme") + + ExternalAuthProvisioner.loginOrProvision(profile("sub-admit", "Ghost", "admitme" + emailDomain)) + + userDao.fetchOneByUid(placeholder.getUid).getRole shouldBe UserRoleEnum.REGULAR + } + + it should "keep a claimed placeholder INACTIVE while invite-only is on" in { + setInviteOnly(on = true) + val placeholder = seedPlaceholder("Ghost", "waitme") + + ExternalAuthProvisioner.loginOrProvision(profile("sub-wait", "Ghost", "waitme" + emailDomain)) + + userDao.fetchOneByUid(placeholder.getUid).getRole shouldBe UserRoleEnum.INACTIVE + } + + // An INACTIVE account that is not a placeholder is a sign-up already waiting for approval. Adding + // a sign-in method to it is not a new sign-up, so turning invite-only off does not approve it. + it should "leave an existing INACTIVE account INACTIVE when a provider links to it" in { + setInviteOnly(on = false) + val pending = seedUser("Pending", "pending") + pending.setRole(UserRoleEnum.INACTIVE) + userDao.update(pending) + + ExternalAuthProvisioner.loginOrProvision( + profile("sub-pending", "Pending", "pending" + emailDomain) + ) + + userDao.fetchOneByUid(pending.getUid).getRole shouldBe UserRoleEnum.INACTIVE + } + // ---- returning known identity -------------------------------------------- it should "be idempotent for a returning identity (same uid, no duplicate provider row or user)" in { @@ -292,6 +357,19 @@ class ExternalAuthProvisionerSpec providerIdOf(user.getUid, ProviderTypeEnum.ORCID) shouldBe "0000-0001-0000-0001" } + // Such an account is inert until it has an address, and an INACTIVE caller is what lets + // AuthResource.setEmail hand it a contributor placeholder. The address step admits it instead. + it should "keep an identity-only account INACTIVE even while invite-only is off" in { + setInviteOnly(on = false) + + val user = + ExternalAuthProvisioner.loginOrProvisionIdentityOnly( + orcidIdentity("0000-0001-0000-0009", "Open Researcher") + ) + + user.getRole shouldBe UserRoleEnum.INACTIVE + } + // Two emailless accounts have to be able to coexist: `"user".email` is UNIQUE, which in Postgres // does not constrain repeated NULLs. If that ever changed, the second login would 500 here // rather than silently merging, but this pins the behavior either way. diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala index 78eb974eba2..b5fbbccc921 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala @@ -20,9 +20,10 @@ package org.apache.texera.web.resource.auth import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken +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 @@ -63,8 +64,13 @@ class GoogleAuthResourceSpec override protected def beforeEach(): Unit = cleanup() override protected def afterEach(): Unit = cleanup() - private def cleanup(): Unit = + private def cleanup(): Unit = { getDSLContext.deleteFrom(USER).where(USER.EMAIL.like("%" + emailDomain)).execute() + getDSLContext + .deleteFrom(SITE_SETTINGS) + .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) + .execute() + } // ---- helpers ------------------------------------------------------------- @@ -118,6 +124,10 @@ class GoogleAuthResourceSpec behavior of "login" it should "provision an INACTIVE user and a GOOGLE 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", "google-spec-admin") + loginWith(payload("google-sub-new", "newcomer" + emailDomain, name = "New Comer")) val user = userByEmail("newcomer") diff --git a/common/auth/src/test/scala/org/apache/texera/auth/InviteOnlySpec.scala b/common/auth/src/test/scala/org/apache/texera/auth/InviteOnlySpec.scala new file mode 100644 index 00000000000..15144309253 --- /dev/null +++ b/common/auth/src/test/scala/org/apache/texera/auth/InviteOnlySpec.scala @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.auth + +import org.apache.texera.common.config.DefaultsConfig +import org.apache.texera.dao.{MockTexeraDB, SiteSettings} +import org.apache.texera.dao.jooq.generated.Tables.SITE_SETTINGS +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} + +/** + * Spec for [[InviteOnly]]: the switch is the `invite_only` site setting the admin settings page + * writes, read again on every call, with default.conf's value standing in while no usable row + * is stored. + */ +class InviteOnlySpec + extends AnyFlatSpec + with Matchers + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + override protected def beforeAll(): Unit = initializeDBAndReplaceDSLContext() + + override protected def afterAll(): Unit = closeConnectionPool() + + override protected def beforeEach(): Unit = + getDSLContext + .deleteFrom(SITE_SETTINGS) + .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) + .execute() + + private def store(value: String): Unit = + SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, value, "spec-admin") + + private def configuredDefault: Boolean = DefaultsConfig.inviteOnly + + // The settings API only writes keys that have a default.conf entry, so a key without one could + // never be switched from the admin page. + "InviteOnly.SettingKey" should "name a default.conf entry, so the settings API accepts it" in { + DefaultsConfig.allDefaults should contain key InviteOnly.SettingKey + } + + "InviteOnly.enabled" should "follow the stored setting, including a change made after startup" in { + store("true") + InviteOnly.enabled shouldBe true + + store("false") + InviteOnly.enabled shouldBe false + } + + it should "use the default.conf value while no row is stored" in { + InviteOnly.enabled shouldBe configuredDefault + } + + it should "use the default.conf value when the stored row is not a boolean" in { + store("sometimes") + InviteOnly.enabled shouldBe configuredDefault + } +} diff --git a/common/config/src/test/scala/org/apache/texera/common/config/DefaultsConfigSpec.scala b/common/config/src/test/scala/org/apache/texera/common/config/DefaultsConfigSpec.scala index 52da44ca126..91e3d82aa25 100644 --- a/common/config/src/test/scala/org/apache/texera/common/config/DefaultsConfigSpec.scala +++ b/common/config/src/test/scala/org/apache/texera/common/config/DefaultsConfigSpec.scala @@ -38,6 +38,12 @@ class DefaultsConfigSpec extends AnyFlatSpec with Matchers { ) } + // A REGULAR account can run code on the server, so open sign-up has to be a deployment's own + // choice rather than what it gets by leaving USER_SYS_INVITE_ONLY unset. + "DefaultsConfig.inviteOnly" should "default to invite-only" in { + ifUnset("USER_SYS_INVITE_ONLY")(DefaultsConfig.inviteOnly shouldBe true) + } + "DefaultsConfig.allDefaults" should "flatten default.conf into short-key/value entries" in { val defaults = DefaultsConfig.allDefaults defaults should not be empty @@ -57,6 +63,8 @@ class DefaultsConfigSpec extends AnyFlatSpec with Matchers { ifUnset("OPERATOR_CSV_PARSER_MAX_COLUMNS")( defaults.get("csv_parser_max_columns") shouldBe Some("512") ) + // the invite-only switch, seeded from the variable the user system has always read + ifUnset("USER_SYS_INVITE_ONLY")(defaults.get("invite_only") shouldBe Some("true")) // every value is rendered as a String defaults.values.foreach(_ shouldBe a[String]) } diff --git a/common/config/src/test/scala/org/apache/texera/common/config/UserSystemConfigSpec.scala b/common/config/src/test/scala/org/apache/texera/common/config/UserSystemConfigSpec.scala index 0e42bf3f5c2..2265d9fe521 100644 --- a/common/config/src/test/scala/org/apache/texera/common/config/UserSystemConfigSpec.scala +++ b/common/config/src/test/scala/org/apache/texera/common/config/UserSystemConfigSpec.scala @@ -70,7 +70,6 @@ class UserSystemConfigSpec extends AnyFlatSpec with Matchers { UserSystemConfig.orcidRedirectUri shouldBe "http://127.0.0.1:4200/callback/orcid" ) ifUnset("USER_SYS_PROJECT_NAME")(UserSystemConfig.projectName shouldBe "Texera") - ifUnset("USER_SYS_INVITE_ONLY")(UserSystemConfig.inviteOnly shouldBe false) ifUnset("USER_SYS_EMAIL_VERIFICATION")(UserSystemConfig.emailVerification shouldBe false) ifUnset("USER_SYS_VERSION_TIME_LIMIT_IN_MINUTES")( UserSystemConfig.workflowVersionCollapseIntervalInMinutes shouldBe 60 diff --git a/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala b/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala index 33199aae261..51f81f5a486 100644 --- a/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala +++ b/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala @@ -93,6 +93,28 @@ class SiteSettingsSpec SiteSettings.getLong("big", 0L) shouldBe 9999999999L } + "getBoolean" should "read a stored true or false regardless of case and surrounding whitespace" in { + SiteSettings.upsert(getDSLContext, "flag_on", " TRUE ", "admin") + SiteSettings.upsert(getDSLContext, "flag_off", "false", "admin") + SiteSettings.getBoolean("flag_on", default = false) shouldBe true + SiteSettings.getBoolean("flag_off", default = true) shouldBe false + } + + it should "return the default when the key is absent" in { + SiteSettings.getBoolean("missing_flag", default = true) shouldBe true + SiteSettings.getBoolean("missing_flag", default = false) shouldBe false + } + + // Only the two literals are answers. Reading "yes", "1" or a blank as false would quietly pick + // whichever side of a switch false stands for. + it should "return the default when the stored value is not a boolean literal" in { + Seq("yes", "1", "").foreach { raw => + SiteSettings.upsert(getDSLContext, "bad_flag", raw, "admin") + SiteSettings.getBoolean("bad_flag", default = true) shouldBe true + SiteSettings.getBoolean("bad_flag", default = false) shouldBe false + } + } + "upsert" should "insert a new row and then overwrite it with the latest value and writer" in { SiteSettings.upsert(getDSLContext, "k", "1", "admin") SiteSettings.getInt("k", 0) shouldBe 1 diff --git a/config-service/src/test/scala/org/apache/texera/service/resource/ConfigResourceSpec.scala b/config-service/src/test/scala/org/apache/texera/service/resource/ConfigResourceSpec.scala index ce3819d8beb..cea6780db22 100644 --- a/config-service/src/test/scala/org/apache/texera/service/resource/ConfigResourceSpec.scala +++ b/config-service/src/test/scala/org/apache/texera/service/resource/ConfigResourceSpec.scala @@ -475,6 +475,41 @@ class ConfigResourceSpec resource.getSetting("csv_parser_max_columns").settingValue shouldBe DefaultsConfig.allDefaults("csv_parser_max_columns") } + + it should "restore the invite-only switch to its default.conf value" in { + // Write the opposite of the default, so the reset shows whichever way the default is set. + val opposite = (!DefaultsConfig.inviteOnly).toString + resource.updateSetting( + adminSession(), + "invite_only", + ConfigSettingPojo("invite_only", opposite) + ) + resource.getSetting("invite_only").settingValue shouldBe opposite + + resource.resetSetting(adminSession(), "invite_only").getStatus shouldBe 200 + resource.getSetting("invite_only").settingValue shouldBe + DefaultsConfig.allDefaults("invite_only") + } + + // The login flow decides whether to show the pending-approval screen from these two payloads, and + // the switch is now edited on the admin settings page. A value frozen at service start would keep + // the screen out of step with the role the next sign-up gets. + "getPreLoginConfig and getUserSystemConfig" should "report invite-only as the admin settings page last wrote it" in { + resource.updateSetting(adminSession(), "invite_only", ConfigSettingPojo("invite_only", "true")) + resource.getPreLoginConfig("inviteOnly") shouldBe true + resource.getUserSystemConfig("inviteOnly") shouldBe true + + resource.updateSetting(adminSession(), "invite_only", ConfigSettingPojo("invite_only", "false")) + resource.getPreLoginConfig("inviteOnly") shouldBe false + resource.getUserSystemConfig("inviteOnly") shouldBe false + } + + it should "fall back to the default.conf value while no invite_only row is stored" in { + getDSLContext.deleteFrom(SITE_SETTINGS).where(SITE_SETTINGS.KEY.eq("invite_only")).execute() + + resource.getPreLoginConfig("inviteOnly") shouldBe DefaultsConfig.inviteOnly + resource.getUserSystemConfig("inviteOnly") shouldBe DefaultsConfig.inviteOnly + } } object ConfigResourceSpec { diff --git a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.spec.ts b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.spec.ts index 4dfea1cd85e..1be030b1f93 100644 --- a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.spec.ts +++ b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.spec.ts @@ -82,6 +82,7 @@ describe("AdminSettingsComponent", () => { model_max_number_of_concurrent_uploading_file_chunks: "4", model_multipart_upload_chunk_size_mib: "32", csv_parser_max_columns: "4096", + invite_only: "true", }); expect(component.logoData).toBe("logo.png"); @@ -99,6 +100,28 @@ describe("AdminSettingsComponent", () => { expect(modelForm().maxConcurrentChunks).toBe(4); expect(modelForm().chunkSizeMiB).toBe(32); expect(component.csvMaxColumns).toBe(4096); + expect(component.inviteOnly).toBe(true); + }); + + it("reads invite-only as off for a stored false", () => { + httpTestingController.expectOne(SETTINGS_URL).flush({ invite_only: "false" }); + + expect(component.inviteOnly).toBe(false); + }); + + // The backend reads the row trimmed and case-insensitively, so the switch has to agree with it. + it("reads a padded or upper-case false as off", () => { + httpTestingController.expectOne(SETTINGS_URL).flush({ invite_only: " FALSE " }); + + expect(component.inviteOnly).toBe(false); + }); + + // Anything but false leaves sign-up closed on the backend too (an unreadable value falls back to + // the default, on), so the switch shows on rather than inviting a Save that opens sign-up. + it("reads a value that is not false as on", () => { + httpTestingController.expectOne(SETTINGS_URL).flush({ invite_only: "sometimes" }); + + expect(component.inviteOnly).toBe(true); }); it("keeps the initializer defaults for missing or unparsable values", () => { @@ -112,6 +135,8 @@ describe("AdminSettingsComponent", () => { // The model default is the 2 GiB ceiling #8000 gave models, not the dataset's 20 MiB. expect(modelForm().maxFileSizeMiB).toBe(2048); expect(component.csvMaxColumns).toBe(512); + // On is the default and the safe side: Save writes whatever the switch shows. + expect(component.inviteOnly).toBe(true); }); it("surfaces a load failure through the message service", () => { @@ -475,6 +500,72 @@ describe("AdminSettingsComponent", () => { }); }); + describe("registration settings", () => { + it("saveRegistrationSettings PUTs the invite-only switch and notifies success", () => { + completeLoad({ invite_only: "false" }); + component.inviteOnly = true; + + component.saveRegistrationSettings(); + + const req = httpTestingController.expectOne(updateUrl("invite_only")); + expect(req.request.method).toBe("PUT"); + expect(req.request.body).toEqual({ value: "true" }); + req.flush(null); + + expect(notifySuccess).toHaveBeenCalledWith("Registration settings saved."); + }); + + it("saveRegistrationSettings writes false once the switch is turned off", () => { + completeLoad({ invite_only: "true" }); + component.inviteOnly = false; + + component.saveRegistrationSettings(); + + const req = httpTestingController.expectOne(updateUrl("invite_only")); + expect(req.request.body).toEqual({ value: "false" }); + req.flush(null); + }); + + // A failed load leaves the switch at its initializer rather than the stored value, and saving + // that would overwrite the admin's choice of who may sign up. + it("saveRegistrationSettings refuses to save before the bulk load completes", () => { + const pending = httpTestingController.expectOne(SETTINGS_URL); + + component.saveRegistrationSettings(); + + httpTestingController.expectNone((req: { method: string }) => req.method === "PUT"); + expect(msgError).toHaveBeenCalledWith("Settings have not loaded; refresh before saving."); + pending.flush({}); + }); + + it("saveRegistrationSettings notifies an error when the request fails", () => { + completeLoad(); + + component.saveRegistrationSettings(); + + httpTestingController.expectOne(updateUrl("invite_only")).flush("boom", HTTP_ERROR); + expect(notifyError).toHaveBeenCalledWith("Could not save registration settings."); + }); + + it("resetRegistrationSettings POSTs a reset and notifies info", () => { + completeLoad(); + + component.resetRegistrationSettings(); + + httpTestingController.expectOne(resetUrl("invite_only")).flush(null); + expect(notifyInfo).toHaveBeenCalledWith("Resetting registration settings..."); + }); + + it("resetRegistrationSettings notifies an error when the reset fails", () => { + completeLoad(); + + component.resetRegistrationSettings(); + + httpTestingController.expectOne(resetUrl("invite_only")).flush("boom", HTTP_ERROR); + expect(notifyError).toHaveBeenCalledWith("Could not reset registration settings."); + }); + }); + describe("onFileChange", () => { it("rejects a non-image file with an error and leaves the existing logo untouched", () => { completeLoad(); @@ -638,16 +729,26 @@ describe("AdminSettingsComponent wiring", () => { it("gives every switch its own setting, in template order", () => { // The point of the test: workflow_enabled/workflows_enabled and dataset_enabled/ // datasets_enabled are one character apart, and a swap between them is invisible on screen. - expect(switches().length).toBe(SWITCH_KEYS.length); + // The Registration card's invite-only switch renders after every tab switch. + expect(switches().length).toBe(SWITCH_KEYS.length + 1); + const inviteOnlySwitch = SWITCH_KEYS.length; SWITCH_KEYS.forEach((key, i) => { SWITCH_KEYS.forEach(k => ((component.sidebarTabs as any)[k] = false)); + component.inviteOnly = false; switches()[i].triggerEventHandler("ngModelChange", true); const flipped = SWITCH_KEYS.filter(k => (component.sidebarTabs as any)[k]); expect(flipped).toEqual([key]); + expect(component.inviteOnly).toBe(false); }); + + SWITCH_KEYS.forEach(k => ((component.sidebarTabs as any)[k] = false)); + switches()[inviteOnlySwitch].triggerEventHandler("ngModelChange", true); + + expect(component.inviteOnly).toBe(true); + expect(SWITCH_KEYS.filter(k => (component.sidebarTabs as any)[k])).toEqual([]); }); it("locks the Hub children until Hub itself is on", () => { @@ -723,9 +824,10 @@ describe("AdminSettingsComponent wiring", () => { saveTabs: vi.spyOn(component, "saveTabs").mockImplementation(() => {}), saveUploadSettings: vi.spyOn(component, "saveUploadSettings").mockImplementation(() => {}), saveCsvSettings: vi.spyOn(component, "saveCsvSettings").mockImplementation(() => {}), + saveRegistrationSettings: vi.spyOn(component, "saveRegistrationSettings").mockImplementation(() => {}), }; const saves = buttonsLabelled("Save"); - expect(saves.length).toBe(2 + component.uploadGroups.length + 1); + expect(saves.length).toBe(2 + component.uploadGroups.length + 2); saves.forEach(b => b.click()); @@ -734,6 +836,7 @@ describe("AdminSettingsComponent wiring", () => { // Each upload card passes its own group, so the two cards cannot save each other's keys. expect(spies.saveUploadSettings.mock.calls.map(call => call[0])).toEqual(component.uploadGroups); expect(spies.saveCsvSettings).toHaveBeenCalledTimes(1); + expect(spies.saveRegistrationSettings).toHaveBeenCalledTimes(1); }); it("routes each card's Reset to that card's own handler", () => { @@ -742,9 +845,10 @@ describe("AdminSettingsComponent wiring", () => { resetTabs: vi.spyOn(component, "resetTabs").mockImplementation(() => {}), resetUploadSettings: vi.spyOn(component, "resetUploadSettings").mockImplementation(() => {}), resetCsvSettings: vi.spyOn(component, "resetCsvSettings").mockImplementation(() => {}), + resetRegistrationSettings: vi.spyOn(component, "resetRegistrationSettings").mockImplementation(() => {}), }; const resets = buttonsLabelled("Reset"); - expect(resets.length).toBe(2 + component.uploadGroups.length + 1); + expect(resets.length).toBe(2 + component.uploadGroups.length + 2); resets.forEach(b => b.click()); @@ -752,6 +856,7 @@ describe("AdminSettingsComponent wiring", () => { expect(spies.resetTabs).toHaveBeenCalledTimes(1); expect(spies.resetUploadSettings.mock.calls.map(call => call[0])).toEqual(component.uploadGroups); expect(spies.resetCsvSettings).toHaveBeenCalledTimes(1); + expect(spies.resetRegistrationSettings).toHaveBeenCalledTimes(1); }); }); diff --git a/frontend/src/app/hub/component/login/texera-login.component.spec.ts b/frontend/src/app/hub/component/login/texera-login.component.spec.ts index 6a25580bb20..66a2ea9a7f5 100644 --- a/frontend/src/app/hub/component/login/texera-login.component.spec.ts +++ b/frontend/src/app/hub/component/login/texera-login.component.spec.ts @@ -33,6 +33,7 @@ import { MockGuiConfigService } from "../../../common/service/gui-config.service import { commonTestProviders } from "../../../common/testing/test-utils"; import { USER_WORKFLOW } from "../../../app-routing.constant"; import { ORCID_STATE_KEY } from "../../../common/service/user/orcid-auth.service"; +import { Role, User } from "../../../common/type/user"; import { By } from "@angular/platform-browser"; import { NzIconDirective } from "ng-zorro-antd/icon"; import { NzTabsComponent } from "ng-zorro-antd/tabs"; @@ -56,6 +57,7 @@ describe("TexeraLoginComponent", () => { authState$ = new Subject(); userServiceMock = { isLogin: vi.fn().mockReturnValue(false), + getCurrentUser: vi.fn().mockReturnValue(undefined), login: vi.fn().mockReturnValue(of(undefined)), register: vi.fn().mockReturnValue(of({ verificationRequired: false })), registerVerify: vi.fn().mockReturnValue(of(undefined)), @@ -347,6 +349,54 @@ describe("TexeraLoginComponent", () => { expect(notificationServiceMock.success).toHaveBeenCalled(); }); + const fillSignup = () => + component.form.patchValue({ + username: "alice", + email: "alice@example.com", + password: "secret1", + confirm: "secret1", + }); + const signedInAs = (role: Role) => + (userServiceMock.getCurrentUser as any).mockReturnValue({ uid: 7, name: "alice", role } as User); + + // With invite-only off the account is REGULAR and registering has already signed the user in, + // so the page goes where a sign-in would rather than telling them to wait for an admin. + it("opens the dashboard when the new account can be used at once", () => { + signedInAs(Role.REGULAR); + fillSignup(); + + component.submit(); + + expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); + expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + }); + + // With invite-only on the account is INACTIVE, and signing in with it signs straight back out. + it("asks the user to wait for an admin when the new account is not signed in", () => { + fillSignup(); + + component.submit(); + + expect(notificationServiceMock.success).toHaveBeenCalledWith( + "Your account has been created. Please contact the Texera administrator to activate your account." + ); + expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); + }); + + // A page loaded before an admin turned invite-only on still holds the old flag, and then keeps an + // INACTIVE session. That account can do nothing yet, so it is not sent to the dashboard. + it("does not open the dashboard for an INACTIVE account", () => { + signedInAs(Role.INACTIVE); + fillSignup(); + + component.submit(); + + expect(notificationServiceMock.success).toHaveBeenCalledWith( + "Your account has been created. Please contact the Texera administrator to activate your account." + ); + expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); + }); + // Where verification is on the code field is present from the outset, and mailing the code is // its own button. Signing up is then a single submit that carries the code, rather than a first // submit that silently sent mail and a second that completed. @@ -432,6 +482,30 @@ describe("TexeraLoginComponent", () => { expect(notificationServiceMock.success).toHaveBeenCalled(); }); + it("opens the dashboard once the code completes a sign-up that can be used at once", () => { + signedInAs(Role.REGULAR); + fillForm(); + component.form.patchValue({ code: "123456" }); + + component.submit(); + + expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); + expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + }); + + // The button only shows where the config says verification is on. A server that disagrees has + // just created the account outright, and that sign-up ends like any other. + it("ends the sign-up when the server created the account without a code", () => { + (userServiceMock.register as any).mockReturnValue(of({ verificationRequired: false })); + signedInAs(Role.REGULAR); + fillForm(); + + component.sendCode(); + + expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); + expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + }); + it("asks for the code rather than submitting an empty one", () => { fillForm(); @@ -743,12 +817,23 @@ describe("TexeraLoginComponent", () => { expect(input("email")).toBeTruthy(); expect(input("confirm")).toBeTruthy(); + // Invite-only is off in the default config, so there is no approval to wait for. expect(host().querySelector("p.hint")?.textContent?.replace(/\s+/g, " ").trim()).toBe( - "Password must be at least 6 characters. After registering, contact the Texera administrator to activate your account." + "Password must be at least 6 characters." ); expect(submitButton()?.textContent?.trim()).toBe("Sign up"); }); + it("says an admin has to activate the account while invite-only is on", () => { + (TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService).setConfig({ inviteOnly: true }); + component.setMode("signup"); + fixture.detectChanges(); + + expect(host().querySelector("p.hint")?.textContent?.replace(/\s+/g, " ").trim()).toBe( + "Password must be at least 6 characters. After registering, contact the Texera administrator to activate your account." + ); + }); + it("switches mode from the tab strip in both directions", () => { const tabs = fixture.debugElement.query(By.css("nz-tabs")); From b9d6f11ae99896520bdf1ccabed1de72adac1c70 Mon Sep 17 00:00:00 2001 From: Xinyuan Lin Date: Mon, 16 Nov 2026 02:34:13 -0800 Subject: [PATCH 2/8] feat: honor invite-only at sign-up and add an admin switch --- .../web/resource/auth/AuthResource.scala | 43 +++++++++++++++---- .../auth/ExternalAuthProvisioner.scala | 12 +++++- bin/k8s/values-development.yaml | 2 + bin/k8s/values.yaml | 2 + .../org/apache/texera/auth/InviteOnly.scala | 39 +++++++++++++++++ common/config/src/main/resources/default.conf | 14 ++++++ .../src/main/resources/user-system.conf | 4 +- .../texera/common/config/DefaultsConfig.scala | 5 +++ .../common/config/UserSystemConfig.scala | 1 - .../org/apache/texera/dao/SiteSettings.scala | 4 ++ .../service/resource/ConfigResource.scala | 10 +++-- .../guide-for-developers.md | 6 ++- .../settings/admin-settings.component.html | 27 ++++++++++++ .../settings/admin-settings.component.ts | 34 +++++++++++++++ .../login/texera-login.component.html | 5 ++- .../component/login/texera-login.component.ts | 36 +++++++++++++--- 16 files changed, 216 insertions(+), 28 deletions(-) create mode 100644 common/auth/src/main/scala/org/apache/texera/auth/InviteOnly.scala diff --git a/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala index 3d3f4a49a6c..d85efcca39a 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala @@ -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 @@ -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("") + @@ -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()) @@ -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( @@ -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( @@ -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. @@ -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)) } @@ -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)) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala b/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala index a627e80a33c..6378ca159bb 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala @@ -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()) @@ -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) } @@ -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 } diff --git a/bin/k8s/values-development.yaml b/bin/k8s/values-development.yaml index 7ed9c532d19..362c62010ad 100644 --- a/bin/k8s/values-development.yaml +++ b/bin/k8s/values-development.yaml @@ -398,6 +398,8 @@ texeraEnvVars: value: "true" - name: COMPUTING_UNIT_SHARING_ENABLED value: "true" + # Only the starting value of Admin > Settings > Invite Only, stored when config-service first + # starts; after that the settings page owns it, and its Reset restores this value. - name: USER_SYS_INVITE_ONLY value: "true" # On by default; set to "false" to accept addresses unproven. This must agree with the diff --git a/bin/k8s/values.yaml b/bin/k8s/values.yaml index 661da84e43e..ba74316b12f 100644 --- a/bin/k8s/values.yaml +++ b/bin/k8s/values.yaml @@ -503,6 +503,8 @@ texeraEnvVars: value: "true" - name: COMPUTING_UNIT_SHARING_ENABLED value: "true" + # Only the starting value of Admin > Settings > Invite Only, stored when config-service first + # starts; after that the settings page owns it, and its Reset restores this value. - name: USER_SYS_INVITE_ONLY value: "true" # On by default; set to "false" to accept addresses unproven. This must agree with the diff --git a/common/auth/src/main/scala/org/apache/texera/auth/InviteOnly.scala b/common/auth/src/main/scala/org/apache/texera/auth/InviteOnly.scala new file mode 100644 index 00000000000..2fa5cf6f9bc --- /dev/null +++ b/common/auth/src/main/scala/org/apache/texera/auth/InviteOnly.scala @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.auth + +import org.apache.texera.common.config.DefaultsConfig +import org.apache.texera.dao.SiteSettings + +/** + * Whether a new account has to wait for an admin's approval before it can be used. + * + * The switch is the `invite_only` site setting, which admins flip on the Admin Settings page. It + * is read on every call, so a change reaches the next sign-up without a restart. default.conf's + * `user-sys.invite_only` (USER_SYS_INVITE_ONLY) seeds that row and stands in whenever the row is + * missing, unreadable or not a boolean. + */ +object InviteOnly { + + /** The `site_settings` key, which is also the default.conf leaf that seeds it. */ + val SettingKey = "invite_only" + + def enabled: Boolean = SiteSettings.getBoolean(SettingKey, DefaultsConfig.inviteOnly) +} diff --git a/common/config/src/main/resources/default.conf b/common/config/src/main/resources/default.conf index e815a27f9e2..6442ba07e43 100644 --- a/common/config/src/main/resources/default.conf +++ b/common/config/src/main/resources/default.conf @@ -117,6 +117,20 @@ model { model_multipart_upload_chunk_size_mib = ${?MODEL_MULTIPART_UPLOAD_CHUNK_SIZE_MIB} } +# Sign-up policy. Management-only like `operator` below: the login page reads the +# switch through /config/pre-login, so it stays out of the anonymous +# /config/settings/public whitelist. +user-sys { + # true: a new account is INACTIVE until an admin approves it on the Users page. + # false: a new account is REGULAR and usable as soon as it signs up. + # On by default: a REGULAR account can run code on the server, so open sign-up + # is a deployment's own choice. + # USER_SYS_INVITE_ONLY only seeds the setting; once the row exists, the Admin + # Settings page owns it (Reset there restores this value). + invite_only = true + invite_only = ${?USER_SYS_INVITE_ONLY} +} + # Operator-level defaults. These are management-only site settings (edited from # the admin page, read by the engine) and are deliberately NOT under # gui/dataset/model, so they stay out of the anonymous /config/settings/public diff --git a/common/config/src/main/resources/user-system.conf b/common/config/src/main/resources/user-system.conf index 312aaa6313d..657f88e4b39 100644 --- a/common/config/src/main/resources/user-system.conf +++ b/common/config/src/main/resources/user-system.conf @@ -71,8 +71,8 @@ user-sys { project-name = "Texera" project-name = ${?USER_SYS_PROJECT_NAME} - invite-only = false - invite-only = ${?USER_SYS_INVITE_ONLY} + # Invite-only lives in default.conf (user-sys.invite_only): admins switch it on the Admin + # Settings page, and USER_SYS_INVITE_ONLY seeds it. # Whether an address the user typed must be proved by a code mailed to it before it is accepted — # at registration, and when an account with no address on file supplies one. An address a provider diff --git a/common/config/src/main/scala/org/apache/texera/common/config/DefaultsConfig.scala b/common/config/src/main/scala/org/apache/texera/common/config/DefaultsConfig.scala index 3a00e8da5da..032612060a1 100644 --- a/common/config/src/main/scala/org/apache/texera/common/config/DefaultsConfig.scala +++ b/common/config/src/main/scala/org/apache/texera/common/config/DefaultsConfig.scala @@ -27,6 +27,11 @@ object DefaultsConfig { val reinit: Boolean = conf.getBoolean("config-service.always-reset-configurations-to-default-values") + // Typed rather than read off `allDefaults`: HOCON's parsing keeps the spellings + // USER_SYS_INVITE_ONLY has always accepted (yes/no, on/off), and an unreadable value stops + // config-service at startup, when it loads this object to seed site_settings. + val inviteOnly: Boolean = conf.getBoolean("user-sys.invite_only") + // site_settings rows are keyed by the last path segment of a HOCON key, so // this is the single place that turns a config path into a row key. private def shortKey(fullKey: String): String = fullKey.split("\\.").last diff --git a/common/config/src/main/scala/org/apache/texera/common/config/UserSystemConfig.scala b/common/config/src/main/scala/org/apache/texera/common/config/UserSystemConfig.scala index 18ee4dea670..f13471d27bc 100644 --- a/common/config/src/main/scala/org/apache/texera/common/config/UserSystemConfig.scala +++ b/common/config/src/main/scala/org/apache/texera/common/config/UserSystemConfig.scala @@ -37,7 +37,6 @@ object UserSystemConfig { val appleClientId: String = conf.getString("user-sys.apple.clientId") val gmail: String = conf.getString("user-sys.google.smtp.gmail") val smtpPassword: String = conf.getString("user-sys.google.smtp.password") - val inviteOnly: Boolean = conf.getBoolean("user-sys.invite-only") val emailVerification: Boolean = conf.getBoolean("user-sys.email-verification") val projectName: String = conf.getString("user-sys.project-name") val workflowVersionCollapseIntervalInMinutes: Int = diff --git a/common/dao/src/main/scala/org/apache/texera/dao/SiteSettings.scala b/common/dao/src/main/scala/org/apache/texera/dao/SiteSettings.scala index d818f0f056f..303e69fe5b1 100644 --- a/common/dao/src/main/scala/org/apache/texera/dao/SiteSettings.scala +++ b/common/dao/src/main/scala/org/apache/texera/dao/SiteSettings.scala @@ -46,6 +46,10 @@ object SiteSettings { def getLong(key: String, default: => Long): Long = readAndParse(key, default)(_.toLong) + /** `true` or `false` in any case; any other value is unparsable and yields `default`. */ + def getBoolean(key: String, default: => Boolean): Boolean = + readAndParse(key, default)(_.toBoolean) + /** Insert or overwrite the row for `key`, stamping who/when. */ def upsert(ctx: DSLContext, key: String, value: String, updatedBy: String): Unit = ctx diff --git a/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala b/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala index ab8eaa90301..4508fa9745e 100644 --- a/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala +++ b/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala @@ -24,7 +24,7 @@ import io.dropwizard.auth.Auth import jakarta.annotation.security.{PermitAll, RolesAllowed} import jakarta.ws.rs.core.{MediaType, Response} import jakarta.ws.rs.{Consumes, GET, POST, PUT, Path, PathParam, Produces} -import org.apache.texera.auth.SessionUser +import org.apache.texera.auth.{InviteOnly, SessionUser} import org.apache.texera.common.config.{ ApplicationConfig, ComputingUnitConfig, @@ -72,7 +72,9 @@ class ConfigResource { ), "attributionEnabled" -> GuiConfig.guiAttributionEnabled, "deploymentVersionCheckEnabled" -> GuiConfig.guiDeploymentVersionCheckEnabled, - "inviteOnly" -> UserSystemConfig.inviteOnly, + // Read per request: admins switch it on the settings page, and the login flow uses it to + // decide whether an INACTIVE sign-in sees the pending-approval screen. + "inviteOnly" -> InviteOnly.enabled, // The sign-up form decides whether to expect a code step before anyone has a token, so this // has to be readable anonymously. "emailVerification" -> UserSystemConfig.emailVerification @@ -122,8 +124,8 @@ class ConfigResource { @Path("/user-system") def getUserSystemConfig: Map[String, Any] = Map( - // flags from the user-system.conf - "inviteOnly" -> UserSystemConfig.inviteOnly + // the admin-editable invite_only site setting + "inviteOnly" -> InviteOnly.enabled ) // The site_settings keys that non-admin pages consume: dashboard branding, diff --git a/docs/contribution-guidelines/guide-for-developers.md b/docs/contribution-guidelines/guide-for-developers.md index 5a58c22a950..d595776baf5 100644 --- a/docs/contribution-guidelines/guide-for-developers.md +++ b/docs/contribution-guidelines/guide-for-developers.md @@ -307,8 +307,10 @@ Note: Jooq creates DAO for simple operations if the requested SQL query is compl ### Disable password login Edit `common/config/src/main/resources/gui.conf`, change `local-login` to `false`. -### Enforce invite only -Edit `common/config/src/main/resources/user-system.conf`, change `invite-only` to `true`. +### Invite-only sign-up +Invite-only is on by default: a new account stays inactive until an admin approves it on the **Users** page. To let new accounts in at once, sign in as an admin, open **Admin → Settings**, turn off **Invite Only** under **Registration**, and click **Save**. Accounts that sign up while it is off can run their own code in workflows. + +`USER_SYS_INVITE_ONLY` (or `invite_only` in `common/config/src/main/resources/default.conf`) only sets the starting value, which config-service stores the first time it starts. After that the settings page owns it, and its **Reset** button restores the configured value. ### Backend endpoints Role Annotation There are two types of permissions for the backend endpoints: diff --git a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.html b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.html index 0c4b2e0c0a4..982750eda13 100644 --- a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.html +++ b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.html @@ -399,3 +399,30 @@

General Settings

+ + +
+ Invite Only: + +
+
+ When on, a new account stays inactive until an admin approves it on the Users page. When off, anyone who signs up + gets a regular account right away, and regular accounts can run their own code in workflows. Accounts already + waiting for approval stay inactive until you approve them. +
+ +
+ + +
+
diff --git a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.ts b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.ts index c91a15141cb..22f8b29cc1f 100644 --- a/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.ts +++ b/frontend/src/app/dashboard/component/admin/settings/admin-settings.component.ts @@ -124,6 +124,10 @@ export class AdminSettingsComponent implements OnInit { csvMaxColumns: number = 512; + // Whether a new account waits for an admin's approval (the `invite_only` setting). On is the + // default and the safe side, since Save writes whatever the switch shows. + inviteOnly: boolean = true; + // S3 Multipart Upload Constraints readonly MIN_PART_SIZE_MiB = 5; // 5 MiB minimum for parts (except last part) readonly MAX_PART_SIZE_MiB = 5120; // 5 GiB maximum per part (5 * 1024 MiB) @@ -176,6 +180,9 @@ export class AdminSettingsComponent implements OnInit { form.chunkSizeMiB = parseIntOrDefault(settings[endpoint.chunkSizeSettingKey], form.chunkSizeMiB); }); this.csvMaxColumns = parseIntOrDefault(settings["csv_parser_max_columns"], this.csvMaxColumns); + // Only an explicit false opens sign-up on the backend, which reads the row trimmed and + // case-insensitively and falls back to on for anything it cannot read. + this.inviteOnly = (settings["invite_only"] ?? "").trim().toLowerCase() !== "false"; this.settingsLoaded = true; }, error: () => this.message.error("Failed to load settings."), @@ -360,4 +367,31 @@ export class AdminSettingsComponent implements OnInit { this.notificationService.info("Resetting result panel settings..."); setTimeout(() => window.location.reload(), this.RELOAD_DELAY); } + + saveRegistrationSettings(): void { + // Without a completed load the switch shows its initializer rather than the stored value. + if (!this.settingsLoaded) { + this.message.error("Settings have not loaded; refresh before saving."); + return; + } + this.adminSettingsService + .updateSetting("invite_only", this.inviteOnly.toString()) + .pipe(untilDestroyed(this)) + .subscribe({ + next: () => this.notificationService.success("Registration settings saved."), + error: () => this.notificationService.error("Could not save registration settings."), + }); + } + + resetRegistrationSettings(): void { + this.adminSettingsService + .resetSetting("invite_only") + .pipe(untilDestroyed(this)) + .subscribe({ + error: () => this.notificationService.error("Could not reset registration settings."), + }); + + this.notificationService.info("Resetting registration settings..."); + setTimeout(() => window.location.reload(), this.RELOAD_DELAY); + } } diff --git a/frontend/src/app/hub/component/login/texera-login.component.html b/frontend/src/app/hub/component/login/texera-login.component.html index 7afcbc0056c..40b9da2f98d 100644 --- a/frontend/src/app/hub/component/login/texera-login.component.html +++ b/frontend/src/app/hub/component/login/texera-login.component.html @@ -141,8 +141,9 @@ nz-typography nzType="secondary" class="hint"> - Password must be at least 6 characters. After registering, contact the Texera administrator to activate your - account. + Password must be at least 6 characters. @if (config.env.inviteOnly) { + After registering, contact the Texera administrator to activate your account. + }