1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-09-27 04:03:00 +02:00

[SG-147] - Feature/web-organization-domain-claiming (#4734)

* Feature/SG-680 - Create Domain Verification Comp (#4283)

* domain-base.ts - added link to Architectural docs describing domain base class purpose

* SG-680 - (1) Created Org Domain API and observable based data store service (2) Created required response and request models

* SG-680 - Renaming org domain service abstractions to match existing convention

* SG-680 - (1) Updated getByOrgId method to return array of data to match back end + renamed it as such (2) Updated OrgDomainApiService get methods to update the OrgDomainService observables

* Two-factor-setup comp - change "tabbed-header" class to "page-header" to achieve visual consistency with other settings components.

* SG-680 - Refactor Org Domain API & domain services to conform to ADR 0013 - Avoid layered folder structure for request/response models (i.e., put models near "owner" services)

* SG-680 - Update Organization model to include a canManageDomainVerification check

* SG-680 - Created Domain Verification component and started scaffolding out HTML

* SG-680 - New OrgDomain state and API services need to be registered on jslib-services.module in order to be injectable into components for use (this is what maps abstractions to implementation for dependency injection)

* SG-680 - OrgDomainApiServiceAbstraction should be an abstract class

* SG-680 - Update OrgDomainApiService to use ListResponse and map into OrganizationDomainResponse properly

* SG-680 - Moved domain verification comp into subfolder to add clarity in folder structure

* SG-680 - Good start on Domain Add Edit Dialog

* SG-680 - Domain Add Edit Dialog - (1) Random generation of DNS TXT Record now working (2) DNS TXT Record Copyable (3) Additional translations added (4) Info callout added

* SG-680 - Domain Add Edit Dialog - (1) Added custom validator for domain name (2) Disable verify btn if form invalid

* SG-680 - Updated Domain Name custom validator to pass back error message in format the error.component.ts expected so it can be displayed without an untranslated error prefix of "invalidDomainName"

* Form-button - Added useful note regarding use of the bitFormButton directive and how it requires the use of the bitButton directive as well.

* SG-680 - OrgDomain.service - replace delete with splice as delete doesn't actually alter array. Duh.

* SG-680 -  Domain verification progress - (1) Table layout + loading working for the most part (more translations needed (2) Add & edit opening dialog (3) Dialog first draft of save and verify

* SG-680 - DomainAddEditDialog - Unique domain name enforcement implemented

* SG-680 - Domain Name Custom Reactive forms validator refactor - swapped to regex to support proper domain format (which now enforces the requirement of a .com or similar)

* SG-680 - OrgDomainApi svc - must await send of delete call otherwise runs synchronously. Duh.

* SG-680 - Domain verification progress - (1) CopyDnsTxt added to state service (2) Refactored dialog to use async actions (3) Dialog form changes now mark form controls as touched for more responsive error handling

* SG-680 - Domain-add-edit-dialog - Confirmation required now for domain deletion

* SG-680 - Domain verification table options now supports removing domains with confirmation prompt

* Shared module - merge conflict resolution + removing unused imports so I can check this in.

* SG-680 - Adding missing translations

* SG-680 - Comment clean up + todo

* Revert "Shared module - merge conflict resolution + removing unused imports so I can check this in."

This reverts commit 98fe346e67.

* SG-680 - DomainAddEditDialog - Replace bitAction with leveraging bitSubmit so that when users hit enter in a field the form gets submitted.

* SG-680 - Added httpStatusCode enum

* SG-680 - OrgDomainAPI - Verify endpoint now returns domain response model so upsert to sync obs state service

* SG-680 - Domain Verification comp - (1) Display last checked date (2) Verify first attempt in place (3) justify options content per design

* SG-680 - DomainAddEditDialog - Validation and error handling overhaul

* SG-680 - DomainAddEditDialog - (1) Autofocus domain name on new domain creation (2) Removed form.invalid == form disabled logic because of accessibility concerns

* SG-680 - OrgDomainResponse model refactor - back end is sending lower cased props

* SG-680 - OrgDomain service refactor - (1) Use proper abstraction for i18n svc (2) Don't make non-async methods async for no reason

* SG-680 - OrgDomainService - Added test suite

* SG-680 - Renaming httpStatusCode.enum to strip off .enum in attempt to pass eslint issue

* SG-680 - Renaming httpStatusCode enum file again to remove all capitalized letters to pass eslint rules.

* SG-680 - Updating HttpStatusCode import b/c auto import update missed it.

* SG-680 - DomainAddEditDialog - Don't show callout if domain is verified

* SG-680 - DomainVerificationComp - Add error handling to verify to handle case where domain isn't available

* SG-680 - OrgDomainApiSvc - svc should use abstractions in constructor

* SG-680 - OrgDomainApiSvc - added full test suite

* SG-680 - OrgDomainSvc test suite - fixing broken test

* SG-680 - Domain Verification Validation Scenario: show form control error when domain verification fails  - (1) Enhanced bitSubmit to optionally allowDisabledFormSubmit (2) Enhanced bitInput to optionally allow showErrorsWhenDisabled + added new docs

* SG-680 - Adjusting location & name of the bitInput docs to be in the top level docs section to match historical consensus and existing pattern.

* SG-680 - Removed TODO for adding tests since I've already added tests.

* SG-680 - DomainAddEditDialog - Handle verify domain conflict exceptions just in case

* SG-680 - Adjusting location of Domain verification settings item in the organization settings menu to match figma.

* SG-680 - Removing unnecessary comment

* SG-680 - Domain Verification component - updated svg to not have alt text so it is treated as decorative by screen readers for accessibility.

* SG-680 - Fixing messages.json missing }

* SG-680 - DomainAddEditDialog - Hardcoding inputs to bit-dialog as component vars are not needed for dynamic anything right now.

* SG-680 - Dialog comment refactor

* SG-680 -  OrgDomainSvc - comment and console log removals.

* SG-680 - Updating OrgDomain Service test suites to have better test titles.

* Defect/web org domain claiming bugfixes (#4458)

* SG-949 - OrgDomainVerification - Domain name validator now supports n levels of subdomains as well as top level domains.

* SG-955 - On domain verification error or failure, call to update the individual org domain item to get an updated last checked date on the client.

* SG-953 - In domain verification dialog edit, if verify called and failed, then must manually mark domain name as touched for errors to show up.

* SG-954 - Domain Verification edit dialog - Fixing delete button not having trash icon displayed + added i18n translation for title prop.

* SG-956 - Fixing domain claiming event logs so that they show up on the client (more to do as there are some events missing client & member)

* Form button directive comment update

* SG-977 - Event Log improvements: (1) Add new device type of server (2) Add EventSystemUser mapping to translated value.  The end result is that both SCIM and Domain verification logs properly show server as the client and SCIM or Domain verification as the member.

* Add comment to clarify use of SCIM in EVENT_SYSTEM_USER_TO_TRANSLATION  dict

* DeviceType.Server must be incremented to 22 b/c server master already has a DeviceType.SDK of 21.

* Add SDK w/ value of 21 to DeviceType to match master server

* Defect/web org domain claiming bugfixes the sequel (#4530)

* Update <bit-table> to latest standard so it works again (swap body from ng-container to ng-template)

* Input directive - showErrorsWhenDisabled case doesn't need to care if input isActive or not.

* SG-949 - Update domain name validator regex to prevent http://, https://, and www.

* SG-771 - Added claimed domain logic to web client (#4603)

* SG-771 / SG-772 / SG-743 - Add claimed domain logic which skips entry of Org SSO Id when an org has a claimed and verified domain to web, browser, and desktop.

* Fix lint errors by adding button types

---------

Co-authored-by: SmithThe4th <gsmith@bitwarden.com>
This commit is contained in:
Jared Snider 2023-02-15 15:50:39 -05:00 committed by GitHub
parent 24fa521b17
commit 36633bcb04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 2093 additions and 13 deletions

View File

@ -118,7 +118,9 @@ export class LoginComponent extends BaseLoginComponent {
"&state=" +
state +
"&codeChallenge=" +
codeChallenge
codeChallenge +
"&email=" +
encodeURIComponent(this.formGroup.controls.email.value)
);
}
}

View File

@ -397,6 +397,19 @@ export class EventService {
this.getShortId(ev.providerOrganizationId)
);
break;
// Org Domain claiming events
case EventType.OrganizationDomain_Added:
msg = humanReadableMsg = this.i18nService.t("addedDomain", ev.domainName);
break;
case EventType.OrganizationDomain_Removed:
msg = humanReadableMsg = this.i18nService.t("removedDomain", ev.domainName);
break;
case EventType.OrganizationDomain_Verified:
msg = humanReadableMsg = this.i18nService.t("domainVerifiedEvent", ev.domainName);
break;
case EventType.OrganizationDomain_NotVerified:
msg = humanReadableMsg = this.i18nService.t("domainNotVerifiedEvent", ev.domainName);
break;
default:
break;
}
@ -446,6 +459,8 @@ export class EventService {
return ["bwi-globe", this.i18nService.t("webVault") + " - Edge"];
case DeviceType.IEBrowser:
return ["bwi-globe", this.i18nService.t("webVault") + " - IE"];
case DeviceType.Server:
return ["bwi-server", this.i18nService.t("server")];
case DeviceType.UnknownBrowser:
return [
"bwi-globe",

View File

@ -19,6 +19,11 @@ import { EventResponse } from "@bitwarden/common/models/response/event.response"
import { BaseEventsComponent } from "../../common/base.events.component";
import { EventService } from "../../core";
const EVENT_SYSTEM_USER_TO_TRANSLATION: Record<EventSystemUser, string> = {
[EventSystemUser.SCIM]: null, // SCIM acronym not able to be translated so just display SCIM
[EventSystemUser.DomainVerification]: "domainVerification",
};
@Component({
selector: "app-org-events",
templateUrl: "events.component.html",
@ -134,9 +139,17 @@ export class EventsComponent extends BaseEventsComponent implements OnInit, OnDe
}
if (r.systemUser != null) {
return {
name: EventSystemUser[r.systemUser],
};
const systemUserI18nKey: string = EVENT_SYSTEM_USER_TO_TRANSLATION[r.systemUser];
if (systemUserI18nKey) {
return {
name: this.i18nService.t(systemUserI18nKey),
};
} else {
return {
name: EventSystemUser[r.systemUser],
};
}
}
return null;

View File

@ -44,6 +44,14 @@
>
{{ "exportVault" | i18n }}
</a>
<a
routerLink="domain-verification"
class="list-group-item"
routerLinkActive="active"
*ngIf="organization?.canManageDomainVerification"
>
{{ "domainVerification" | i18n }}
</a>
<a
routerLink="sso"
class="list-group-item"

View File

@ -107,6 +107,7 @@
<div class="tw-mb-3">
<a
routerLink="/sso"
[queryParams]="{ email: formGroup.value.email }"
(click)="saveEmailSettings()"
bitButton
buttonType="secondary"

View File

@ -1,6 +1,6 @@
<!-- Please remove this disable statement when editing this file! -->
<!-- eslint-disable @angular-eslint/template/button-has-type -->
<div class="tabbed-header">
<div class="page-header">
<h1 *ngIf="!organizationId">{{ "twoStepLogin" | i18n }}</h1>
<h1 *ngIf="organizationId">{{ "twoStepLoginEnforcement" | i18n }}</h1>
</div>

View File

@ -8,10 +8,16 @@ import { CryptoFunctionService } from "@bitwarden/common/abstractions/cryptoFunc
import { EnvironmentService } from "@bitwarden/common/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/abstractions/log.service";
import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction";
import { OrganizationDomainSsoDetailsResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain-sso-details.response";
import { PasswordGenerationService } from "@bitwarden/common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service";
import { StateService } from "@bitwarden/common/abstractions/state.service";
import { ValidationService } from "@bitwarden/common/abstractions/validation.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum";
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
@Component({
selector: "app-sso",
@ -30,7 +36,10 @@ export class SsoComponent extends BaseSsoComponent {
cryptoFunctionService: CryptoFunctionService,
environmentService: EnvironmentService,
passwordGenerationService: PasswordGenerationService,
logService: LogService
logService: LogService,
private orgDomainApiService: OrgDomainApiServiceAbstraction,
private loginService: LoginService,
private validationService: ValidationService
) {
super(
authService,
@ -51,11 +60,37 @@ export class SsoComponent extends BaseSsoComponent {
async ngOnInit() {
super.ngOnInit();
// eslint-disable-next-line rxjs-angular/prefer-takeuntil, rxjs/no-async-subscribe
this.route.queryParams.pipe(first()).subscribe(async (qParams) => {
if (qParams.identifier != null) {
// SSO Org Identifier in query params takes precedence over claimed domains
this.identifier = qParams.identifier;
} else {
// Note: this flow is written for web but both browser and desktop
// redirect here on SSO button click.
// Check if email matches any claimed domains
if (qParams.email) {
// show loading spinner
this.loggingIn = true;
try {
const response: OrganizationDomainSsoDetailsResponse =
await this.orgDomainApiService.getClaimedOrgDomainByEmail(qParams.email);
if (response?.ssoAvailable) {
this.identifier = response.organizationIdentifier;
await this.submit();
return;
}
} catch (error) {
this.handleGetClaimedDomainByEmailError(error);
}
this.loggingIn = false;
}
// Fallback to state svc if domain is unclaimed
const storedIdentifier = await this.stateService.getSsoOrgIdentifier();
if (storedIdentifier != null) {
this.identifier = storedIdentifier;
@ -64,6 +99,24 @@ export class SsoComponent extends BaseSsoComponent {
});
}
private handleGetClaimedDomainByEmailError(error: any): void {
if (error instanceof ErrorResponse) {
const errorResponse: ErrorResponse = error as ErrorResponse;
switch (errorResponse.statusCode) {
case HttpStatusCode.NotFound:
if (errorResponse?.message?.includes("Claimed org domain not found")) {
// Do nothing. This is a valid case.
return;
}
break;
default:
this.validationService.showError(errorResponse);
break;
}
}
}
async submit() {
await this.stateService.setSsoOrganizationIdentifier(this.identifier);
if (this.clientId === "browser") {

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="129" height="123" fill="none"><circle cx="67.071" cy="61.444" r="59.684" fill="#F0F0F0" stroke="#89929F" stroke-width="3"/><path stroke="#89929F" stroke-linecap="round" stroke-width="1.5" d="M21.55 100.351c30.98 2.459 58.077-20.525 60.522-51.335 1.482-18.666-6.06-34.632-19.411-45.882"/><path stroke="#89929F" stroke-linecap="round" stroke-width="1.5" d="M14.496 33.785C12.136 66.27 38.456 95.843 72.6 98.322c1.593.116 5.962.174 7.528.177 4.43-.177 17.611-2.407 26.618-7.151 6.626-3.49 12.932-7.15 17.831-12.737"/><path stroke="#89929F" stroke-linecap="round" stroke-width="1.5" d="M124.435 48.005c-17.949-24.123-55.678-26.834-83.084-6.443-16.604 12.353-26.685 30.356-27.493 48.08"/><circle cx="78.336" cy="27.893" r="5" fill="#89929F"/><circle cx="19.703" cy="66.052" r="5" fill="#89929F"/><circle cx="52.277" cy="93.973" r="5" fill="#89929F"/></svg>

After

Width:  |  Height:  |  Size: 898 B

View File

@ -6039,6 +6039,135 @@
"memberAccessAll": {
"message": "This member can access and modify all items."
},
"domainVerification": {
"message": "Domain verification"
},
"newDomain": {
"message": "New domain"
},
"noDomains": {
"message": "No domains"
},
"noDomainsSubText": {
"message": "Connecting a domain allows members to skip the SSO identifier field during Login with SSO."
},
"verifyDomain": {
"message": "Verify domain"
},
"reverifyDomain": {
"message": "Reverify domain"
},
"copyDnsTxtRecord": {
"message": "Copy DNS TXT record"
},
"dnsTxtRecord": {
"message": "DNS TXT record"
},
"dnsTxtRecordInputHint": {
"message": "Copy and paste the TXT record into your DNS Provider."
},
"domainNameInputHint": {
"message": "Example: mydomain.com. Subdomains require separate entries to be verified."
},
"automaticDomainVerification": {
"message": "Automatic Domain Verification"
},
"automaticDomainVerificationProcess": {
"message": "Bitwarden will attempt to verify the domain 3 times during the first 72 hours. If the domain cant be verified, check the DNS record in your host and manually verify. The domain will be removed from your organization in 7 days if it is not verified"
},
"invalidDomainNameMessage": {
"message": "Input is not a valid format. Format: mydomain.com. Subdomains require separate entries to be verified."
},
"removeDomain": {
"message": "Remove domain"
},
"removeDomainWarning": {
"message": "Removing a domain cannot be undone. Are you sure you want to continue?"
},
"domainRemoved": {
"message": "Domain removed"
},
"domainSaved": {
"message": "Domain saved"
},
"domainVerified": {
"message": "Domain verified"
},
"duplicateDomainError": {
"message": "You can't claim the same domain twice."
},
"domainNotAvailable": {
"message": "Someone else is using $DOMAIN$. Use a different domain to continue.",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"domainNotVerified": {
"message": "$DOMAIN$ not verified. Check your DNS record.",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"domainStatusVerified": {
"message": "Verified"
},
"domainStatusUnverified": {
"message": "Unverified"
},
"domainNameTh": {
"message": "Name"
},
"domainStatusTh": {
"message": "Status"
},
"lastChecked": {
"message": "Last checked"
},
"domainFormInvalid": {
"message": "There are form errors that need your attention"
},
"addedDomain": {
"message": "Added domain $DOMAIN$",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"removedDomain": {
"message": "Removed domain $DOMAIN$",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"domainVerifiedEvent": {
"message": "$DOMAIN$ verified",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"domainNotVerifiedEvent": {
"message": "$DOMAIN$ not verified",
"placeholders": {
"DOMAIN": {
"content": "$1",
"example": "bitwarden.com"
}
}
},
"membersColumnHeader": {
"message": "Member/Group"
},
@ -6114,6 +6243,9 @@
}
}
},
"server": {
"message": "Server"
},
"exportData": {
"message": "Export data"
},

View File

@ -0,0 +1,75 @@
<form
[formGroup]="domainForm"
[bitSubmit]="data.orgDomain ? verifyDomain : saveDomain"
[allowDisabledFormSubmit]="true"
>
<bit-dialog [dialogSize]="'default'" [disablePadding]="false">
<span bitDialogTitle>
<span *ngIf="!data.orgDomain">{{ "newDomain" | i18n }}</span>
<span *ngIf="data.orgDomain"> {{ "verifyDomain" | i18n }}</span>
<span *ngIf="data.orgDomain" class="tw-text-xs tw-text-muted">{{
data.orgDomain.domainName
}}</span>
<span *ngIf="data?.orgDomain && !data.orgDomain?.verifiedDate" bitBadge badgeType="warning">{{
"domainStatusUnverified" | i18n
}}</span>
<span *ngIf="data?.orgDomain && data?.orgDomain?.verifiedDate" bitBadge badgeType="success">{{
"domainStatusVerified" | i18n
}}</span>
</span>
<div bitDialogContent>
<bit-form-field>
<bit-label>{{ "domainName" | i18n }}</bit-label>
<input bitInput appAutofocus formControlName="domainName" [showErrorsWhenDisabled]="true" />
<bit-hint>{{ "domainNameInputHint" | i18n }}</bit-hint>
</bit-form-field>
<bit-form-field>
<bit-label>{{ "dnsTxtRecord" | i18n }}</bit-label>
<input bitInput formControlName="txt" />
<bit-hint>{{ "dnsTxtRecordInputHint" | i18n }}</bit-hint>
<button
type="button"
bitSuffix
bitButton
appA11yTitle="{{ 'copyDnsTxtRecord' | i18n }}"
(click)="copyDnsTxt()"
>
<i class="bwi bwi-lg bwi-clone" aria-hidden="true"></i>
</button>
</bit-form-field>
<bit-callout
*ngIf="!data?.orgDomain?.verifiedDate"
type="info"
title="{{ 'automaticDomainVerification' | i18n }}"
>
{{ "automaticDomainVerificationProcess" | i18n }}
</bit-callout>
</div>
<div bitDialogFooter class="tw-flex tw-flex-row tw-items-center tw-gap-2">
<button type="submit" bitButton bitFormButton buttonType="primary">
<span *ngIf="!data?.orgDomain?.verifiedDate">{{ "verifyDomain" | i18n }}</span>
<span *ngIf="data?.orgDomain?.verifiedDate">{{ "reverifyDomain" | i18n }}</span>
</button>
<button bitButton buttonType="secondary" (click)="dialogRef.close()" type="button">
{{ "cancel" | i18n }}
</button>
<button
*ngIf="data.orgDomain"
class="tw-ml-auto"
bitIconButton="bwi-trash"
buttonType="danger"
size="default"
title="{{ 'delete' | i18n }}"
aria-label="Delete"
[bitAction]="deleteDomain"
type="submit"
bitFormButton
></button>
</div>
</bit-dialog>
</form>

View File

@ -0,0 +1,270 @@
import { DialogRef, DIALOG_DATA } from "@angular/cdk/dialog";
import { Component, Inject, OnDestroy, OnInit } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from "@angular/forms";
import { Subject, takeUntil } from "rxjs";
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/abstractions/cryptoFunction.service";
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction";
import { OrgDomainServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction";
import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response";
import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service";
import { ValidationService } from "@bitwarden/common/abstractions/validation.service";
import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum";
import { Utils } from "@bitwarden/common/misc/utils";
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
import { OrganizationDomainRequest } from "@bitwarden/common/services/organization-domain/requests/organization-domain.request";
import { domainNameValidator } from "./validators/domain-name.validator";
import { uniqueInArrayValidator } from "./validators/unique-in-array.validator";
export interface DomainAddEditDialogData {
organizationId: string;
orgDomain: OrganizationDomainResponse;
existingDomainNames: Array<string>;
}
@Component({
selector: "app-domain-add-edit-dialog",
templateUrl: "domain-add-edit-dialog.component.html",
})
export class DomainAddEditDialogComponent implements OnInit, OnDestroy {
private componentDestroyed$: Subject<void> = new Subject();
domainForm: FormGroup = this.formBuilder.group({
domainName: [
"",
[
Validators.required,
domainNameValidator(this.i18nService.t("invalidDomainNameMessage")),
uniqueInArrayValidator(
this.data.existingDomainNames,
this.i18nService.t("duplicateDomainError")
),
],
],
txt: [{ value: null, disabled: true }],
});
get domainNameCtrl(): FormControl {
return this.domainForm.controls.domainName as FormControl;
}
get txtCtrl(): FormControl {
return this.domainForm.controls.txt as FormControl;
}
rejectedDomainNameValidator: ValidatorFn = null;
rejectedDomainNames: Array<string> = [];
constructor(
public dialogRef: DialogRef,
@Inject(DIALOG_DATA) public data: DomainAddEditDialogData,
private formBuilder: FormBuilder,
private cryptoFunctionService: CryptoFunctionServiceAbstraction,
private platformUtilsService: PlatformUtilsService,
private i18nService: I18nService,
private orgDomainApiService: OrgDomainApiServiceAbstraction,
private orgDomainService: OrgDomainServiceAbstraction,
private validationService: ValidationService
) {}
//#region Angular Method Implementations
async ngOnInit(): Promise<void> {
// If we have data.orgDomain, then editing, otherwise creating new domain
await this.populateForm();
}
ngOnDestroy(): void {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
//#endregion
//#region Form methods
async populateForm(): Promise<void> {
if (this.data.orgDomain) {
// Edit
this.domainForm.patchValue(this.data.orgDomain);
this.domainForm.disable();
} else {
// Add
// Figuring out the proper length of our DNS TXT Record value was fun.
// DNS-Based Service Discovery RFC: https://www.ietf.org/rfc/rfc6763.txt; see section 6.1
// Google uses 43 chars for their TXT record value: https://support.google.com/a/answer/2716802
// So, chose a magic # of 33 bytes to achieve at least that once converted to base 64 (47 char length).
const generatedTxt = `bw=${Utils.fromBufferToB64(
await this.cryptoFunctionService.randomBytes(33)
)}`;
this.txtCtrl.setValue(generatedTxt);
}
this.setupFormListeners();
}
setupFormListeners(): void {
// <bit-form-field> suppresses touched state on change for reactive form controls
// Manually set touched to show validation errors as the user stypes
this.domainForm.valueChanges.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
this.domainForm.markAllAsTouched();
});
}
copyDnsTxt(): void {
this.orgDomainService.copyDnsTxt(this.txtCtrl.value);
}
//#endregion
//#region Async Form Actions
saveDomain = async (): Promise<void> => {
if (this.domainForm.invalid) {
this.platformUtilsService.showToast("error", null, this.i18nService.t("domainFormInvalid"));
return;
}
this.domainNameCtrl.disable();
const request: OrganizationDomainRequest = new OrganizationDomainRequest(
this.txtCtrl.value,
this.domainNameCtrl.value
);
try {
this.data.orgDomain = await this.orgDomainApiService.post(this.data.organizationId, request);
this.platformUtilsService.showToast("success", null, this.i18nService.t("domainSaved"));
await this.verifyDomain();
} catch (e) {
this.handleDomainSaveError(e);
}
};
private handleDomainSaveError(e: any): void {
if (e instanceof ErrorResponse) {
const errorResponse: ErrorResponse = e as ErrorResponse;
switch (errorResponse.statusCode) {
case HttpStatusCode.Conflict:
if (errorResponse.message.includes("The domain is not available to be claimed")) {
// If user has attempted to claim a different rejected domain first:
if (this.rejectedDomainNameValidator) {
// Remove the validator:
this.domainNameCtrl.removeValidators(this.rejectedDomainNameValidator);
this.domainNameCtrl.updateValueAndValidity();
}
// Update rejected domain names and add new unique in validator
// which will prevent future known bad domain name submissions.
this.rejectedDomainNames.push(this.domainNameCtrl.value);
this.rejectedDomainNameValidator = uniqueInArrayValidator(
this.rejectedDomainNames,
this.i18nService.t("domainNotAvailable", this.domainNameCtrl.value)
);
this.domainNameCtrl.addValidators(this.rejectedDomainNameValidator);
this.domainNameCtrl.updateValueAndValidity();
// Give them another chance to enter a new domain name:
this.domainForm.enable();
} else {
this.validationService.showError(errorResponse);
}
break;
default:
this.validationService.showError(errorResponse);
break;
}
} else {
this.validationService.showError(e);
}
}
verifyDomain = async (): Promise<void> => {
if (this.domainForm.invalid) {
// Note: shouldn't be possible, but going to leave this to be safe.
this.platformUtilsService.showToast("error", null, this.i18nService.t("domainFormInvalid"));
return;
}
try {
this.data.orgDomain = await this.orgDomainApiService.verify(
this.data.organizationId,
this.data.orgDomain.id
);
if (this.data.orgDomain.verifiedDate) {
this.platformUtilsService.showToast("success", null, this.i18nService.t("domainVerified"));
this.dialogRef.close();
} else {
this.domainNameCtrl.setErrors({
errorPassthrough: {
message: this.i18nService.t("domainNotVerified", this.domainNameCtrl.value),
},
});
// For the case where user opens dialog and reverifies when domain name formControl disabled.
// The input directive only shows error if touched, so must manually mark as touched.
this.domainNameCtrl.markAsTouched();
// Update this item so the last checked date gets updated.
await this.updateOrgDomain();
}
} catch (e) {
this.handleVerifyDomainError(e, this.domainNameCtrl.value);
// Update this item so the last checked date gets updated.
await this.updateOrgDomain();
}
};
private handleVerifyDomainError(e: any, domainName: string): void {
if (e instanceof ErrorResponse) {
const errorResponse: ErrorResponse = e as ErrorResponse;
switch (errorResponse.statusCode) {
case HttpStatusCode.Conflict:
if (errorResponse.message.includes("The domain is not available to be claimed")) {
this.domainNameCtrl.setErrors({
errorPassthrough: {
message: this.i18nService.t("domainNotAvailable", domainName),
},
});
}
break;
default:
this.validationService.showError(errorResponse);
break;
}
}
}
private async updateOrgDomain() {
// Update this item so the last checked date gets updated.
await this.orgDomainApiService.getByOrgIdAndOrgDomainId(
this.data.organizationId,
this.data.orgDomain.id
);
}
deleteDomain = async (): Promise<void> => {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t("removeDomainWarning"),
this.i18nService.t("removeDomain"),
this.i18nService.t("yes"),
this.i18nService.t("no"),
"warning"
);
if (!confirmed) {
return;
}
await this.orgDomainApiService.delete(this.data.organizationId, this.data.orgDomain.id);
this.platformUtilsService.showToast("success", null, this.i18nService.t("domainRemoved"));
this.dialogRef.close();
};
//#endregion
}

View File

@ -0,0 +1,47 @@
import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
export function domainNameValidator(errorMessage: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) {
return null;
}
// Domain labels (sections) are only allowed to be 63 chars in length max
// 1st and last chars cannot be hyphens per RFC 3696 (https://www.rfc-editor.org/rfc/rfc3696#section-2)
// We do not want any prefixes per industry standards.
// Must support top-level domains and any number of subdomains.
// / # start regex
// ^ # start of string
// (?!(http(s)?:\/\/|www\.)) # negative lookahead to check if input doesn't match "http://", "https://" or "www."
// [a-zA-Z0-9] # first character must be a letter or a number
// [a-zA-Z0-9-]{0,61} # domain name can have 0 to 61 characters that are letters, numbers, or hyphens
// [a-zA-Z0-9] # domain name must end with a letter or a number
// (?: # start of non-capturing group (subdomain sections are optional)
// \. # subdomain must have a period
// [a-zA-Z0-9] # first character of subdomain must be a letter or a number
// [a-zA-Z0-9-]{0,61} # subdomain can have 0 to 61 characters that are letters, numbers, or hyphens
// [a-zA-Z0-9] # subdomain must end with a letter or a number
// )* # end of non-capturing group (subdomain sections are optional)
// \. # domain name must have a period
// [a-zA-Z]{2,} # domain name must have at least two letters (the domain extension)
// $/ # end of string
const validDomainNameRegex =
/^(?!(http(s)?:\/\/|www\.))[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*\.[a-zA-Z]{2,}$/;
const invalid = !validDomainNameRegex.test(control.value);
if (invalid) {
return {
invalidDomainName: {
message: errorMessage,
},
};
}
return null;
};
}

View File

@ -0,0 +1,23 @@
import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
export function uniqueInArrayValidator(values: Array<string>, errorMessage: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) {
return null;
}
const lowerTrimmedValue = value.toLowerCase().trim();
// check if the entered value is unique
if (values.some((val) => val.toLowerCase().trim() === lowerTrimmedValue)) {
return {
nonUniqueValue: {
message: errorMessage,
},
};
}
return null;
};
}

View File

@ -0,0 +1,105 @@
<div class="tw-flex tw-flex-row tw-justify-between">
<h1>{{ "domainVerification" | i18n }}</h1>
<button *ngIf="!loading" type="button" buttonType="primary" bitButton (click)="addDomain()">
<i class="bwi bwi-plus bwi-fw" aria-hidden="true"></i> {{ "newDomain" | i18n }}
</button>
</div>
<ng-container *ngIf="loading">
<i
class="bwi bwi-spinner bwi-spin text-muted"
title="{{ 'loading' | i18n }}"
aria-hidden="true"
></i>
<span class="sr-only">{{ "loading" | i18n }}</span>
</ng-container>
<ng-container *ngIf="!loading">
<ng-container *ngIf="orgDomains$ | async as orgDomains">
<div class="tw-flex tw-flex-row">
<bit-table class="tw-w-full tw-table-auto">
<ng-container header>
<tr>
<th bitCell>{{ "name" | i18n }}</th>
<th bitCell>{{ "status" | i18n }}</th>
<th bitCell>{{ "lastChecked" | i18n }}</th>
<th bitCell class="tw-text-right">{{ "options" | i18n }}</th>
</tr>
</ng-container>
<ng-template body>
<tr bitRow *ngFor="let orgDomain of orgDomains; index as i">
<td bitCell>
<a bitLink href appStopClick linkType="primary" (click)="editDomain(orgDomain)">{{
orgDomain.domainName
}}</a>
</td>
<td bitCell>
<span *ngIf="!orgDomain?.verifiedDate" bitBadge badgeType="warning">{{
"domainStatusUnverified" | i18n
}}</span>
<span *ngIf="orgDomain?.verifiedDate" bitBadge badgeType="success">{{
"domainStatusVerified" | i18n
}}</span>
</td>
<td bitCell class="tw-text-muted">
{{ orgDomain.lastCheckedDate | date: "medium" }}
</td>
<td bitCell class="table-list-options tw-text-right">
<button
[bitMenuTriggerFor]="orgDomainOptions"
class="tw-border-none tw-bg-transparent tw-text-main"
type="button"
appA11yTitle="{{ 'options' | i18n }}"
>
<i class="bwi bwi-ellipsis-v bwi-lg" aria-hidden="true"></i>
</button>
<bit-menu #orgDomainOptions>
<button bitMenuItem (click)="copyDnsTxt(orgDomain.txt)" type="button">
<i class="bwi bwi-fw bwi-clone" aria-hidden="true"></i>
{{ "copyDnsTxtRecord" | i18n }}
</button>
<button
bitMenuItem
(click)="verifyDomain(orgDomain.id, orgDomain.domainName)"
type="button"
>
<i class="bwi bwi-fw bwi-check" aria-hidden="true"></i>
{{ "verifyDomain" | i18n }}
</button>
<button bitMenuItem (click)="deleteDomain(orgDomain.id)" type="button">
<span class="tw-text-danger">
<i class="bwi bwi-fw bwi-close" aria-hidden="true"></i>
{{ "remove" | i18n }}
</span>
</button>
</bit-menu>
</td>
</tr>
</ng-template>
</bit-table>
</div>
<div
class="tw-mt-6 tw-flex tw-flex-col tw-items-center tw-justify-center"
*ngIf="orgDomains?.length == 0"
>
<img src="../../images/domain-verification/domain.svg" class="tw-mb-4" alt="" />
<div class="tw-mb-2 tw-flex tw-flex-row tw-justify-center">
<span class="tw-text-lg tw-font-bold">{{ "noDomains" | i18n }}</span>
</div>
<div class="tw-mb-4 tw-flex tw-flex-row tw-justify-center">
<span>
{{ "noDomainsSubText" | i18n }}
</span>
</div>
<button type="button" buttonType="secondary" bitButton (click)="addDomain()">
<i class="bwi bwi-plus bwi-fw" aria-hidden="true"></i> {{ "newDomain" | i18n }}
</button>
</div>
</ng-container>
</ng-container>

View File

@ -0,0 +1,179 @@
import { Component, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import { concatMap, Observable, Subject, take, takeUntil } from "rxjs";
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction";
import { OrgDomainServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction";
import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response";
import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service";
import { ValidationService } from "@bitwarden/common/abstractions/validation.service";
import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum";
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
import { DialogService } from "@bitwarden/components";
import {
DomainAddEditDialogComponent,
DomainAddEditDialogData,
} from "./domain-add-edit-dialog/domain-add-edit-dialog.component";
@Component({
selector: "app-org-manage-domain-verification",
templateUrl: "domain-verification.component.html",
})
export class DomainVerificationComponent implements OnInit, OnDestroy {
private componentDestroyed$ = new Subject<void>();
loading = true;
organizationId: string;
orgDomains$: Observable<OrganizationDomainResponse[]>;
constructor(
private route: ActivatedRoute,
private platformUtilsService: PlatformUtilsService,
private i18nService: I18nService,
private orgDomainApiService: OrgDomainApiServiceAbstraction,
private orgDomainService: OrgDomainServiceAbstraction,
private dialogService: DialogService,
private validationService: ValidationService
) {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async ngOnInit() {
this.orgDomains$ = this.orgDomainService.orgDomains$;
// Note: going to use concatMap as async subscribe blocks don't work as you expect and
// as such, ESLint rejects it
// ex: https://stackoverflow.com/a/71056380
this.route.params
.pipe(
concatMap(async (params: Params) => {
this.organizationId = params.organizationId;
await this.load();
}),
takeUntil(this.componentDestroyed$)
)
.subscribe();
}
async load() {
await this.orgDomainApiService.getAllByOrgId(this.organizationId);
this.loading = false;
}
addDomain() {
const domainAddEditDialogData: DomainAddEditDialogData = {
organizationId: this.organizationId,
orgDomain: null,
existingDomainNames: this.getExistingDomainNames(),
};
this.dialogService.open(DomainAddEditDialogComponent, {
data: domainAddEditDialogData,
});
}
editDomain(orgDomain: OrganizationDomainResponse) {
const domainAddEditDialogData: DomainAddEditDialogData = {
organizationId: this.organizationId,
orgDomain: orgDomain,
existingDomainNames: this.getExistingDomainNames(),
};
this.dialogService.open(DomainAddEditDialogComponent, {
data: domainAddEditDialogData,
});
}
private getExistingDomainNames(): Array<string> {
let existingDomainNames: string[];
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
this.orgDomains$.pipe(take(1)).subscribe((orgDomains: Array<OrganizationDomainResponse>) => {
existingDomainNames = orgDomains.map((o) => o.domainName);
});
return existingDomainNames;
}
//#region Options
copyDnsTxt(dnsTxt: string): void {
this.orgDomainService.copyDnsTxt(dnsTxt);
}
async verifyDomain(orgDomainId: string, domainName: string): Promise<void> {
try {
const orgDomain: OrganizationDomainResponse = await this.orgDomainApiService.verify(
this.organizationId,
orgDomainId
);
if (orgDomain.verifiedDate) {
this.platformUtilsService.showToast("success", null, this.i18nService.t("domainVerified"));
} else {
this.platformUtilsService.showToast(
"error",
null,
this.i18nService.t("domainNotVerified", domainName)
);
// Update this item so the last checked date gets updated.
await this.updateOrgDomain(orgDomainId);
}
} catch (e) {
this.handleVerifyDomainError(e, domainName);
// Update this item so the last checked date gets updated.
await this.updateOrgDomain(orgDomainId);
}
}
private async updateOrgDomain(orgDomainId: string) {
// Update this item so the last checked date gets updated.
await this.orgDomainApiService.getByOrgIdAndOrgDomainId(this.organizationId, orgDomainId);
}
private handleVerifyDomainError(e: any, domainName: string): void {
if (e instanceof ErrorResponse) {
const errorResponse: ErrorResponse = e as ErrorResponse;
switch (errorResponse.statusCode) {
case HttpStatusCode.Conflict:
if (errorResponse.message.includes("The domain is not available to be claimed")) {
this.platformUtilsService.showToast(
"error",
null,
this.i18nService.t("domainNotAvailable", domainName)
);
}
break;
default:
this.validationService.showError(errorResponse);
break;
}
}
}
async deleteDomain(orgDomainId: string): Promise<void> {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t("removeDomainWarning"),
this.i18nService.t("removeDomain"),
this.i18nService.t("yes"),
this.i18nService.t("no"),
"warning"
);
if (!confirmed) {
return;
}
await this.orgDomainApiService.delete(this.organizationId, orgDomainId);
this.platformUtilsService.showToast("success", null, this.i18nService.t("domainRemoved"));
}
//#endregion
ngOnDestroy(): void {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
}

View File

@ -10,6 +10,7 @@ import { SettingsComponent } from "@bitwarden/web-vault/app/organizations/settin
import { SsoComponent } from "../auth/sso.component";
import { DomainVerificationComponent } from "./manage/domain-verification/domain-verification.component";
import { ScimComponent } from "./manage/scim.component";
const routes: Routes = [
@ -26,6 +27,14 @@ const routes: Routes = [
organizationPermissions: canAccessSettingsTab,
},
children: [
{
path: "domain-verification",
component: DomainVerificationComponent,
canActivate: [OrganizationPermissionsGuard],
data: {
organizationPermissions: (org: Organization) => org.canManageDomainVerification,
},
},
{
path: "sso",
component: SsoComponent,

View File

@ -5,11 +5,19 @@ import { SharedModule } from "@bitwarden/web-vault/app/shared/shared.module";
import { SsoComponent } from "../auth/sso.component";
import { InputCheckboxComponent } from "./components/input-checkbox.component";
import { DomainAddEditDialogComponent } from "./manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component";
import { DomainVerificationComponent } from "./manage/domain-verification/domain-verification.component";
import { ScimComponent } from "./manage/scim.component";
import { OrganizationsRoutingModule } from "./organizations-routing.module";
@NgModule({
imports: [SharedModule, OrganizationsRoutingModule],
declarations: [InputCheckboxComponent, SsoComponent, ScimComponent],
declarations: [
InputCheckboxComponent,
SsoComponent,
ScimComponent,
DomainVerificationComponent,
DomainAddEditDialogComponent,
],
})
export class OrganizationsModule {}

View File

@ -221,7 +221,9 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit
"&state=" +
state +
"&codeChallenge=" +
codeChallenge
codeChallenge +
"&email=" +
encodeURIComponent(this.formGroup.controls.email.value)
);
}

View File

@ -22,6 +22,11 @@ import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/abstrac
import { LogService } from "@bitwarden/common/abstractions/log.service";
import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/abstractions/messaging.service";
import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service";
import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction";
import {
OrgDomainServiceAbstraction,
OrgDomainInternalServiceAbstraction,
} from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction";
import { OrganizationUserService } from "@bitwarden/common/abstractions/organization-user/organization-user.service";
import { OrganizationApiServiceAbstraction } from "@bitwarden/common/abstractions/organization/organization-api.service.abstraction";
import {
@ -91,6 +96,8 @@ import { ExportService } from "@bitwarden/common/services/export.service";
import { FileUploadService } from "@bitwarden/common/services/fileUpload.service";
import { FormValidationErrorsService } from "@bitwarden/common/services/formValidationErrors.service";
import { NotificationsService } from "@bitwarden/common/services/notifications.service";
import { OrgDomainApiService } from "@bitwarden/common/services/organization-domain/org-domain-api.service";
import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service";
import { OrganizationUserServiceImplementation } from "@bitwarden/common/services/organization-user/organization-user.service.implementation";
import { OrganizationApiService } from "@bitwarden/common/services/organization/organization-api.service";
import { OrganizationService } from "@bitwarden/common/services/organization/organization.service";
@ -610,6 +617,20 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
useClass: LoginService,
deps: [StateServiceAbstraction],
},
{
provide: OrgDomainServiceAbstraction,
useClass: OrgDomainService,
deps: [PlatformUtilsServiceAbstraction, I18nServiceAbstraction],
},
{
provide: OrgDomainInternalServiceAbstraction,
useExisting: OrgDomainServiceAbstraction,
},
{
provide: OrgDomainApiServiceAbstraction,
useClass: OrgDomainApiService,
deps: [OrgDomainServiceAbstraction, ApiServiceAbstraction],
},
],
})
export class JslibServicesModule {}

View File

@ -0,0 +1,173 @@
import { mock, mockReset } from "jest-mock-extended";
import { lastValueFrom } from "rxjs";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response";
import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service";
import { OrgDomainApiService } from "@bitwarden/common/services/organization-domain/org-domain-api.service";
import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service";
const mockedGetAllByOrgIdResponse: any = {
data: [
{
id: "ca01a674-7f2f-45f2-8245-af6d016416b7",
organizationId: "cb903acf-2361-4072-ae32-af6c014943b6",
txt: "bw=EUX6UKR8A68igAJkmodwkzMiqB00u7Iyq1QqALu6jFID",
domainName: "test.com",
creationDate: "2022-12-16T21:36:28.68Z",
nextRunDate: "2022-12-17T09:36:28.68Z",
jobRunCount: 0,
verifiedDate: null as any,
lastCheckedDate: "2022-12-16T21:36:28.7633333Z",
object: "organizationDomain",
},
{
id: "adbd44c5-90d5-4537-97e6-af6d01644870",
organizationId: "cb903acf-2361-4072-ae32-af6c014943b6",
txt: "bw=Ql4fCfDacmcjwyAP9BPmvhSMTCz4PkEDm4uQ3fH01pD4",
domainName: "test2.com",
creationDate: "2022-12-16T21:37:10.9566667Z",
nextRunDate: "2022-12-17T09:37:10.9566667Z",
jobRunCount: 0,
verifiedDate: "totally verified",
lastCheckedDate: "2022-12-16T21:37:11.1933333Z",
object: "organizationDomain",
},
{
id: "05cf3ab8-bcfe-4b95-92e8-af6d01680942",
organizationId: "cb903acf-2361-4072-ae32-af6c014943b6",
txt: "bw=EQNUs77BWQHbfSiyc/9nT3wCen9z2yMn/ABCz0cNKaTx",
domainName: "test3.com",
creationDate: "2022-12-16T21:50:50.96Z",
nextRunDate: "2022-12-17T09:50:50.96Z",
jobRunCount: 0,
verifiedDate: null,
lastCheckedDate: "2022-12-16T21:50:51.0933333Z",
object: "organizationDomain",
},
],
continuationToken: null as any,
object: "list",
};
const mockedOrgDomainServerResponse = {
id: "ca01a674-7f2f-45f2-8245-af6d016416b7",
organizationId: "cb903acf-2361-4072-ae32-af6c014943b6",
txt: "bw=EUX6UKR8A68igAJkmodwkzMiqB00u7Iyq1QqALu6jFID",
domainName: "test.com",
creationDate: "2022-12-16T21:36:28.68Z",
nextRunDate: "2022-12-17T09:36:28.68Z",
jobRunCount: 0,
verifiedDate: null as any,
lastCheckedDate: "2022-12-16T21:36:28.7633333Z",
object: "organizationDomain",
};
const mockedOrgDomainResponse = new OrganizationDomainResponse(mockedOrgDomainServerResponse);
describe("Org Domain API Service", () => {
let orgDomainApiService: OrgDomainApiService;
const apiService = mock<ApiService>();
let orgDomainService: OrgDomainService;
const platformUtilService = mock<PlatformUtilsService>();
const i18nService = mock<I18nService>();
beforeEach(() => {
orgDomainService = new OrgDomainService(platformUtilService, i18nService);
mockReset(apiService);
orgDomainApiService = new OrgDomainApiService(orgDomainService, apiService);
});
it("instantiates", () => {
expect(orgDomainApiService).not.toBeFalsy();
});
it("getAllByOrgId retrieves all org domains and calls orgDomainSvc replace", () => {
apiService.send.mockResolvedValue(mockedGetAllByOrgIdResponse);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
const orgDomainSvcReplaceSpy = jest.spyOn(orgDomainService, "replace");
orgDomainApiService
.getAllByOrgId("fakeOrgId")
.then((orgDomainResponses: Array<OrganizationDomainResponse>) => {
expect(orgDomainResponses).toHaveLength(3);
expect(orgDomainSvcReplaceSpy).toHaveBeenCalled();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3);
});
});
it("getByOrgIdAndOrgDomainId retrieves single org domain and calls orgDomainSvc upsert", () => {
apiService.send.mockResolvedValue(mockedOrgDomainServerResponse);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert");
orgDomainApiService
.getByOrgIdAndOrgDomainId("fakeOrgId", "fakeDomainId")
.then((orgDomain: OrganizationDomainResponse) => {
expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id);
expect(orgDomainSvcUpsertSpy).toHaveBeenCalled();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1);
});
});
it("post success should call orgDomainSvc upsert", () => {
apiService.send.mockResolvedValue(mockedOrgDomainServerResponse);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert");
orgDomainApiService
.post("fakeOrgId", mockedOrgDomainResponse)
.then((orgDomain: OrganizationDomainResponse) => {
expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id);
expect(orgDomainSvcUpsertSpy).toHaveBeenCalled();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1);
});
});
it("verify success should call orgDomainSvc upsert", () => {
apiService.send.mockResolvedValue(mockedOrgDomainServerResponse);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert");
orgDomainApiService
.verify("fakeOrgId", "fakeOrgId")
.then((orgDomain: OrganizationDomainResponse) => {
expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id);
expect(orgDomainSvcUpsertSpy).toHaveBeenCalled();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1);
});
});
it("delete success should call orgDomainSvc delete", () => {
apiService.send.mockResolvedValue(true);
orgDomainService.upsert([mockedOrgDomainResponse]);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1);
const orgDomainSvcDeleteSpy = jest.spyOn(orgDomainService, "delete");
orgDomainApiService.delete("fakeOrgId", "fakeOrgId").then(() => {
expect(orgDomainSvcDeleteSpy).toHaveBeenCalled();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
});
});
// TODO: add Get Domain SSO method: Retrieves SSO provider information given a domain name
// when added on back end
});

View File

@ -0,0 +1,168 @@
import { mock, mockReset } from "jest-mock-extended";
import { lastValueFrom } from "rxjs";
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response";
import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service";
import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service";
const mockedUnverifiedDomainServerResponse = {
creationDate: "2022-12-13T23:16:43.7066667Z",
domainName: "bacon.com",
id: "12eac4ea-9ed8-4dd4-85da-af6a017f9f97",
jobRunCount: 0,
lastCheckedDate: "2022-12-13T23:16:43.8033333Z",
nextRunDate: "2022-12-14T11:16:43.7066667Z",
object: "organizationDomain",
organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef",
txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX",
verifiedDate: null as any,
};
const mockedVerifiedDomainServerResponse = {
creationDate: "2022-12-13T23:16:43.7066667Z",
domainName: "cat.com",
id: "58715f70-8650-4a42-9d4a-af6a0188151b",
jobRunCount: 0,
lastCheckedDate: "2022-12-13T23:16:43.8033333Z",
nextRunDate: "2022-12-14T11:16:43.7066667Z",
object: "organizationDomain",
organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef",
txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX",
verifiedDate: "2022-12-13T23:16:43.7066667Z",
};
const mockedExtraDomainServerResponse = {
creationDate: "2022-12-13T23:16:43.7066667Z",
domainName: "dog.com",
id: "fac7cdb6-283e-4805-aa55-af6b016bf699",
jobRunCount: 0,
lastCheckedDate: "2022-12-13T23:16:43.8033333Z",
nextRunDate: "2022-12-14T11:16:43.7066667Z",
object: "organizationDomain",
organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef",
txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX",
verifiedDate: null as any,
};
const mockedUnverifiedOrgDomainResponse = new OrganizationDomainResponse(
mockedUnverifiedDomainServerResponse
);
const mockedVerifiedOrgDomainResponse = new OrganizationDomainResponse(
mockedVerifiedDomainServerResponse
);
const mockedExtraOrgDomainResponse = new OrganizationDomainResponse(
mockedExtraDomainServerResponse
);
describe("Org Domain Service", () => {
let orgDomainService: OrgDomainService;
const platformUtilService = mock<PlatformUtilsService>();
const i18nService = mock<I18nService>();
beforeEach(() => {
mockReset(platformUtilService);
mockReset(i18nService);
orgDomainService = new OrgDomainService(platformUtilService, i18nService);
});
it("instantiates", () => {
expect(orgDomainService).not.toBeFalsy();
});
it("orgDomains$ public observable exists and instantiates w/ empty array", () => {
expect(orgDomainService.orgDomains$).toBeDefined();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual([]);
});
it("replace and clear work", () => {
const newOrgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse];
orgDomainService.replace(newOrgDomains);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual(newOrgDomains);
orgDomainService.clearCache();
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual([]);
});
it("get successfully retrieves org domain by id", () => {
const orgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse];
orgDomainService.replace(orgDomains);
expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id)).toEqual(
mockedVerifiedOrgDomainResponse
);
expect(orgDomainService.get(mockedUnverifiedOrgDomainResponse.id)).toEqual(
mockedUnverifiedOrgDomainResponse
);
});
it("upsert both updates an existing org domain and adds a new one", () => {
const orgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse];
orgDomainService.replace(orgDomains);
const changedOrgDomain = new OrganizationDomainResponse(mockedVerifiedDomainServerResponse);
changedOrgDomain.domainName = "changed domain name";
expect(mockedVerifiedOrgDomainResponse.domainName).not.toEqual(changedOrgDomain.domainName);
orgDomainService.upsert([changedOrgDomain]);
expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id).domainName).toEqual(
changedOrgDomain.domainName
);
const newOrgDomain = new OrganizationDomainResponse({
creationDate: "2022-12-13T23:16:43.7066667Z",
domainName: "cat.com",
id: "magical-cat-id-number-999",
jobRunCount: 0,
lastCheckedDate: "2022-12-13T23:16:43.8033333Z",
nextRunDate: "2022-12-14T11:16:43.7066667Z",
object: "organizationDomain",
organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef",
txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX",
verifiedDate: null as any,
});
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(2);
orgDomainService.upsert([newOrgDomain]);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3);
expect(orgDomainService.get(newOrgDomain.id)).toEqual(newOrgDomain);
});
it("delete successfully removes multiple org domains", () => {
const orgDomains = [
mockedUnverifiedOrgDomainResponse,
mockedVerifiedOrgDomainResponse,
mockedExtraOrgDomainResponse,
];
orgDomainService.replace(orgDomains);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3);
orgDomainService.delete([mockedUnverifiedOrgDomainResponse.id]);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(2);
expect(orgDomainService.get(mockedUnverifiedOrgDomainResponse.id)).toEqual(undefined);
orgDomainService.delete([mockedVerifiedOrgDomainResponse.id, mockedExtraOrgDomainResponse.id]);
expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0);
expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id)).toEqual(undefined);
expect(orgDomainService.get(mockedExtraOrgDomainResponse.id)).toEqual(undefined);
});
it("copyDnsTxt copies DNS TXT to clipboard and shows toast", () => {
orgDomainService.copyDnsTxt("fakeTxt");
expect(jest.spyOn(platformUtilService, "copyToClipboard")).toHaveBeenCalled();
expect(jest.spyOn(platformUtilService, "showToast")).toHaveBeenCalled();
});
});

