From f8537bc067762908cf8f7857f7934dddea11a46c Mon Sep 17 00:00:00 2001 From: Sebastian Stehle Date: Tue, 10 Nov 2026 18:24:01 +0100 Subject: [PATCH] Fix (#1374) --- backend/i18n/frontend_de.json | 7 ++ backend/i18n/frontend_en.json | 7 ++ backend/i18n/frontend_fr.json | 7 ++ backend/i18n/frontend_it.json | 7 ++ backend/i18n/frontend_nl.json | 7 ++ backend/i18n/frontend_pt.json | 7 ++ backend/i18n/frontend_zh.json | 7 ++ backend/i18n/source/backend_de.json | 3 + backend/i18n/source/backend_en.json | 3 + backend/i18n/source/frontend_de.json | 7 ++ backend/i18n/source/frontend_en.json | 7 ++ .../Apps/Entities/Teams/EFTeamRepository.cs | 7 +- .../Entities/Teams/MongoTeamRepository.cs | 7 +- .../Teams/Team.cs | 23 +++++- .../Squidex.Domain.Apps.Entities.csproj | 1 + .../Teams/AuthDomainRecord.cs | 23 ++++++ .../Teams/Commands/VerifyAuthDomain.cs | 12 +++ .../Teams/DnsAuthDomainVerifier.cs | 34 +++++++++ .../Teams/DomainObject/Guards/GuardTeam.cs | 34 +++++++++ .../DomainObject/TeamDomainObject.State.cs | 4 + .../Teams/DomainObject/TeamDomainObject.cs | 20 +++++ .../Teams/IAuthDomainVerifier.cs | 16 ++++ .../Teams/Indexes/TeamsIndex.cs | 2 +- .../Teams/TeamAuthDomainVerified.cs | 13 ++++ backend/src/Squidex.Shared/Texts.de.resx | 9 +++ backend/src/Squidex.Shared/Texts.fr.resx | 9 +++ backend/src/Squidex.Shared/Texts.it.resx | 9 +++ backend/src/Squidex.Shared/Texts.nl.resx | 9 +++ backend/src/Squidex.Shared/Texts.pt.resx | 9 +++ backend/src/Squidex.Shared/Texts.resx | 9 +++ backend/src/Squidex.Shared/Texts.zh.resx | 9 +++ .../Teams/Models/AuthSchemeResponseDto.cs | 33 +++++++- .../Api/Controllers/Teams/TeamsController.cs | 24 ++++++ .../Config/Dynamic/DynamicSchemeProvider.cs | 31 +++++--- .../Controllers/Account/AccountController.cs | 7 ++ .../Config/Authentication/GithubHandler.cs | 2 + .../Config/Authentication/GoogleHandler.cs | 17 +++++ .../Config/Authentication/MicrosoftHandler.cs | 35 +++++++++ .../Config/Authentication/OidcHandler.cs | 46 ++++++++++- .../Authentication/VerifiedEmailExtensions.cs | 40 ++++++++++ .../Squidex/Config/Domain/CommandsServices.cs | 4 + .../src/Squidex/Config/MyIdentityOptions.cs | 2 + backend/src/Squidex/appsettings.json | 3 + .../Shared/TeamRepositoryTests.cs | 35 +++++++++ .../Model/Teams/Team.json | 1 + .../Model/Teams/TeamTests.cs | 49 ++++++++++++ .../DomainObject/Guards/GuardTeamTests.cs | 55 ++++++++++++++ .../DomainObject/TeamDomainObjectTests.cs | 35 +++++++++ .../Teams/Indexes/TeamsIndexTests.cs | 19 ++++- ...te_events_and_add_contributor.verified.txt | 1 + ...create_events_and_update_plan.verified.txt | 1 + ...ould_reset_plan_for_free_plan.verified.txt | 1 + ...create_events_and_update_plan.verified.txt | 1 + ..._billing_manager_for_callback.verified.txt | 1 + ...ke_update_for_redirect_result.verified.txt | 1 + ...ould_reset_plan_for_free_plan.verified.txt | 1 + ...events_and_set_intitial_state.verified.txt | 1 + ..._assign_client_as_contributor.verified.txt | 1 + ...vents_and_update_deleted_flag.verified.txt | 1 + ...events_and_remove_contributor.verified.txt | 1 + ..._update_label_and_description.verified.txt | 1 + ...eate_events_and_remove_scheme.verified.txt | 1 + ...eate_events_and_update_scheme.verified.txt | 1 + ...eate_events_and_verify_domain.verified.txt | 41 ++++++++++ .../teams/pages/auth/auth-page.component.html | 42 ++++++++++ .../teams/pages/auth/auth-page.component.scss | 6 +- .../teams/pages/auth/auth-page.component.ts | 18 +++++ .../teams/state/team-auth.state.spec.ts | 33 +++++++- .../features/teams/state/team-auth.state.ts | 76 +++++++++++++++---- frontend/src/app/shared/model/custom.ts | 4 + frontend/src/app/shared/model/generated.ts | 22 ++++++ .../app/shared/services/teams.service.spec.ts | 47 ++++++++++++ .../src/app/shared/services/teams.service.ts | 12 +++ 73 files changed, 1037 insertions(+), 44 deletions(-) create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs create mode 100644 backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs create mode 100644 backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs create mode 100644 backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs create mode 100644 backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt diff --git a/backend/i18n/frontend_de.json b/backend/i18n/frontend_de.json index fd61a8e48..5f6dfd6f2 100644 --- a/backend/i18n/frontend_de.json +++ b/backend/i18n/frontend_de.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domäne", "teams.auth.domainHint": "Die Domäne wird verwendet, um Ihre Benutzer zu identifizieren. Wenn sie ihre E-Mail-Adresse eingeben und die Domäne mit Ihren Einstellungen übereinstimmt, werden sie zu Ihrem Authentifizierungsserver weitergeleitet.", "teams.auth.domainHintEmail": "E-Mail-Format", + "teams.auth.notVerifiedHint": "Ihre Benutzer können sich erst mit diesem Server anmelden, nachdem Sie bestätigt haben, dass Ihnen die Domäne gehört. Fügen Sie den folgenden DNS-TXT-Eintrag zu Ihrer Domäne hinzu und klicken Sie auf Bestätigen.", "teams.auth.redirectUrl": "Weiterleitungs-URL", "teams.auth.redirectUrlHint": "Sie müssen diese URL in Ihrem Authentifizierungsserver zulassen.", "teams.auth.reloaded": "Authentifizierungseinstellung neu geladen.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Testanmeldung", "teams.auth.use": "Benutzerdefinierter OIDC-Server", "teams.auth.useHint": "Verwenden Sie eine Single-Sign-On (SSO)-Lösung, um Squidex mit Ihrer Infrastruktur zu verbinden. Ihre Mitarbeiter und Kollegen können sich mit ihrem normalen Geschäftskonto verbinden.", + "teams.auth.verificationRecordName": "Eintragsname", + "teams.auth.verificationRecordValue": "Eintragswert", + "teams.auth.verified": "Domäne bestätigt.", + "teams.auth.verifiedHint": "Die Inhaberschaft der Domäne wurde bestätigt.", + "teams.auth.verify": "Domäne bestätigen", + "teams.auth.verifyFailed": "Die Domäne konnte nicht bestätigt werden. Bitte neu laden.", "teams.create": "Erstellen", "teams.createFailed": "Fehler beim Erstellen des Teams. Bitte neu laden.", "teams.delete": "Team löschen", diff --git a/backend/i18n/frontend_en.json b/backend/i18n/frontend_en.json index 598571b3c..70e5a6444 100644 --- a/backend/i18n/frontend_en.json +++ b/backend/i18n/frontend_en.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Create", "teams.createFailed": "Failed to create team. Please reload.", "teams.delete": "Delete Team", diff --git a/backend/i18n/frontend_fr.json b/backend/i18n/frontend_fr.json index 02d8ade94..57623d793 100644 --- a/backend/i18n/frontend_fr.json +++ b/backend/i18n/frontend_fr.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Créer", "teams.createFailed": "Échec de la création de l'équipe. Veuillez recharger.", "teams.delete": "Delete Team", diff --git a/backend/i18n/frontend_it.json b/backend/i18n/frontend_it.json index 96ae3b83e..71e6dfd7a 100644 --- a/backend/i18n/frontend_it.json +++ b/backend/i18n/frontend_it.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Create", "teams.createFailed": "Failed to create team. Please reload.", "teams.delete": "Delete Team", diff --git a/backend/i18n/frontend_nl.json b/backend/i18n/frontend_nl.json index 3ddeab64b..ddbddd391 100644 --- a/backend/i18n/frontend_nl.json +++ b/backend/i18n/frontend_nl.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Create", "teams.createFailed": "Failed to create team. Please reload.", "teams.delete": "Delete Team", diff --git a/backend/i18n/frontend_pt.json b/backend/i18n/frontend_pt.json index 383d8613e..53ec4c9b2 100644 --- a/backend/i18n/frontend_pt.json +++ b/backend/i18n/frontend_pt.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Criar", "teams.createFailed": "Falhou na criação de uma equipa. Por favor, recarregue.", "teams.delete": "Delete Team", diff --git a/backend/i18n/frontend_zh.json b/backend/i18n/frontend_zh.json index 3be1b015a..3e97341c0 100644 --- a/backend/i18n/frontend_zh.json +++ b/backend/i18n/frontend_zh.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Create", "teams.createFailed": "Failed to create team. Please reload.", "teams.delete": "Delete Team", diff --git a/backend/i18n/source/backend_de.json b/backend/i18n/source/backend_de.json index 4d9704ef5..224cf482a 100644 --- a/backend/i18n/source/backend_de.json +++ b/backend/i18n/source/backend_de.json @@ -336,6 +336,8 @@ "setup.ruleUrl.success": "Herzlichen Glückwunsch, die Umgebungsvariable `URLS__BASEURL` ist korrekt konfiguriert. Diese Variable muss auf die öffentliche URL zeigen, unter der Ihre Squidex-Instanz verfügbar ist.", "setup.title": "Installation", "teams.appsAssigned": "Team kann nicht gelöscht werden, wenn Apps zugewiesen sind.", + "teams.authDomainNotConfigured": "Es ist keine Authentifizierungsdomain konfiguriert.", + "teams.authDomainNotVerified": "Der DNS-TXT-Eintrag '{name}' mit dem Wert '{value}' wurde nicht gefunden.", "teams.domainInUse": "Die Domain wird bereits für ein anderes Team verwendet.", "users.accessDenied.text": "Diese Operation ist nicht erlaubt, Ihr Konto könnte gesperrt sein.", "users.accessDenied.title": "Zugriff verweigert", @@ -350,6 +352,7 @@ "users.consent.piiText": "Ich verstehe und stimme zu, dass Squidex die folgenden privaten Informationen sammelt, die von externen Authentifizierungsanbietern wie Google, Microsoft oder Github abgerufen werden. ", "users.consent.title": "Zustimmung", "users.deleteYourselfError": "Sie können sich nicht selbst löschen.", + "users.emailNotVerified": "Der Authentifizierungsanbieter hat Ihre E-Mail-Adresse nicht bestätigt.", "users.error.headline": "Operation fehlgeschlagen", "users.error.text": "Es tut uns wirklich leid, dass etwas schief gelaufen ist.", "users.error.title": "Fehler", diff --git a/backend/i18n/source/backend_en.json b/backend/i18n/source/backend_en.json index dc53b2771..33498cee9 100644 --- a/backend/i18n/source/backend_en.json +++ b/backend/i18n/source/backend_en.json @@ -340,6 +340,8 @@ "setup.ruleUrl.success": "Congratulations, the URLS__BASEURL environment variable is configured properly. This variable must point to the public URL under which your Squidex instance is available.", "setup.title": "Installation", "teams.appsAssigned": "Cannot delete team, when apps are assigned.", + "teams.authDomainNotConfigured": "No authentication domain is configured.", + "teams.authDomainNotVerified": "The DNS TXT record '{name}' with the value '{value}' has not been found.", "teams.domainInUse": "Domain is already used for another team.", "users.accessDenied.text": "This operation is not allowed, your account might be locked.", "users.accessDenied.title": "Access denied", @@ -354,6 +356,7 @@ "users.consent.piiText": "I understand and agree that Squidex collects the following private information that are retrieved from external authentication providers such as Google, Microsoft or Github. ", "users.consent.title": "Consent", "users.deleteYourselfError": "You cannot delete yourself.", + "users.emailNotVerified": "The authentication provider has not verified your email address.", "users.error.headline": "Operation failed", "users.error.text": "We are really sorry that something went wrong.", "users.error.title": "Error", diff --git a/backend/i18n/source/frontend_de.json b/backend/i18n/source/frontend_de.json index 6e2614ab9..73a462719 100644 --- a/backend/i18n/source/frontend_de.json +++ b/backend/i18n/source/frontend_de.json @@ -1128,6 +1128,7 @@ "teams.auth.domain": "Domäne", "teams.auth.domainHint": "Die Domäne wird verwendet, um Ihre Benutzer zu identifizieren. Wenn sie ihre E-Mail-Adresse eingeben und die Domäne mit Ihren Einstellungen übereinstimmt, werden sie zu Ihrem Authentifizierungsserver weitergeleitet.", "teams.auth.domainHintEmail": "E-Mail-Format", + "teams.auth.notVerifiedHint": "Ihre Benutzer können sich erst mit diesem Server anmelden, nachdem Sie bestätigt haben, dass Ihnen die Domäne gehört. Fügen Sie den folgenden DNS-TXT-Eintrag zu Ihrer Domäne hinzu und klicken Sie auf Bestätigen.", "teams.auth.redirectUrl": "Weiterleitungs-URL", "teams.auth.redirectUrlHint": "Sie müssen diese URL in Ihrem Authentifizierungsserver zulassen.", "teams.auth.reloaded": "Authentifizierungseinstellung neu geladen.", @@ -1135,6 +1136,12 @@ "teams.auth.testLogin": "Testanmeldung", "teams.auth.use": "Benutzerdefinierter OIDC-Server", "teams.auth.useHint": "Verwenden Sie eine Single-Sign-On (SSO)-Lösung, um Squidex mit Ihrer Infrastruktur zu verbinden. Ihre Mitarbeiter und Kollegen können sich mit ihrem normalen Geschäftskonto verbinden.", + "teams.auth.verificationRecordName": "Eintragsname", + "teams.auth.verificationRecordValue": "Eintragswert", + "teams.auth.verified": "Domäne bestätigt.", + "teams.auth.verifiedHint": "Die Inhaberschaft der Domäne wurde bestätigt.", + "teams.auth.verify": "Domäne bestätigen", + "teams.auth.verifyFailed": "Die Domäne konnte nicht bestätigt werden. Bitte neu laden.", "teams.create": "Erstellen", "teams.createFailed": "Fehler beim Erstellen des Teams. Bitte neu laden.", "teams.delete": "Team löschen", diff --git a/backend/i18n/source/frontend_en.json b/backend/i18n/source/frontend_en.json index 598571b3c..70e5a6444 100644 --- a/backend/i18n/source/frontend_en.json +++ b/backend/i18n/source/frontend_en.json @@ -1217,6 +1217,7 @@ "teams.auth.domain": "Domain", "teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.", "teams.auth.domainHintEmail": "Email Format", + "teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.", "teams.auth.redirectUrl": "Redirect URL", "teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.", "teams.auth.reloaded": "Auth setting reloaded.", @@ -1224,6 +1225,12 @@ "teams.auth.testLogin": "Test Login", "teams.auth.use": "Custom OIDC Server", "teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.", + "teams.auth.verificationRecordName": "Record Name", + "teams.auth.verificationRecordValue": "Record Value", + "teams.auth.verified": "Domain verified.", + "teams.auth.verifiedHint": "The ownership of the domain has been verified.", + "teams.auth.verify": "Verify Domain", + "teams.auth.verifyFailed": "Failed to verify domain. Please reload.", "teams.create": "Create", "teams.createFailed": "Failed to create team. Please reload.", "teams.delete": "Delete Team", diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs index 143b3664e..a546b9030 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs @@ -59,13 +59,14 @@ public sealed class EFTeamRepository(IDbContextFactory dbCon { await using var dbContext = await CreateDbContextAsync(ct); - var entity = + var entities = await dbContext.Set() .Where(x => x.IndexedAuthDomain == authDomain) .Where(x => !x.IndexedDeleted) - .FirstOrDefaultAsync(ct); + .ToListAsync(ct); - return entity?.Document; + // Several teams can use the same domain, but only one of them can verify it. + return entities.Select(x => x.Document).FirstOrDefault(x => x.IsAuthDomainVerified); } } diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs index 0d74e2971..5b011f4c6 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs @@ -62,11 +62,12 @@ public sealed class MongoTeamRepository(IMongoDatabase database) : MongoSnapshot { using (Telemetry.Activities.StartActivity("MongoTeamRepository/FindByAuthDomainAsync")) { - var entity = + var entities = await Collection.Find(x => x.IndexedAuthDomain == authDomain && !x.IndexedDeleted) - .FirstOrDefaultAsync(ct); + .ToListAsync(ct); - return entity?.Document; + // Several teams can use the same domain, but only one of them can verify it. + return entities.Select(x => x.Document).FirstOrDefault(x => x.IsAuthDomainVerified); } } } diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs b/backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs index 287b3d661..7998824e7 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs @@ -21,6 +21,8 @@ public record Team : Entity public AuthScheme? AuthScheme { get; init; } + public bool IsAuthDomainVerified { get; init; } + public bool IsDeleted { get; init; } [Pure] @@ -55,7 +57,26 @@ public record Team : Entity return this; } - return this with { AuthScheme = authScheme }; + // The verification is only valid for the domain that has been verified. + var isVerified = IsAuthDomainVerified && string.Equals(authScheme?.Domain, AuthScheme?.Domain, StringComparison.OrdinalIgnoreCase); + + return this with { AuthScheme = authScheme, IsAuthDomainVerified = isVerified }; + } + + [Pure] + public Team VerifyAuthDomain(string domain) + { + if (IsAuthDomainVerified) + { + return this; + } + + if (!string.Equals(domain, AuthScheme?.Domain, StringComparison.OrdinalIgnoreCase)) + { + return this; + } + + return this with { IsAuthDomainVerified = true }; } [Pure] diff --git a/backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj b/backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj index a3219f09d..c98b80548 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj +++ b/backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj @@ -29,6 +29,7 @@ + diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs new file mode 100644 index 000000000..717f82597 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs @@ -0,0 +1,23 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Teams; + +public static class AuthDomainRecord +{ + public static string GetName(string domain) + { + return $"_squidex.{domain}"; + } + + public static string GetValue(DomainId teamId) + { + return $"squidex-team={teamId}"; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs new file mode 100644 index 000000000..165369245 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs @@ -0,0 +1,12 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Entities.Teams.Commands; + +public sealed class VerifyAuthDomain : TeamCommand +{ +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs new file mode 100644 index 000000000..b06363113 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs @@ -0,0 +1,34 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using DnsClient; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Teams; + +public sealed class DnsAuthDomainVerifier : IAuthDomainVerifier +{ + // Without the cache a record is found immediately after it has been added. + private readonly LookupClient lookupClient = new LookupClient(new LookupClientOptions { UseCache = false, ThrowDnsErrors = false }); + + public async Task IsVerifiedAsync(string domain, DomainId teamId, + CancellationToken ct = default) + { + var expected = AuthDomainRecord.GetValue(teamId); + + try + { + var response = await lookupClient.QueryAsync(AuthDomainRecord.GetName(domain), QueryType.TXT, cancellationToken: ct); + + return response.Answers.TxtRecords().SelectMany(x => x.Text).Any(x => string.Equals(x.Trim(), expected, StringComparison.Ordinal)); + } + catch (DnsResponseException) + { + return false; + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs index ee32e9908..e619c9ea6 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs @@ -5,6 +5,7 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using Squidex.Domain.Apps.Core.Teams; using Squidex.Domain.Apps.Entities.Billing; using Squidex.Domain.Apps.Entities.Teams.Commands; using Squidex.Infrastructure; @@ -122,6 +123,39 @@ public static class GuardTeam }); } + public static Task CanVerifyAuthDomain(VerifyAuthDomain command, Team team, IAppProvider appProvider, IAuthDomainVerifier verifier, + CancellationToken ct) + { + Guard.NotNull(command); + + return Validate.It(async e => + { + var domain = team.AuthScheme?.Domain; + + if (string.IsNullOrWhiteSpace(domain)) + { + e(T.Get("teams.authDomainNotConfigured")); + return; + } + + var existing = await appProvider.GetTeamByAuthDomainAsync(domain, ct); + + if (existing != null && existing.Id != command.TeamId) + { + e(T.Get("teams.domainInUse")); + return; + } + + if (!await verifier.IsVerifiedAsync(domain, command.TeamId, ct)) + { + var name = AuthDomainRecord.GetName(domain); + var value = AuthDomainRecord.GetValue(command.TeamId); + + e(T.Get("teams.authDomainNotVerified", new { name, value })); + } + }); + } + public static Task CanDelete(DeleteTeam command, IAppProvider appProvider, CancellationToken ct) { diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs index fc7a3c8d7..fdcea3c34 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs @@ -49,6 +49,10 @@ public partial class TeamDomainObject newSnapshot = snapshot.ChangeAuthScheme(e.Scheme); break; + case TeamAuthDomainVerified e: + newSnapshot = snapshot.VerifyAuthDomain(e.Domain); + break; + case TeamDeleted: newSnapshot = snapshot with { Plan = null, IsDeleted = true }; break; diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs index d3c5bac28..fa5c3af5a 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs @@ -111,6 +111,16 @@ public partial class TeamDomainObject( return Snapshot; }, ct); + case VerifyAuthDomain verifyAuthDomain: + return ApplyReturnAsync(verifyAuthDomain, async (c, ct) => + { + await GuardTeam.CanVerifyAuthDomain(c, Snapshot, AppProvider, AuthDomainVerifier, ct); + + VerifyAuthDomain(c); + + return Snapshot; + }, ct); + case DeleteTeam delete: return ApplyAsync(delete, async (c, ct) => { @@ -200,6 +210,11 @@ public partial class TeamDomainObject( Raise(command, new TeamAuthChanged()); } + private void VerifyAuthDomain(VerifyAuthDomain command) + { + Raise(command, new TeamAuthDomainVerified { Domain = Snapshot.AuthScheme!.Domain }); + } + private void AssignContributor(AssignContributor command, bool isAdded) { Raise(command, new TeamContributorAssigned { IsAdded = isAdded }); @@ -229,6 +244,11 @@ public partial class TeamDomainObject( get => serviceProvider.GetRequiredService(); } + private IAuthDomainVerifier AuthDomainVerifier + { + get => serviceProvider.GetRequiredService(); + } + private IBillingPlans BillingPlans { get => serviceProvider.GetRequiredService(); diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs new file mode 100644 index 000000000..df9a0b073 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs @@ -0,0 +1,16 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Teams; + +public interface IAuthDomainVerifier +{ + Task IsVerifiedAsync(string domain, DomainId teamId, + CancellationToken ct = default); +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs b/backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs index 34785da94..2beff2204 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs @@ -35,7 +35,7 @@ public sealed class TeamsIndex(ITeamRepository teamRepository) : ITeamsIndex var team = await teamRepository.FindByAuthDomainAsync(authDomain, ct); - return IsValid(team) ? team : null; + return IsValid(team) && team!.IsAuthDomainVerified ? team : null; } } diff --git a/backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs b/backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs new file mode 100644 index 000000000..fa5a90261 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs @@ -0,0 +1,13 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Events.Teams; + +public sealed class TeamAuthDomainVerified : TeamEvent +{ + public string Domain { get; set; } +} diff --git a/backend/src/Squidex.Shared/Texts.de.resx b/backend/src/Squidex.Shared/Texts.de.resx index c8f39aea0..899f3243f 100644 --- a/backend/src/Squidex.Shared/Texts.de.resx +++ b/backend/src/Squidex.Shared/Texts.de.resx @@ -1105,6 +1105,12 @@ Team kann nicht gelöscht werden, wenn Apps zugewiesen sind. + + Es ist keine Authentifizierungsdomain konfiguriert. + + + Der DNS-TXT-Eintrag '{name}' mit dem Wert '{value}' wurde nicht gefunden. + Die Domain wird bereits für ein anderes Team verwendet. @@ -1147,6 +1153,9 @@ Sie können sich nicht selbst löschen. + + Der Authentifizierungsanbieter hat Ihre E-Mail-Adresse nicht bestätigt. + Operation fehlgeschlagen diff --git a/backend/src/Squidex.Shared/Texts.fr.resx b/backend/src/Squidex.Shared/Texts.fr.resx index 49d5f8107..339cb1876 100644 --- a/backend/src/Squidex.Shared/Texts.fr.resx +++ b/backend/src/Squidex.Shared/Texts.fr.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ Vous ne pouvez pas vous supprimer. + + The authentication provider has not verified your email address. + L'opération a échoué diff --git a/backend/src/Squidex.Shared/Texts.it.resx b/backend/src/Squidex.Shared/Texts.it.resx index 6d6efe597..91ebf2c30 100644 --- a/backend/src/Squidex.Shared/Texts.it.resx +++ b/backend/src/Squidex.Shared/Texts.it.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ Non puoi cancellare te stesso. + + The authentication provider has not verified your email address. + Operazione non riuscita diff --git a/backend/src/Squidex.Shared/Texts.nl.resx b/backend/src/Squidex.Shared/Texts.nl.resx index 175fb3dff..a41f5a824 100644 --- a/backend/src/Squidex.Shared/Texts.nl.resx +++ b/backend/src/Squidex.Shared/Texts.nl.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ Je kan jezelf niet verwijderen. + + The authentication provider has not verified your email address. + Bewerking mislukt diff --git a/backend/src/Squidex.Shared/Texts.pt.resx b/backend/src/Squidex.Shared/Texts.pt.resx index 7f0084dcd..8236a007b 100644 --- a/backend/src/Squidex.Shared/Texts.pt.resx +++ b/backend/src/Squidex.Shared/Texts.pt.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ Não pode remover a si proprio. + + The authentication provider has not verified your email address. + Operação falhada diff --git a/backend/src/Squidex.Shared/Texts.resx b/backend/src/Squidex.Shared/Texts.resx index c60378d2b..a32f9bae3 100644 --- a/backend/src/Squidex.Shared/Texts.resx +++ b/backend/src/Squidex.Shared/Texts.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ You cannot delete yourself. + + The authentication provider has not verified your email address. + Operation failed diff --git a/backend/src/Squidex.Shared/Texts.zh.resx b/backend/src/Squidex.Shared/Texts.zh.resx index b2b3c6987..b77bd2c29 100644 --- a/backend/src/Squidex.Shared/Texts.zh.resx +++ b/backend/src/Squidex.Shared/Texts.zh.resx @@ -1105,6 +1105,12 @@ Cannot delete team, when apps are assigned. + + No authentication domain is configured. + + + The DNS TXT record '{name}' with the value '{value}' has not been found. + Domain is already used for another team. @@ -1147,6 +1153,9 @@ 你不能删除自己。 + + The authentication provider has not verified your email address. + 操作失败 diff --git a/backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs b/backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs index 78a7d4cea..a5fb92718 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs @@ -6,6 +6,7 @@ // ========================================================================== using Squidex.Domain.Apps.Core.Teams; +using Squidex.Domain.Apps.Entities.Teams; using Squidex.Web; namespace Squidex.Areas.Api.Controllers.Teams.Models; @@ -17,6 +18,21 @@ public class AuthSchemeResponseDto : Resource /// public AuthSchemeDto? Scheme { get; set; } + /// + /// True, if the ownership of the domain has been verified. + /// + public bool IsVerified { get; set; } + + /// + /// The name of the DNS TXT record to verify the ownership of the domain. + /// + public string? VerificationRecordName { get; set; } + + /// + /// The value of the DNS TXT record to verify the ownership of the domain. + /// + public string? VerificationRecordValue { get; set; } + public static AuthSchemeResponseDto FromDomain(Team team, Resources resources) { var result = new AuthSchemeResponseDto(); @@ -24,6 +40,9 @@ public class AuthSchemeResponseDto : Resource if (team.AuthScheme != null) { result.Scheme = AuthSchemeDto.FromDomain(team.AuthScheme); + result.IsVerified = team.IsAuthDomainVerified; + result.VerificationRecordName = AuthDomainRecord.GetName(team.AuthScheme.Domain); + result.VerificationRecordValue = AuthDomainRecord.GetValue(team.Id); } return result.CreateLinks(resources); @@ -35,10 +54,18 @@ public class AuthSchemeResponseDto : Resource AddSelfLink(resources.Url(x => nameof(x.GetTeamAuth), values)); - if (resources.CanChangeTeamAuth) + if (!resources.CanChangeTeamAuth) + { + return this; + } + + AddPutLink("update", + resources.Url(x => nameof(x.PutTeamAuth), values)); + + if (Scheme != null && !IsVerified) { - AddPutLink("update", - resources.Url(x => nameof(x.PutTeamAuth), values)); + AddPostLink("verify", + resources.Url(x => nameof(x.PostTeamAuthVerify), values)); } return this; diff --git a/backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs b/backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs index 5d11c081b..7beeb9fae 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs @@ -167,6 +167,30 @@ public sealed class TeamsController(ICommandBus commandBus, IAppProvider appProv return Ok(response); } + /// + /// Verify the ownership of the team auth domain with a DNS TXT record. + /// + /// The ID of the team. + /// Domain verified. + /// DNS record not found or domain used by another team. + /// Team not found. + [HttpPost] + [Route("teams/{team}/auth/verify")] + [ProducesResponseType(typeof(AuthSchemeResponseDto), StatusCodes.Status200OK)] + [ApiPermission(PermissionIds.TeamAuthChange)] + [ApiCosts(0)] + public async Task PostTeamAuthVerify(string team) + { + var command = new VerifyAuthDomain(); + + var response = await InvokeCommandAsync(command, x => + { + return AuthSchemeResponseDto.FromDomain(x, Resources); + }); + + return Ok(response); + } + /// /// Delete the team. /// diff --git a/backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs b/backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs index 2eafcc2a8..7752c395c 100644 --- a/backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs +++ b/backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs @@ -67,7 +67,7 @@ public sealed class DynamicSchemeProvider( var team = await appProvider.GetTeamByAuthDomainAsync(parts[1], default); if (team?.AuthScheme != null) { - return CreateScheme(team.Id.ToString(), team.AuthScheme).Scheme; + return CreateScheme(team.Id.ToString(), team.AuthScheme, true).Scheme; } return null; @@ -147,14 +147,22 @@ public sealed class DynamicSchemeProvider( return cached as SchemeResult; } - var scheme = - await GetSchemeByTeamAsync(name, ct) ?? - await GetSchemeByTempNameAsync(name, ct); + SchemeResult? result = null; - var result = - scheme != null ? - CreateScheme(name, scheme) : - null; + var teamScheme = await GetSchemeByTeamAsync(name, ct); + if (teamScheme != null) + { + result = CreateScheme(name, teamScheme, true); + } + else + { + var tempScheme = await GetSchemeByTempNameAsync(name, ct); + if (tempScheme != null) + { + // Temporary schemes can be created by anybody to test the configuration and are never trusted. + result = CreateScheme(name, tempScheme, false); + } + } if (httpContextAccessor.HttpContext != null) { @@ -169,7 +177,8 @@ public sealed class DynamicSchemeProvider( { var app = await appProvider.GetTeamAsync(DomainId.Create(name), ct); - return app?.AuthScheme; + // Unverified schemes could be used to sign in with emails of a domain that the team does not own. + return app?.IsAuthDomainVerified == true ? app.AuthScheme : null; } private async Task GetSchemeByTempNameAsync(string name, @@ -180,7 +189,7 @@ public sealed class DynamicSchemeProvider( return value != null ? jsonSerializer.Deserialize(new MemoryStream(value)) : null; } - private SchemeResult CreateScheme(string name, AuthScheme config) + private SchemeResult CreateScheme(string name, AuthScheme config, bool isTeamScheme) { var scheme = new AuthenticationScheme(name, config.DisplayName, typeof(DynamicOpenIdConnectHandler)); @@ -189,7 +198,7 @@ public sealed class DynamicSchemeProvider( Events = new OidcHandler(new MyIdentityOptions { OidcOnSignoutRedirectUrl = config.SignoutRedirectUrl, - }), + }, isTeamScheme, config.Domain ?? string.Empty), Authority = config.Authority, CallbackPath = new PathString($"/signin-{name}"), ClientId = config.ClientId, diff --git a/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs b/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs index c54064ee5..cf96eafd6 100644 --- a/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs +++ b/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Squidex.Areas.IdentityServer.Config; using Squidex.Config; +using Squidex.Config.Authentication; using Squidex.Domain.Users; using Squidex.Infrastructure; using Squidex.Infrastructure.Security; @@ -279,6 +280,12 @@ public sealed class AccountController( throw new DomainException(T.Get("users.noEmailAddress")); } + // Otherwise an attacker could squat an email address or claim the account of an invited user. + if (!login.Principal.IsEmailVerified()) + { + throw new DomainException(T.Get("users.emailNotVerified")); + } + user = await userService.FindByEmailAsync(email!, HttpContext.RequestAborted); // User might not have a login or password if the user got invited. diff --git a/backend/src/Squidex/Config/Authentication/GithubHandler.cs b/backend/src/Squidex/Config/Authentication/GithubHandler.cs index d23b5ed48..9f93b23fe 100644 --- a/backend/src/Squidex/Config/Authentication/GithubHandler.cs +++ b/backend/src/Squidex/Config/Authentication/GithubHandler.cs @@ -29,6 +29,8 @@ public sealed class GithubHandler : OAuthEvents throw new DomainException(T.Get("login.githubPrivateEmail")); } + context.Identity.SetEmailVerified(true); + return base.CreatingTicket(context); } } diff --git a/backend/src/Squidex/Config/Authentication/GoogleHandler.cs b/backend/src/Squidex/Config/Authentication/GoogleHandler.cs index 7c7446059..1d097ca81 100644 --- a/backend/src/Squidex/Config/Authentication/GoogleHandler.cs +++ b/backend/src/Squidex/Config/Authentication/GoogleHandler.cs @@ -7,6 +7,7 @@ using System.Security.Claims; using System.Text.Json; +using System.Text.Json.Serialization; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OAuth; using Squidex.Shared.Identity; @@ -56,6 +57,22 @@ public sealed class GoogleHandler : OAuthEvents context.Identity?.AddClaim(new Claim(SquidexClaimTypes.PictureUrl, pictureUrl)); } + var user = context.User.Deserialize(JsonSerializerOptions.Web); + + // The property name depends on the version of the user info endpoint. + var isVerified = user?.EmailVerified == true || user?.VerifiedEmail == true; + + context.Identity.SetEmailVerified(isVerified); + return base.CreatingTicket(context); } + + private sealed class GoogleUser + { + [JsonPropertyName("email_verified")] + public bool? EmailVerified { get; init; } + + [JsonPropertyName("verified_email")] + public bool? VerifiedEmail { get; init; } + } } diff --git a/backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs b/backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs index 30cc80f28..837bb96d4 100644 --- a/backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs +++ b/backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs @@ -42,6 +42,41 @@ public sealed class MicrosoftHandler : OAuthEvents context.Identity?.AddClaim(new Claim(SquidexClaimTypes.PictureUrl, pictureUrl)); } + UseUserPrincipalNameAsEmail(context); + return base.CreatingTicket(context); } + + private static void UseUserPrincipalNameAsEmail(OAuthCreatingTicketContext context) + { + var identity = context.Identity; + + if (identity == null) + { + return; + } + + // The 'mail' attribute can be set to any value by the admin of any tenant, therefore we cannot trust it. + foreach (var claim in identity.FindAll(ClaimTypes.Email).ToList()) + { + identity.RemoveClaim(claim); + } + + var upn = context.User.Deserialize(JsonSerializerOptions.Web)?.UserPrincipalName; + + // The UPN must use a domain that has been verified by the tenant. Guest accounts contain '#EXT#' and are not verified. + var isValid = !string.IsNullOrWhiteSpace(upn) && upn.Contains('@', StringComparison.Ordinal) && !upn.Contains('#', StringComparison.Ordinal); + + if (isValid) + { + identity.AddClaim(new Claim(ClaimTypes.Email, upn!)); + } + + identity.SetEmailVerified(isValid); + } + + private sealed class MicrosoftUser + { + public string? UserPrincipalName { get; init; } + } } diff --git a/backend/src/Squidex/Config/Authentication/OidcHandler.cs b/backend/src/Squidex/Config/Authentication/OidcHandler.cs index aa8ecfa5b..4d736f697 100644 --- a/backend/src/Squidex/Config/Authentication/OidcHandler.cs +++ b/backend/src/Squidex/Config/Authentication/OidcHandler.cs @@ -6,12 +6,14 @@ // ========================================================================== using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Squidex.Infrastructure.Security; using Squidex.Shared.Identity; namespace Squidex.Config.Authentication; -public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents +public sealed class OidcHandler(MyIdentityOptions options, bool trustEmails = true, string? emailDomain = null) : OpenIdConnectEvents { public override Task TokenValidated(TokenValidatedContext context) { @@ -34,6 +36,18 @@ public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents return base.TokenValidated(context); } + public override Task TicketReceived(TicketReceivedContext context) + { + var principal = context.Principal; + + if (principal != null) + { + (principal.Identity as ClaimsIdentity).SetEmailVerified(IsEmailVerified(principal)); + } + + return base.TicketReceived(context); + } + public override Task RedirectToIdentityProviderForSignOut(RedirectContext context) { if (!string.IsNullOrEmpty(options.OidcOnSignoutRedirectUrl)) @@ -48,4 +62,34 @@ public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents return base.RedirectToIdentityProviderForSignOut(context); } + + private bool IsEmailVerified(ClaimsPrincipal principal) + { + if (!trustEmails) + { + return false; + } + + var email = principal.GetEmail(); + + if (string.IsNullOrWhiteSpace(email)) + { + return false; + } + + // Dynamic providers can only vouch for emails of their own domain. + if (emailDomain != null && !email.EndsWith($"@{emailDomain}", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var verified = principal.FindFirst("email_verified")?.Value; + + if (verified != null) + { + return bool.TryParse(verified, out var isVerified) && isVerified; + } + + return !options.OidcRequireVerifiedEmail; + } } diff --git a/backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs b/backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs new file mode 100644 index 000000000..4d47ad9e7 --- /dev/null +++ b/backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs @@ -0,0 +1,40 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Security.Claims; + +namespace Squidex.Config.Authentication; + +public static class VerifiedEmailExtensions +{ + // Not prefixed with 'urn:squidex:' so that it is never stored as a custom user claim. + private const string ClaimType = "squidex_email_verified"; + + public static void SetEmailVerified(this ClaimsIdentity? identity, bool verified) + { + if (identity == null) + { + return; + } + + // Never trust a value that has been provided by the external identity provider. + foreach (var claim in identity.FindAll(ClaimType).ToList()) + { + identity.RemoveClaim(claim); + } + + if (verified) + { + identity.AddClaim(new Claim(ClaimType, "true")); + } + } + + public static bool IsEmailVerified(this ClaimsPrincipal principal) + { + return principal.HasClaim(ClaimType, "true"); + } +} diff --git a/backend/src/Squidex/Config/Domain/CommandsServices.cs b/backend/src/Squidex/Config/Domain/CommandsServices.cs index 3e0e902e2..5a779138a 100644 --- a/backend/src/Squidex/Config/Domain/CommandsServices.cs +++ b/backend/src/Squidex/Config/Domain/CommandsServices.cs @@ -22,6 +22,7 @@ using Squidex.Domain.Apps.Entities.Schemas; using Squidex.Domain.Apps.Entities.Schemas.Commands; using Squidex.Domain.Apps.Entities.Schemas.DomainObject; using Squidex.Domain.Apps.Entities.Schemas.Indexes; +using Squidex.Domain.Apps.Entities.Teams; using Squidex.Domain.Apps.Entities.Teams.Commands; using Squidex.Domain.Apps.Entities.Teams.DomainObject; using Squidex.Domain.Apps.Entities.Teams.Indexes; @@ -105,6 +106,9 @@ public static class CommandsServices services.AddSingletonAs() .As(); + services.AddSingletonAs() + .As(); + services.AddSingletonAs() .As(); diff --git a/backend/src/Squidex/Config/MyIdentityOptions.cs b/backend/src/Squidex/Config/MyIdentityOptions.cs index 1a32f6843..0754753ad 100644 --- a/backend/src/Squidex/Config/MyIdentityOptions.cs +++ b/backend/src/Squidex/Config/MyIdentityOptions.cs @@ -72,6 +72,8 @@ public sealed class MyIdentityOptions public bool OidcOverridePermissionsWithCustomClaimsOnLogin { get; set; } + public bool OidcRequireVerifiedEmail { get; set; } + public bool AdminRecreate { get; set; } public bool AllowPasswordAuth { get; set; } diff --git a/backend/src/Squidex/appsettings.json b/backend/src/Squidex/appsettings.json index 1d185fc58..231feaa9b 100644 --- a/backend/src/Squidex/appsettings.json +++ b/backend/src/Squidex/appsettings.json @@ -824,6 +824,9 @@ "oidcResponseType": "id_token", // or "code" "oidcGetClaimsFromUserInfoEndpoint": false, "oidcOverridePermissionsWithCustomClaimsOnLogin": false, + // Set to true to require the "email_verified" claim. Without this claim the email of the OIDC provider is trusted. + // Only users with a verified email can create an account or claim an account they got invited to. + "oidcRequireVerifiedEmail": false, "oidcOnSignoutRedirectUrl": "", // Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions by default contains scopes "openid" and "profile". // When oidcDisableProfileScope is set to true scope "profile" will be removed. diff --git a/backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs b/backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs index 69f5502c8..9b01bc6e3 100644 --- a/backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs +++ b/backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs @@ -53,6 +53,15 @@ public abstract class TeamRepositoryTests CreatedBy = createdBy, }; + var byAuthUnverified = new Team + { + Id = DomainId.NewGuid(), + Name = "by-auth-unverified", + Created = created, + CreatedBy = createdBy, + AuthScheme = new AuthScheme { Domain = "squidex.io" }, + }; + var byAuth = new Team { Id = DomainId.NewGuid(), @@ -60,6 +69,7 @@ public abstract class TeamRepositoryTests Created = created, CreatedBy = createdBy, AuthScheme = new AuthScheme { Domain = "squidex.io" }, + IsAuthDomainVerified = true, }; var byContributors = new Team @@ -73,6 +83,7 @@ public abstract class TeamRepositoryTests await PrepareAsync(sut, [ known, + byAuthUnverified, byAuth, byContributors, ]); @@ -100,6 +111,29 @@ public abstract class TeamRepositoryTests Assert.Equal("by-auth", found!.Name); } + [Fact] + public async Task Should_not_find_by_auth_schema_if_not_verified() + { + var sut = await CreateSutAsync(); + + var authDomain = $"{Guid.NewGuid()}.io"; + + var unverified = new Team + { + Id = DomainId.NewGuid(), + Name = "unverified", + Created = SystemClock.Instance.GetCurrentInstant(), + CreatedBy = RefToken.Client("client1"), + AuthScheme = new AuthScheme { Domain = authDomain }, + }; + + await PrepareAsync(sut, [unverified]); + + var found = await sut.FindByAuthDomainAsync(authDomain); + + Assert.Null(found); + } + [Theory] [InlineData("1")] [InlineData("2")] @@ -139,6 +173,7 @@ public abstract class TeamRepositoryTests Created = SystemClock.Instance.GetCurrentInstant(), CreatedBy = RefToken.Client("client1"), AuthScheme = new AuthScheme { Domain = authDomain }, + IsAuthDomainVerified = true, Contributors = Contributors.Empty.Assign(contributorId, Role.Owner), IsDeleted = true, }; diff --git a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json index 3ec9a13b4..2940bd5f6 100644 --- a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json +++ b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json @@ -5,6 +5,7 @@ "created": "2022-12-05T11:00:23Z", "createdBy": "subject:63761585e06d5466c71521b3", "id": "265aaf1e-5dff-4c40-b1e6-1149f652cd30", + "isAuthDomainVerified": false, "isDeleted": false, "lastModified": "2022-12-05T11:00:23Z", "lastModifiedBy": "subject:63761585e06d5466c71521b3", diff --git a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs index 558cf0ba3..19c7aada0 100644 --- a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs @@ -68,6 +68,55 @@ public class TeamTests Assert.Same(team_1, team_2); } + [Fact] + public void Should_verify_auth_domain() + { + var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }); + var team_2 = team_1.VerifyAuthDomain("SQUIDEX.io"); + var team_3 = team_2.VerifyAuthDomain("squidex.io"); + + Assert.False(team_1.IsAuthDomainVerified); + Assert.True(team_2.IsAuthDomainVerified); + Assert.Same(team_2, team_3); + } + + [Fact] + public void Should_not_verify_auth_domain_if_domain_does_not_match() + { + var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }); + var team_2 = team_1.VerifyAuthDomain("other.io"); + + Assert.Same(team_1, team_2); + Assert.False(team_2.IsAuthDomainVerified); + } + + [Fact] + public void Should_keep_verification_if_domain_does_not_change() + { + var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io"); + var team_2 = team_1.ChangeAuthScheme(new AuthScheme { Domain = "Squidex.io", DisplayName = "Changed" }); + + Assert.True(team_2.IsAuthDomainVerified); + } + + [Fact] + public void Should_reset_verification_if_domain_changes() + { + var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io"); + var team_2 = team_1.ChangeAuthScheme(new AuthScheme { Domain = "other.io" }); + + Assert.False(team_2.IsAuthDomainVerified); + } + + [Fact] + public void Should_reset_verification_if_scheme_removed() + { + var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io"); + var team_2 = team_1.ChangeAuthScheme(null); + + Assert.False(team_2.IsAuthDomainVerified); + } + [Fact] public void Should_update_contributors() { diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs index 656ca55dd..0d24d9d2c 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs @@ -8,6 +8,7 @@ using Squidex.Domain.Apps.Core.Teams; using Squidex.Domain.Apps.Core.TestHelpers; using Squidex.Domain.Apps.Entities.Billing; +using Squidex.Domain.Apps.Entities.Teams; using Squidex.Domain.Apps.Entities.Teams.Commands; using Squidex.Domain.Apps.Entities.Teams.DomainObject.Guards; using Squidex.Domain.Apps.Entities.TestHelpers; @@ -19,6 +20,7 @@ namespace Squidex.Domain.Teams.Apps.Teams.DomainObject.Guards; public class GuardTeamTests : GivenContext, IClassFixture { + private readonly IAuthDomainVerifier verifier = A.Fake(); private readonly IUserResolver users = A.Fake(); private readonly IBillingPlans billingPlans = A.Fake(); private readonly Plan planBasic = new Plan(); @@ -177,6 +179,59 @@ public class GuardTeamTests : GivenContext, IClassFixture await GuardTeam.CanUpsertAuth(command, AppProvider, CancellationToken); } + [Fact] + public async Task CanVerifyAuthDomain_should_throw_exception_if_no_scheme_configured() + { + var command = new VerifyAuthDomain { TeamId = Team.Id }; + + await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = null }, AppProvider, verifier, CancellationToken), + new ValidationError("No authentication domain is configured.")); + } + + [Fact] + public async Task CanVerifyAuthDomain_should_throw_exception_if_domain_verified_by_another_team() + { + A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken)) + .Returns(Team with { Id = DomainId.NewGuid() }); + + var command = new VerifyAuthDomain { TeamId = Team.Id }; + + await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken), + new ValidationError("Domain is already used for another team.")); + + A.CallTo(() => verifier.IsVerifiedAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task CanVerifyAuthDomain_should_throw_exception_if_record_not_found() + { + A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken)) + .Returns(Task.FromResult(null)); + + A.CallTo(() => verifier.IsVerifiedAsync("squidex.io", Team.Id, CancellationToken)) + .Returns(false); + + var command = new VerifyAuthDomain { TeamId = Team.Id }; + + await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken), + new ValidationError($"The DNS TXT record '_squidex.squidex.io' with the value 'squidex-team={Team.Id}' has not been found.")); + } + + [Fact] + public async Task CanVerifyAuthDomain_should_not_throw_exception_if_record_found() + { + A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken)) + .Returns(Team); + + A.CallTo(() => verifier.IsVerifiedAsync("squidex.io", Team.Id, CancellationToken)) + .Returns(true); + + var command = new VerifyAuthDomain { TeamId = Team.Id }; + + await GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken); + } + [Fact] public async Task CanDelete_should_throw_exception_if_app_is_assigned() { diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs index efab3f9be..39bc9207a 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs @@ -13,6 +13,7 @@ using Squidex.Domain.Apps.Entities.Billing; using Squidex.Domain.Apps.Entities.Teams.Commands; using Squidex.Domain.Apps.Entities.TestHelpers; using Squidex.Infrastructure; +using Squidex.Infrastructure.Validation; using Squidex.Shared.Users; namespace Squidex.Domain.Apps.Entities.Teams.DomainObject; @@ -20,6 +21,7 @@ namespace Squidex.Domain.Apps.Entities.Teams.DomainObject; public class TeamDomainObjectTests : HandlerTestBase { private readonly IAppProvider appProvider = A.Fake(); + private readonly IAuthDomainVerifier authDomainVerifier = A.Fake(); private readonly IBillingPlans billingPlans = A.Fake(); private readonly IBillingManager billingManager = A.Fake(); private readonly IUser user; @@ -70,6 +72,7 @@ public class TeamDomainObjectTests : HandlerTestBase var serviceProvider = new ServiceCollection() .AddSingleton(appProvider) + .AddSingleton(authDomainVerifier) .AddSingleton(billingPlans) .AddSingleton(billingManager) .AddSingleton(userResolver) @@ -139,6 +142,38 @@ public class TeamDomainObjectTests : HandlerTestBase await VerifySutAsync(actual); } + [Fact] + public async Task VerifyAuthDomain_should_create_events_and_verify_domain() + { + A.CallTo(() => authDomainVerifier.IsVerifiedAsync(scheme.Domain, TeamId, A._)) + .Returns(true); + + var command = new VerifyAuthDomain(); + + await ExecuteCreateAsync(); + await ExecuteUpsertAuthAsync(); + + var actual = await PublishIdempotentAsync(sut, command); + + await VerifySutAsync(actual); + } + + [Fact] + public async Task VerifyAuthDomain_should_throw_exception_if_record_not_found() + { + A.CallTo(() => authDomainVerifier.IsVerifiedAsync(scheme.Domain, TeamId, A._)) + .Returns(false); + + var command = new VerifyAuthDomain(); + + await ExecuteCreateAsync(); + await ExecuteUpsertAuthAsync(); + + await Assert.ThrowsAsync(() => PublishAsync(sut, command)); + + Assert.False(sut.Snapshot.IsAuthDomainVerified); + } + [Fact] public async Task ChangePlan_should_create_events_and_update_plan() { diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs index 0fc6801eb..fbf99dada 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs @@ -70,11 +70,26 @@ public class TeamsIndexTests : GivenContext [Fact] public async Task Should_resolve_team_by_domain() { + var team = Team with { IsAuthDomainVerified = true }; + A.CallTo(() => teamRepository.FindByAuthDomainAsync("squidex.io", CancellationToken)) - .Returns(Team); + .Returns(team); var actual = await sut.GetTeamByAuthDomainAsync("squidex.io", CancellationToken); - Assert.Same(actual, Team); + Assert.Same(actual, team); + } + + [Fact] + public async Task Should_not_resolve_team_by_domain_if_not_verified() + { + var team = Team with { IsAuthDomainVerified = false }; + + A.CallTo(() => teamRepository.FindByAuthDomainAsync("squidex.io", CancellationToken)) + .Returns(team); + + var actual = await sut.GetTeamByAuthDomainAsync("squidex.io", CancellationToken); + + Assert.Null(actual); } } diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt index 4a878f64a..49f456428 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt @@ -4,6 +4,7 @@ Guid_1: Owner, me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_2, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt index d2233c3e6..c24d60f4f 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt @@ -10,6 +10,7 @@ Owner: subject:me, PlanId: premium }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt index 21aab7a9c..2dd6f4881 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt index d2233c3e6..c24d60f4f 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt @@ -10,6 +10,7 @@ Owner: subject:me, PlanId: premium }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt index d2233c3e6..c24d60f4f 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt @@ -10,6 +10,7 @@ Owner: subject:me, PlanId: premium }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt index d11903327..7eb2a08b7 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt index 21aab7a9c..2dd6f4881 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt index 88b402036..fdb4925bc 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt index 9ceccd672..f654d40b1 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt @@ -3,6 +3,7 @@ UniqueId: Guid_1, Snapshot: { Name: My Team, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: client:client, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt index ed4b96a42..48a08ca06 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: true, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt index 4991540cc..513e2d068 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt @@ -3,6 +3,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt index d4ae5ecab..7ea3b1774 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt index 21aab7a9c..2dd6f4881 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt @@ -6,6 +6,7 @@ Contributors: { me: Owner }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt index 297611054..8d5cd7ffb 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt @@ -13,6 +13,7 @@ ClientSecret: clientSecret, Authority: https://identity.squidex.io }, + IsAuthDomainVerified: false, IsDeleted: false, Id: Guid_1, CreatedBy: subject:me, diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt new file mode 100644 index 000000000..924b8de69 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt @@ -0,0 +1,41 @@ +{ + sut: { + UniqueId: Guid_1, + Snapshot: { + Name: My Team, + Contributors: { + me: Owner + }, + AuthScheme: { + Domain: squidex.io, + DisplayName: Squidex, + ClientId: clientId, + ClientSecret: clientSecret, + Authority: https://identity.squidex.io + }, + IsAuthDomainVerified: true, + IsDeleted: false, + Id: Guid_1, + CreatedBy: subject:me, + LastModifiedBy: subject:me, + Version: 3, + UniqueId: Guid_1 + }, + Version: 3, + ObjectState: Created + }, + events: [ + { + Headers: { + AggregateId: Guid_1, + EventId: Guid_2 + }, + Payload: { + Domain: squidex.io, + TeamId: Guid_1, + Actor: subject:me, + FromRule: false + } + } + ] +} \ No newline at end of file diff --git a/frontend/src/app/features/teams/pages/auth/auth-page.component.html b/frontend/src/app/features/teams/pages/auth/auth-page.component.html index 905eb6ca1..61892321c 100644 --- a/frontend/src/app/features/teams/pages/auth/auth-page.component.html +++ b/frontend/src/app/features/teams/pages/auth/auth-page.component.html @@ -16,6 +16,48 @@ + @if (isEditing() && isSaved()) { +
+ @if (isVerified()) { +
{{ "teams.auth.verifiedHint" | sqxTranslate }}
+ } @else { +
{{ "teams.auth.notVerifiedHint" | sqxTranslate }}
+ + +
+ + +
+
+ + +
+ + +
+
+ + @if (canVerify()) { + + } + } +
+ } + @if (isEditing()) {
diff --git a/frontend/src/app/features/teams/pages/auth/auth-page.component.scss b/frontend/src/app/features/teams/pages/auth/auth-page.component.scss index 465debf6a..6ab0098eb 100644 --- a/frontend/src/app/features/teams/pages/auth/auth-page.component.scss +++ b/frontend/src/app/features/teams/pages/auth/auth-page.component.scss @@ -4,4 +4,8 @@ .card-header, .card-footer { padding: 1.25rem; -} \ No newline at end of file +} + +.verification { + border-bottom: 1px solid $color-border; +} diff --git a/frontend/src/app/features/teams/pages/auth/auth-page.component.ts b/frontend/src/app/features/teams/pages/auth/auth-page.component.ts index 81f6ab498..111c25818 100644 --- a/frontend/src/app/features/teams/pages/auth/auth-page.component.ts +++ b/frontend/src/app/features/teams/pages/auth/auth-page.component.ts @@ -45,6 +45,16 @@ export class AuthPageComponent { protected readonly isEditing = signal(false); + protected readonly canVerify = this.authState.canVerify; + + protected readonly isVerified = this.authState.isVerified; + + protected readonly verificationRecordName = this.authState.verificationRecordName; + + protected readonly verificationRecordValue = this.authState.verificationRecordValue; + + protected readonly isSaved = computed(() => !!this.authState.scheme()); + protected readonly urlToRedirect = computed(() => { const team = this.teamsState.selectedTeam(); if (!team) { @@ -84,6 +94,14 @@ export class AuthPageComponent { } } + protected verify() { + if (!this.canVerify()) { + return; + } + + this.authState.verify(); + } + protected save() { if (!this.isEditable()) { return; diff --git a/frontend/src/app/features/teams/state/team-auth.state.spec.ts b/frontend/src/app/features/teams/state/team-auth.state.spec.ts index 1f7456c00..5ef230890 100644 --- a/frontend/src/app/features/teams/state/team-auth.state.spec.ts +++ b/frontend/src/app/features/teams/state/team-auth.state.spec.ts @@ -52,6 +52,10 @@ describe('TeamAuthState', () => { expect(authState.snapshot.scheme).toEqual(scheme); expect(authState.snapshot.isLoaded).toBeTruthy(); expect(authState.snapshot.canUpdate).toBeTruthy(); + expect(authState.snapshot.canVerify).toBeTruthy(); + expect(authState.snapshot.isVerified).toBeFalsy(); + expect(authState.snapshot.verificationRecordName).toEqual('_squidex.squidex.io'); + expect(authState.snapshot.verificationRecordValue).toEqual('squidex-team=42'); expect(authState.snapshot.version).toEqual(version); dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.never()); }); @@ -106,14 +110,35 @@ describe('TeamAuthState', () => { expect(authState.snapshot.scheme).toEqual(newScheme); expect(authState.snapshot.version).toEqual(newVersion); }); + + it('should verify domain', () => { + authService.setup(x => x.verifyTeamAuth(It.isAny(), version)) + .returns(() => of(versioned(newVersion, createAuthResponse(scheme, true)))).verifiable(); + + authState.verify().subscribe(); + + expect(authState.snapshot.isVerified).toBeTruthy(); + expect(authState.snapshot.canVerify).toBeFalsy(); + expect(authState.snapshot.version).toEqual(newVersion); + dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.once()); + }); }); }); -function createAuthResponse(scheme: AuthSchemeDto | undefined): AuthSchemeResponseDto { +function createAuthResponse(scheme: AuthSchemeDto | undefined, isVerified = false): AuthSchemeResponseDto { + const _links: Record = { + update: new ResourceLinkDto({ method: 'PUT', href: 'teams/42/auth' }), + }; + + if (!isVerified) { + _links['verify'] = new ResourceLinkDto({ method: 'POST', href: 'teams/42/auth/verify' }); + } + return new AuthSchemeResponseDto({ scheme, - _links: { - update: new ResourceLinkDto({ method: 'PUT', href: 'teams/42/auth' }), - }, + isVerified, + verificationRecordName: '_squidex.squidex.io', + verificationRecordValue: 'squidex-team=42', + _links, }); } diff --git a/frontend/src/app/features/teams/state/team-auth.state.ts b/frontend/src/app/features/teams/state/team-auth.state.ts index 0a71f5e4b..a024418cf 100644 --- a/frontend/src/app/features/teams/state/team-auth.state.ts +++ b/frontend/src/app/features/teams/state/team-auth.state.ts @@ -8,15 +8,30 @@ import { inject, Service } from '@angular/core'; import { Observable } from 'rxjs'; import { finalize, map, tap } from 'rxjs/operators'; -import { AuthSchemeDto, AuthSchemeValueDto, debug, DialogService, LoadingState, shareSubscribed, State, TeamsService, TeamsState, VersionTag } from '@app/shared'; +import { AuthSchemeDto, AuthSchemeResponseDto, AuthSchemeValueDto, debug, DialogService, LoadingState, shareSubscribed, State, TeamsService, TeamsState, VersionTag } from '@app/shared'; interface Snapshot extends LoadingState { // The current scheme. scheme?: AuthSchemeDto | null; + // The current response, needed for the links. + response?: AuthSchemeResponseDto; + // Indicates if the user can update the auth settings. canUpdate?: boolean; + // Indicates if the user can verify the domain. + canVerify?: boolean; + + // Indicates if the domain is verified. + isVerified?: boolean; + + // The name of the DNS record to verify the domain. + verificationRecordName?: string; + + // The value of the DNS record to verify the domain. + verificationRecordValue?: string; + // The team version. version: VersionTag; } @@ -33,6 +48,18 @@ export class TeamAuthState extends State { public readonly canUpdate = this.project(x => x.canUpdate === true); + public readonly canVerify = + this.project(x => x.canVerify === true); + + public readonly isVerified = + this.project(x => x.isVerified === true); + + public readonly verificationRecordName = + this.project(x => x.verificationRecordName); + + public readonly verificationRecordValue = + this.project(x => x.verificationRecordValue); + public readonly isLoaded = this.project(x => x.isLoaded === true); @@ -66,14 +93,7 @@ export class TeamAuthState extends State { this.dialogs.notifyInfo('i18n:teams.auth.reloaded'); } - const { scheme, canUpdate } = payload; - this.next({ - canUpdate, - isLoaded: true, - isLoading: false, - scheme, - version, - }, 'Loading Success'); + this.replacePayload(payload, version, { isLoaded: true, isLoading: false }, 'Loading Success'); }), finalize(() => { this.next({ isLoading: false }, 'Loading Done'); @@ -84,10 +104,7 @@ export class TeamAuthState extends State { public update(scheme: AuthSchemeDto | undefined): Observable { return this.teamService.putTeamAuth(this.teamId, AuthSchemeValueDto.fromJSON({ scheme }), this.version).pipe( tap(({ version, payload }) => { - this.next({ - ...payload, - version, - }, 'Change'); + this.replacePayload(payload, version, {}, 'Change'); }), map(({ payload }) => { return payload.scheme; @@ -95,7 +112,38 @@ export class TeamAuthState extends State { shareSubscribed(this.dialogs)); } + public verify(): Observable { + const response = this.snapshot.response; + if (!response) { + throw new Error('Auth settings not loaded.'); + } + + return this.teamService.verifyTeamAuth(response, this.version).pipe( + tap(({ version, payload }) => { + this.dialogs.notifyInfo('i18n:teams.auth.verified'); + + this.replacePayload(payload, version, {}, 'Verified'); + }), + shareSubscribed(this.dialogs)); + } + + private replacePayload(payload: AuthSchemeResponseDto, version: VersionTag, state: Partial, event: string) { + const { canUpdate, canVerify, isVerified, scheme, verificationRecordName, verificationRecordValue } = payload; + + this.next({ + ...state, + canUpdate, + canVerify, + isVerified, + response: payload, + scheme, + verificationRecordName, + verificationRecordValue, + version, + }, event); + } + private get version() { return this.snapshot.version; } -} \ No newline at end of file +} diff --git a/frontend/src/app/shared/model/custom.ts b/frontend/src/app/shared/model/custom.ts index 7e7641f66..4664994df 100644 --- a/frontend/src/app/shared/model/custom.ts +++ b/frontend/src/app/shared/model/custom.ts @@ -213,6 +213,10 @@ export class AuthSchemeResponseDto extends generated.AuthSchemeResponseDto { public get canUpdate() { return this.compute('canUpdate', () => hasAnyLink(this._links, 'update')); } + + public get canVerify() { + return this.compute('canVerify', () => hasAnyLink(this._links, 'verify')); + } } export class ClientDto extends generated.ClientDto { diff --git a/frontend/src/app/shared/model/generated.ts b/frontend/src/app/shared/model/generated.ts index 0d249905d..4f02cda31 100644 --- a/frontend/src/app/shared/model/generated.ts +++ b/frontend/src/app/shared/model/generated.ts @@ -1582,11 +1582,21 @@ export interface IUpdateTeamDto { export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeResponseDto { /** The auth scheme if configured. */ readonly scheme?: AuthSchemeDto | undefined; + /** True, if the ownership of the domain has been verified. */ + readonly isVerified!: boolean; + /** The name of the DNS TXT record to verify the ownership of the domain. */ + readonly verificationRecordName?: string | undefined; + /** The value of the DNS TXT record to verify the ownership of the domain. */ + readonly verificationRecordValue?: string | undefined; public get canUpdate() { return this.compute('canUpdate', () => hasAnyLink(this._links, 'update')); } + public get canVerify() { + return this.compute('canVerify', () => hasAnyLink(this._links, 'verify')); + } + constructor(data?: IAuthSchemeResponseDto) { super(data); } @@ -1594,6 +1604,9 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes init(_data: any) { super.init(_data); (this).scheme = _data["scheme"] ? AuthSchemeDto.fromJSON(_data["scheme"]) : undefined; + (this).isVerified = _data["isVerified"]; + (this).verificationRecordName = _data["verificationRecordName"]; + (this).verificationRecordValue = _data["verificationRecordValue"]; this.cleanup(this); return this; } @@ -1607,6 +1620,9 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["scheme"] = this.scheme ? this.scheme.toJSON() : undefined; + data["isVerified"] = this.isVerified; + data["verificationRecordName"] = this.verificationRecordName; + data["verificationRecordValue"] = this.verificationRecordValue; super.toJSON(data); this.cleanup(data); return data; @@ -1616,6 +1632,12 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes export interface IAuthSchemeResponseDto extends IResourceDto { /** The auth scheme if configured. */ readonly scheme?: AuthSchemeDto | undefined; + /** True, if the ownership of the domain has been verified. */ + readonly isVerified: boolean; + /** The name of the DNS TXT record to verify the ownership of the domain. */ + readonly verificationRecordName?: string | undefined; + /** The value of the DNS TXT record to verify the ownership of the domain. */ + readonly verificationRecordValue?: string | undefined; } export class AuthSchemeDto implements IAuthSchemeDto { diff --git a/frontend/src/app/shared/services/teams.service.spec.ts b/frontend/src/app/shared/services/teams.service.spec.ts index 62b1b487e..b23a383cc 100644 --- a/frontend/src/app/shared/services/teams.service.spec.ts +++ b/frontend/src/app/shared/services/teams.service.spec.ts @@ -156,6 +156,42 @@ describe('TeamsService', () => { }, )); + it('should make post request to verify auth domain', inject( + [TeamsService, HttpTestingController], + (teamsService: TeamsService, httpMock: HttpTestingController) => { + const resource: Resource = { + _links: { + verify: { method: 'POST', href: '/api/teams/my-team/auth/verify' }, + }, + }; + + let auth: Versioned; + teamsService + .verifyTeamAuth(resource, version) + .subscribe((result) => { + auth = result; + }); + + const req = httpMock.expectOne( + 'http://service/p/api/teams/my-team/auth/verify', + ); + + expect(req.request.method).toEqual('POST'); + expect(req.request.headers.get('If-Match')).toBe(version.value); + + req.flush(teamAuthResponse(12), { + headers: { + etag: '2', + }, + }); + + expect(auth!).toEqual({ + payload: createTeamAuth(12), + version: new VersionTag('2'), + }); + }, + )); + it('should make put request to update auth', inject( [TeamsService, HttpTestingController], (teamsService: TeamsService, httpMock: HttpTestingController) => { @@ -262,8 +298,12 @@ describe('TeamsService', () => { clientSecret: 'client-secret', authority: 'squidex.io/authority', }, + isVerified: false, + verificationRecordName: '_squidex.squidex.io', + verificationRecordValue: `squidex-team=${id}`, _links: { update: { method: 'PUT', href: `teams/${id}/auth` }, + verify: { method: 'POST', href: `teams/${id}/auth/verify` }, }, }; } @@ -296,11 +336,18 @@ export function createTeamAuth(id: number) { clientSecret: 'client-secret', authority: 'squidex.io/authority', }), + isVerified: false, + verificationRecordName: '_squidex.squidex.io', + verificationRecordValue: `squidex-team=${id}`, _links: { update: new ResourceLinkDto({ method: 'PUT', href: `teams/${id}/auth`, }), + verify: new ResourceLinkDto({ + method: 'POST', + href: `teams/${id}/auth/verify`, + }), }, }); } diff --git a/frontend/src/app/shared/services/teams.service.ts b/frontend/src/app/shared/services/teams.service.ts index fac9b2b73..acc690ec0 100644 --- a/frontend/src/app/shared/services/teams.service.ts +++ b/frontend/src/app/shared/services/teams.service.ts @@ -79,6 +79,18 @@ export class TeamsService { pretifyError('i18n:teams.teamLoadFailed')); } + public verifyTeamAuth(resource: Resource, version: VersionOrTag): Observable> { + const link = resource._links['verify']; + + const url = this.apiUrl.buildUrl(link.href); + + return HTTP.requestVersioned(this.http, link.method, url, version).pipe( + mapVersioned((payload) => { + return AuthSchemeResponseDto.fromJSON(payload.body); + }), + pretifyError('i18n:teams.auth.verifyFailed')); + } + public leaveTeam(teamId: string, resource: Resource): Observable { const link = resource._links['leave'];