View File

@ -0,0 +1,19 @@
import { OrganizationDomainRequest } from "../../services/organization-domain/requests/organization-domain.request";
import { OrganizationDomainSsoDetailsResponse } from "./responses/organization-domain-sso-details.response";
import { OrganizationDomainResponse } from "./responses/organization-domain.response";
export abstract class OrgDomainApiServiceAbstraction {
getAllByOrgId: (orgId: string) => Promise<Array<OrganizationDomainResponse>>;
getByOrgIdAndOrgDomainId: (
orgId: string,
orgDomainId: string
) => Promise<OrganizationDomainResponse>;
post: (
orgId: string,
orgDomain: OrganizationDomainRequest
) => Promise<OrganizationDomainResponse>;
verify: (orgId: string, orgDomainId: string) => Promise<OrganizationDomainResponse>;
delete: (orgId: string, orgDomainId: string) => Promise<any>;
getClaimedOrgDomainByEmail: (email: string) => Promise<OrganizationDomainSsoDetailsResponse>;
}

View File

@ -0,0 +1,20 @@
import { Observable } from "rxjs";
import { OrganizationDomainResponse } from "./responses/organization-domain.response";
export abstract class OrgDomainServiceAbstraction {
orgDomains$: Observable<OrganizationDomainResponse[]>;
get: (orgDomainId: string) => OrganizationDomainResponse;
copyDnsTxt: (dnsTxt: string) => void;
}
// Note: this separate class is designed to hold methods that are not
// meant to be used in components (e.g., data write methods)
export abstract class OrgDomainInternalServiceAbstraction extends OrgDomainServiceAbstraction {
upsert: (orgDomains: OrganizationDomainResponse[]) => void;
replace: (orgDomains: OrganizationDomainResponse[]) => void;
clearCache: () => void;
delete: (orgDomainIds: string[]) => void;
}

View File

@ -0,0 +1,20 @@
import { BaseResponse } from "../../../models/response/base.response";
export class OrganizationDomainSsoDetailsResponse extends BaseResponse {
id: string;
organizationIdentifier: string;
ssoAvailable: boolean;
domainName: string;
ssoRequired: boolean;
verifiedDate?: Date;
constructor(response: any) {
super(response);
this.id = this.getResponseProperty("id");
this.organizationIdentifier = this.getResponseProperty("organizationIdentifier");
this.ssoAvailable = this.getResponseProperty("ssoAvailable");
this.domainName = this.getResponseProperty("domainName");
this.ssoRequired = this.getResponseProperty("ssoRequired");
this.verifiedDate = this.getResponseProperty("verifiedDate");
}
}

View File

@ -0,0 +1,26 @@
import { BaseResponse } from "../../../models/response/base.response";
export class OrganizationDomainResponse extends BaseResponse {
id: string;
organizationId: string;
txt: string;
domainName: string;
creationDate: string;
nextRunDate: string;
jobRunCount: number;
verifiedDate?: string;
lastCheckedDate?: string;
constructor(response: any) {
super(response);
this.id = this.getResponseProperty("id");
this.organizationId = this.getResponseProperty("organizationId");
this.txt = this.getResponseProperty("txt");
this.domainName = this.getResponseProperty("domainName");
this.creationDate = this.getResponseProperty("creationDate");
this.nextRunDate = this.getResponseProperty("nextRunDate");
this.jobRunCount = this.getResponseProperty("jobRunCount");
this.verifiedDate = this.getResponseProperty("verifiedDate");
this.lastCheckedDate = this.getResponseProperty("lastCheckedDate");
}
}

View File

@ -20,4 +20,6 @@ export enum DeviceType {
VivaldiBrowser = 18,
VivaldiExtension = 19,
SafariExtension = 20,
SDK = 21,
Server = 22,
}

View File

@ -1,4 +1,5 @@
// Note: the enum key is used to describe the EventSystemUser in the UI. Be careful about changing it.
export enum EventSystemUser {
SCIM = 1,
DomainVerification = 2,
}

View File

@ -72,4 +72,9 @@ export enum EventType {
ProviderOrganization_Added = 1901,
ProviderOrganization_Removed = 1902,
ProviderOrganization_VaultAccessed = 1903,
OrganizationDomain_Added = 1904,
OrganizationDomain_Removed = 1905,
OrganizationDomain_Verified = 1906,
OrganizationDomain_NotVerified = 1907,
}

View File

@ -0,0 +1,403 @@
/**
* Hypertext Transfer Protocol (HTTP) response status codes.
*
* @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes}
* src: https://gist.github.com/RWOverdijk/6cef816cfdf5722228e01cc05fd4b094
*/
export enum HttpStatusCode {
/**
* The server has received the request headers and the client should proceed to send the request body
* (in the case of a request for which a body needs to be sent; for example, a POST request).
* Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient.
* To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request
* and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued.
*/
Continue = 100,
/**
* The requester has asked the server to switch protocols and the server has agreed to do so.
*/
SwitchingProtocols = 101,
/**
* A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request.
* This code indicates that the server has received and is processing the request, but no response is available yet.
* This prevents the client from timing out and assuming the request was lost.
*/
Processing = 102,
// **********************************************************************************************************
//#region 200s - SUCCESS
// **********************************************************************************************************
/**
* Standard response for successful HTTP requests.
* The actual response will depend on the request method used.
* In a GET request, the response will contain an entity corresponding to the requested resource.
* In a POST request, the response will contain an entity describing or containing the result of the action.
*/
Ok = 200,
/**
* The request has been fulfilled, resulting in the creation of a new resource.
*/
Created = 201,
/**
* The request has been accepted for processing, but the processing has not been completed.
* The request might or might not be eventually acted upon, and may be disallowed when processing occurs.
*/
Accepted = 202,
/**
* SINCE HTTP/1.1
* The server is a transforming proxy that received a 200 OK from its origin,
* but is returning a modified version of the origin's response.
*/
NonAuthoritativeInformation = 203,
/**
* The server successfully processed the request and is not returning any content.
*/
NoContent = 204,
/**
* The server successfully processed the request, but is not returning any content.
* Unlike a 204 response, this response requires that the requester reset the document view.
*/
ResetContent = 205,
/**
* The server is delivering only part of the resource (byte serving) due to a range header sent by the client.
* The range header is used by HTTP clients to enable resuming of interrupted downloads,
* or split a download into multiple simultaneous streams.
*/
PartialContent = 206,
/**
* The message body that follows is an XML message and can contain a number of separate response codes,
* depending on how many sub-requests were made.
*/
MultiStatus = 207,
/**
* The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response,
* and are not being included again.
*/
AlreadyReported = 208,
/**
* The server has fulfilled a request for the resource,
* and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
*/
ImUsed = 226,
// #endregion
// **********************************************************************************************************
//#region 300s - Redirections
// **********************************************************************************************************
/**
* Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation).
* For example, this code could be used to present multiple video format options,
* to list files with different filename extensions, or to suggest word-sense disambiguation.
*/
MultipleChoices = 300,
/**
* This and all future requests should be directed to the given URI.
*/
MovedPermanently = 301,
/**
* This is an example of industry practice contradicting the standard.
* The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect
* (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302
* with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307
* to distinguish between the two behaviours. However, some Web applications and frameworks
* use the 302 status code as if it were the 303.
*/
Found = 302,
/**
* SINCE HTTP/1.1
* The response to the request can be found under another URI using a GET method.
* When received in response to a POST (or PUT/DELETE), the client should presume that
* the server has received the data and should issue a redirect with a separate GET message.
*/
SeeOther = 303,
/**
* Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.
* In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.
*/
NotModified = 304,
/**
* SINCE HTTP/1.1
* The requested resource is available only through a proxy, the address for which is provided in the response.
* Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.
*/
UseProxy = 305,
/**
* No longer used. Originally meant "Subsequent requests should use the specified proxy."
*/
SwitchProxy = 306,
/**
* SINCE HTTP/1.1
* In this case, the request should be repeated with another URI; however, future requests should still use the original URI.
* In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request.
* For example, a POST request should be repeated using another POST request.
*/
TemporaryRedirect = 307,
/**
* The request and all future requests should be repeated using another URI.
* 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change.
* So, for example, submitting a form to a permanently redirected resource may continue smoothly.
*/
PermanentRedirect = 308,
// #endregion
// **********************************************************************************************************
// #region - 400s - Client / User messed up
// **********************************************************************************************************
/**
* The server cannot or will not process the request due to an apparent client error
* (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).
*/
BadRequest = 400,
/**
* Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet
* been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the
* requested resource. See Basic access authentication and Digest access authentication. 401 semantically means
* "unauthenticated",i.e. the user does not have the necessary credentials.
*/
Unauthorized = 401,
/**
* Reserved for future use. The original intention was that this code might be used as part of some form of digital
* cash or micro payment scheme, but that has not happened, and this code is not usually used.
* Google Developers API uses this status if a particular developer has exceeded the daily limit on requests.
*/
PaymentRequired = 402,
/**
* The request was valid, but the server is refusing action.
* The user might not have the necessary permissions for a resource.
*/
Forbidden = 403,
/**
* The requested resource could not be found but may be available in the future.
* Subsequent requests by the client are permissible.
*/
NotFound = 404,
/**
* A request method is not supported for the requested resource;
* for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
*/
MethodNotAllowed = 405,
/**
* The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.
*/
NotAcceptable = 406,
/**
* The client must first authenticate itself with the proxy.
*/
ProxyAuthenticationRequired = 407,
/**
* The server timed out waiting for the request.
* According to HTTP specifications:
* "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
*/
RequestTimeout = 408,
/**
* Indicates that the request could not be processed because of conflict in the request,
* such as an edit conflict between multiple simultaneous updates.
*/
Conflict = 409,
/**
* Indicates that the resource requested is no longer available and will not be available again.
* This should be used when a resource has been intentionally removed and the resource should be purged.
* Upon receiving a 410 status code, the client should not request the resource in the future.
* Clients such as search engines should remove the resource from their indices.
* Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
*/
Gone = 410,
/**
* The request did not specify the length of its content, which is required by the requested resource.
*/
LengthRequired = 411,
/**
* The server does not meet one of the preconditions that the requester put on the request.
*/
PreconditionFailed = 412,
/**
* The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".
*/
PayloadTooLarge = 413,
/**
* The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request,
* in which case it should be converted to a POST request.
* Called "Request-URI Too Long" previously.
*/
UriTooLong = 414,
/**
* The request entity has a media type which the server or resource does not support.
* For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
*/
UnsupportedMediaType = 415,
/**
* The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.
* For example, if the client asked for a part of the file that lies beyond the end of the file.
* Called "Requested Range Not Satisfiable" previously.
*/
RangeNotSatisfiable = 416,
/**
* The server cannot meet the requirements of the Expect request-header field.
*/
ExpectationFailed = 417,
/**
* This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol,
* and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by
* teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com.
*/
IAmATeapot = 418,
/**
* The request was directed at a server that is not able to produce a response (for example because a connection reuse).
*/
MisdirectedRequest = 421,
/**
* The request was well-formed but was unable to be followed due to semantic errors.
*/
UnprocessableEntity = 422,
/**
* The resource that is being accessed is locked.
*/
Locked = 423,
/**
* The request failed due to failure of a previous request (e.g., a PROPPATCH).
*/
FailedDependency = 424,
/**
* The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.
*/
UpgradeRequired = 426,
/**
* The origin server requires the request to be conditional.
* Intended to prevent "the 'lost update' problem, where a client
* GETs a resource's state, modifies it, and PUTs it back to the server,
* when meanwhile a third party has modified the state on the server, leading to a conflict."
*/
PreconditionRequired = 428,
/**
* The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.
*/
TooManyRequests = 429,
/**
* The server is unwilling to process the request because either an individual header field,
* or all the header fields collectively, are too large.
*/
RequestHeaderFieldsTooLarge = 431,
/**
* A server operator has received a legal demand to deny access to a resource or to a set of resources
* that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451.
*/
UnavailableForLegalReasons = 451,
// #endregion
// **********************************************************************************************************
// #region - 500s - Serve messed up
// **********************************************************************************************************
/**
* A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
*/
InternalServerError = 500,
/**
* The server either does not recognize the request method, or it lacks the ability to fulfill the request.
* Usually this implies future availability (e.g., a new feature of a web-service API).
*/
NotImplemented = 501,
/**
* The server was acting as a gateway or proxy and received an invalid response from the upstream server.
*/
BadGateway = 502,
/**
* The server is currently unavailable (because it is overloaded or down for maintenance).
* Generally, this is a temporary state.
*/
ServiceUnavailable = 503,
/**
* The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
*/
GatewayTimeout = 504,
/**
* The server does not support the HTTP protocol version used in the request
*/
HttpVersionNotSupported = 505,
/**
* Transparent content negotiation for the request results in a circular reference.
*/
VariantAlsoNegotiates = 506,
/**
* The server is unable to store the representation needed to complete the request.
*/
InsufficientStorage = 507,
/**
* The server detected an infinite loop while processing the request.
*/
LoopDetected = 508,
/**
* Further extensions to the request are required for the server to fulfill it.
*/
NotExtended = 510,
/**
* The client needs to authenticate to gain network access.
* Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used
* to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).
*/
NetworkAuthenticationRequired = 511,
// #endregion
}

View File

@ -3,6 +3,7 @@ import { View } from "../view/view";
import { EncString } from "./enc-string";
import { SymmetricCryptoKey } from "./symmetric-crypto-key";
// https://contributing.bitwarden.com/architecture/clients/data-model#domain
export default class Domain {
protected buildDomainModel<D extends Domain>(
domain: D,

View File

@ -172,6 +172,10 @@ export class Organization {
return (this.isAdmin || this.permissions.manageSso) && this.useSso;
}
get canManageDomainVerification() {
return (this.isAdmin || this.permissions.manageSso) && this.useSso;
}
get canManageScim() {
return (this.isAdmin || this.permissions.manageScim) && this.useScim;
}

View File

@ -22,6 +22,7 @@ export class EventResponse extends BaseResponse {
ipAddress: string;
installationId: string;
systemUser: EventSystemUser;
domainName: string;
constructor(response: any) {
super(response);
@ -42,5 +43,6 @@ export class EventResponse extends BaseResponse {
this.ipAddress = this.getResponseProperty("IpAddress");
this.installationId = this.getResponseProperty("InstallationId");
this.systemUser = this.getResponseProperty("SystemUser");
this.domainName = this.getResponseProperty("DomainName");
}
}

View File

@ -0,0 +1,112 @@
import { ApiService } from "../../abstractions/api.service";
import { OrgDomainApiServiceAbstraction } from "../../abstractions/organization-domain/org-domain-api.service.abstraction";
import { OrgDomainInternalServiceAbstraction } from "../../abstractions/organization-domain/org-domain.service.abstraction";
import { OrganizationDomainSsoDetailsResponse } from "../../abstractions/organization-domain/responses/organization-domain-sso-details.response";
import { OrganizationDomainResponse } from "../../abstractions/organization-domain/responses/organization-domain.response";
import { ListResponse } from "../../models/response/list.response";
import { OrganizationDomainSsoDetailsRequest } from "./requests/organization-domain-sso-details.request";
import { OrganizationDomainRequest } from "./requests/organization-domain.request";
export class OrgDomainApiService implements OrgDomainApiServiceAbstraction {
constructor(
private orgDomainService: OrgDomainInternalServiceAbstraction,
private apiService: ApiService
) {}
async getAllByOrgId(orgId: string): Promise<Array<OrganizationDomainResponse>> {
const listResponse: ListResponse<any> = await this.apiService.send(
"GET",
`/organizations/${orgId}/domain`,
null,
true,
true
);
const orgDomains = listResponse.data.map(
(resultOrgDomain: any) => new OrganizationDomainResponse(resultOrgDomain)
);
this.orgDomainService.replace(orgDomains);
return orgDomains;
}
async getByOrgIdAndOrgDomainId(
orgId: string,
orgDomainId: string
): Promise<OrganizationDomainResponse> {
const result = await this.apiService.send(
"GET",
`/organizations/${orgId}/domain/${orgDomainId}`,
null,
true,
true
);
const response = new OrganizationDomainResponse(result);
this.orgDomainService.upsert([response]);
return response;
}
async post(
orgId: string,
orgDomainReq: OrganizationDomainRequest
): Promise<OrganizationDomainResponse> {
const result = await this.apiService.send(
"POST",
`/organizations/${orgId}/domain`,
orgDomainReq,
true,
true
);
const response = new OrganizationDomainResponse(result);
this.orgDomainService.upsert([response]);
return response;
}
async verify(orgId: string, orgDomainId: string): Promise<OrganizationDomainResponse> {
const result = await this.apiService.send(
"POST",
`/organizations/${orgId}/domain/${orgDomainId}/verify`,
null,
true,
true
);
const response = new OrganizationDomainResponse(result);
this.orgDomainService.upsert([response]);
return response;
}
async delete(orgId: string, orgDomainId: string): Promise<any> {
await this.apiService.send(
"DELETE",
`/organizations/${orgId}/domain/${orgDomainId}`,
null,
true,
false
);
this.orgDomainService.delete([orgDomainId]);
}
async getClaimedOrgDomainByEmail(email: string): Promise<OrganizationDomainSsoDetailsResponse> {
const result = await this.apiService.send(
"POST",
`/organizations/domain/sso/details`,
new OrganizationDomainSsoDetailsRequest(email),
false, // anonymous
true
);
const response = new OrganizationDomainSsoDetailsResponse(result);
return response;
}
}

View File

@ -0,0 +1,73 @@
import { BehaviorSubject } from "rxjs";
import { I18nService } from "../../abstractions/i18n.service";
import { OrgDomainInternalServiceAbstraction } from "../../abstractions/organization-domain/org-domain.service.abstraction";
import { OrganizationDomainResponse } from "../../abstractions/organization-domain/responses/organization-domain.response";
import { PlatformUtilsService } from "../../abstractions/platformUtils.service";
export class OrgDomainService implements OrgDomainInternalServiceAbstraction {
protected _orgDomains$: BehaviorSubject<OrganizationDomainResponse[]> = new BehaviorSubject([]);
orgDomains$ = this._orgDomains$.asObservable();
constructor(
private platformUtilsService: PlatformUtilsService,
private i18nService: I18nService
) {}
get(orgDomainId: string): OrganizationDomainResponse {
const orgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue();
return orgDomains.find((orgDomain) => orgDomain.id === orgDomainId);
}
copyDnsTxt(dnsTxt: string): void {
this.platformUtilsService.copyToClipboard(dnsTxt);
this.platformUtilsService.showToast(
"success",
null,
this.i18nService.t("valueCopied", this.i18nService.t("dnsTxtRecord"))
);
}
upsert(orgDomains: OrganizationDomainResponse[]): void {
const existingOrgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue();
orgDomains.forEach((orgDomain: OrganizationDomainResponse) => {
// Determine if passed in orgDomain exists in existing array:
const index = existingOrgDomains.findIndex(
(existingOrgDomain) => existingOrgDomain.id === orgDomain.id
);
if (index !== -1) {
existingOrgDomains[index] = orgDomain;
} else {
existingOrgDomains.push(orgDomain);
}
});
this._orgDomains$.next(existingOrgDomains);
}
replace(orgDomains: OrganizationDomainResponse[]): void {
this._orgDomains$.next(orgDomains);
}
clearCache(): void {
this._orgDomains$.next([]);
}
delete(orgDomainIds: string[]): void {
const existingOrgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue();
orgDomainIds.forEach((orgDomainId: string) => {
const index = existingOrgDomains.findIndex(
(existingOrgDomain) => existingOrgDomain.id === orgDomainId
);
if (index !== -1) {
existingOrgDomains.splice(index, 1);
}
});
this._orgDomains$.next(existingOrgDomains);
}
}

View File

@ -0,0 +1,3 @@
export class OrganizationDomainSsoDetailsRequest {
constructor(public email: string) {}
}

View File

@ -0,0 +1,9 @@
export class OrganizationDomainRequest {
txt: string;
domainName: string;
constructor(txt: string, domainName: string) {
this.txt = txt;
this.domainName = domainName;
}
}

View File

@ -20,6 +20,8 @@ export class BitSubmitDirective implements OnInit, OnDestroy {
@Input("bitSubmit") protected handler: FunctionReturningAwaitable;
@Input() allowDisabledFormSubmit?: boolean = false;
readonly loading$ = this._loading$.asObservable();
readonly disabled$ = this._disabled$.asObservable();
@ -56,9 +58,13 @@ export class BitSubmitDirective implements OnInit, OnDestroy {
}
ngOnInit(): void {
this.formGroupDirective.statusChanges
.pipe(takeUntil(this.destroy$))
.subscribe((c) => this._disabled$.next(c === "DISABLED"));
this.formGroupDirective.statusChanges.pipe(takeUntil(this.destroy$)).subscribe((c) => {
if (this.allowDisabledFormSubmit) {
this._disabled$.next(false);
} else {
this._disabled$.next(c === "DISABLED");
}
});
}
get disabled() {

View File

@ -17,6 +17,9 @@ import { BitSubmitDirective } from "./bit-submit.directive";
* - Disables the button while the `bitSubmit` directive is processing an async submit action.
* - Disables the button while a `bitAction` directive on another button is being processed.
* - Disables form submission while the `bitAction` directive is processing an async action.
*
* Note: you must use a directive that implements the ButtonLikeAbstraction (bitButton or bitIconButton for example)
* along with this one in order to avoid provider errors.
*/
@Directive({
selector: "button[bitFormButton]",

View File

@ -105,7 +105,7 @@ class Component {
### 2. Add directive to the `form` element
The `bitSubmit` directive is required beacuse of its coordinating role inside of a form.
The `bitSubmit` directive is required because of its coordinating role inside of a form.
```html
<form [formGroup]="formGroup" [bitSubmit]="submit">...</form>
@ -121,3 +121,11 @@ Add `bitButton`, `bitFormButton`, `bitAction` directives to the button. Make sur
<button type="button" bitFormButton bitButton [bitAction]="handler">Do action</button>
<button type="button" bitFormButton bitIconButton="bwi-star" [bitAction]="handler"></button>
```
## `[bitSubmit]` Disabled Form Submit
If you need your form to be able to submit even when the form is disabled, then add `[allowDisabledFormSubmit]="true"` to your `<form>`
```html
<form [formGroup]="formGroup" [bitSubmit]="submit" [allowDisabledFormSubmit]="true">...</form>
```

View File

@ -72,6 +72,8 @@ export class BitInputDirective implements BitFormFieldControl {
@Input() hasPrefix = false;
@Input() hasSuffix = false;
@Input() showErrorsWhenDisabled? = false;
get labelForId(): string {
return this.id;
}
@ -88,7 +90,15 @@ export class BitInputDirective implements BitFormFieldControl {
}
get hasError() {
return this.ngControl?.status === "INVALID" && this.ngControl?.touched && this.isActive;
if (this.showErrorsWhenDisabled) {
return (
(this.ngControl?.status === "INVALID" || this.ngControl?.status === "DISABLED") &&
this.ngControl?.touched &&
this.ngControl?.errors != null
);
} else {
return this.ngControl?.status === "INVALID" && this.ngControl?.touched && this.isActive;
}
}
get error(): [string, any] {

View File

@ -0,0 +1,48 @@
import { Meta } from "@storybook/addon-docs";
<Meta title="Documentation/bitInput" />
# `bitInput`
`bitInput` is an Angular directive to be used on `<input>`, `<select>`, and `<textarea>`
tags in order to provide standardized TailwindCss styling, error handling, and more.
It is meant to be used within a `<bit-form-field>` custom component.
## Basic Usage Example
```html
<bit-form-field>
<bit-label>...</bit-label>
<input bitInput formControlName="..." />
<bit-hint>...</bit-hint>
</bit-form-field>
```
## Disabled `bitInput` and Error Handling
If you would like to be able to still show errors when an input is disabled for
specific validation scenarios, then set `[showErrorsWhenDisabled]="true"`
```html
<bit-form-field>
<bit-label>...</bit-label>
<input bitInput formControlName="..." [showErrorsWhenDisabled]="true" />
<bit-hint>...</bit-hint>
</bit-form-field>
```
**NOTE:** Disabling a FormControl removes validation errors so you must manually set the errors after disabling:
```ts
get exampleFormCtrl(): FormControl {
return this.form.controls.exampleFormControl as FormControl;
}
...
this.exampleFormCtrl.setErrors({
error: {
message: this.i18nService.t("...", this.exampleFormCtrl.value),
},
});
```