feat(console): friendly quota exhausted screen (#5790)

* fix: remove access interceptor for console

* feat: show dialog on exhausted requests

* fix exhausted cookie handling

* fix quota exhausted screen

* read instance mgmt from environment.json

* fix interceptors

* don't check cookie on environment.json

* fix environment.json path

* exclude environment.json from cookie check

* remove cookie before loading env

* use UTC to delete the cookie

* delete cookie before fetching env

* simplify cookie handling

* lint

* review cleanup

* use exhausted property from env json

* fix bootstrapping

* lint

* always open mgmt link if present

* chore: fetch env json before ng serve

* wait for cookie to be removed

* fix typo

* don't wait for cookie to be set
This commit is contained in:
Elio Bischof
2023-05-19 10:48:39 +00:00
committed by GitHub
parent 2e86c44aa5
commit b475068140
26 changed files with 336 additions and 155 deletions
+12 -28
View File
@@ -1,9 +1,10 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { switchMap } from 'rxjs';
import { PolicyComponentServiceType } from '../modules/policies/policy-component-types.enum';
import { Theme } from '../modules/policies/private-labeling-policy/private-labeling-policy.component';
import { EnvironmentService } from './environment.service';
import { StorageService } from './storage.service';
const authorizationKey = 'Authorization';
@@ -69,46 +70,29 @@ export const ENDPOINT = {
providedIn: 'root',
})
export class AssetService {
private serviceUrl!: Promise<string>;
private accessToken: string = '';
constructor(private http: HttpClient, private storageService: StorageService) {
constructor(private envService: EnvironmentService, private http: HttpClient, private storageService: StorageService) {
const aT = this.storageService.getItem(accessTokenStorageKey);
if (aT) {
this.accessToken = aT;
}
this.serviceUrl = this.getServiceUrl();
}
private async getServiceUrl(): Promise<string> {
const url = await lastValueFrom(this.http.get('./assets/environment.json'))
.then((data: any) => {
if (data && data.api) {
return data.api;
}
})
.catch((error) => {
console.error(error);
});
return url;
}
public upload(endpoint: AssetEndpoint | string, body: any, orgId?: string): Promise<any> {
const headers: any = {
[authorizationKey]: `${bearerPrefix} ${this.accessToken}`,
};
if (orgId) {
headers[orgKey] = `${orgId}`;
}
return this.serviceUrl.then((url) =>
this.http
.post(`${url}/assets/v1/${endpoint}`, body, {
headers: headers,
})
.toPromise(),
);
return this.envService.env
.pipe(
switchMap((env) =>
this.http.post(`${env.api}/assets/v1/${endpoint}`, body, {
headers: headers,
}),
),
)
.toPromise();
}
}
@@ -35,10 +35,8 @@ export class AuthenticationService {
Object.assign(this.authConfig, partialConfig);
}
this.oauthService.configure(this.authConfig);
this.oauthService.strictDiscoveryDocumentValidation = false;
await this.oauthService.loadDiscoveryDocumentAndTryLogin();
this._authenticated = this.oauthService.hasValidAccessToken();
if (!this.oauthService.hasValidIdToken() || !this.authenticated || partialConfig || force) {
const newState = await lastValueFrom(this.statehandler.createState());
@@ -0,0 +1,88 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable, of, shareReplay, switchMap, throwError } from 'rxjs';
import { AdminServiceClient } from '../proto/generated/zitadel/AdminServiceClientPb';
import { AuthServiceClient } from '../proto/generated/zitadel/AuthServiceClientPb';
import { ManagementServiceClient } from '../proto/generated/zitadel/ManagementServiceClientPb';
import { ExhaustedService } from './exhausted.service';
export interface Environment {
api: string;
clientid: string;
issuer: string;
customer_portal?: string;
instance_management_url?: string;
exhausted?: boolean;
}
interface WellKnown {
authorization_endpoint: string;
end_session_endpoint: string;
introspection_endpoint: string;
token_endpoint: string;
userinfo_endpoint: string;
}
@Injectable({
providedIn: 'root',
})
export class EnvironmentService {
private environmentJsonPath = './assets/environment.json';
private wellknownPath = '/.well-known/openid-configuration`';
public auth!: AuthServiceClient;
public mgmt!: ManagementServiceClient;
public admin!: AdminServiceClient;
private environment$: Observable<Environment>;
private wellKnown$: Observable<WellKnown>;
constructor(private http: HttpClient, private exhaustedSvc: ExhaustedService) {
this.environment$ = this.createEnvironment();
this.wellKnown$ = this.createWellKnown(this.environment$);
}
// env returns an `Observable<Environment>` that can be subscribed to whenever needed.
// It makes the HTTP call exactly once and replays the cached result.
// If the responses exhausted property is true, the exhaused dialog is shown.
get env() {
return this.environment$;
}
// wellKnown returns an `Observable<Environment>` that can be subscribed to whenever needed.
// It makes the HTTP call exactly once and replays the cached result.
get wellKnown() {
return this.wellKnown$;
}
private createEnvironment() {
return this.http.get<Environment>(this.environmentJsonPath).pipe(
catchError((err) => {
console.error('Getting environment.json failed', err);
return throwError(() => err);
}),
switchMap((env) => {
const env$ = of(env);
if (env.exhausted) {
return this.exhaustedSvc.showExhaustedDialog(env$).pipe(map(() => env));
}
return env$;
}),
// Cache the first response, then replay it
shareReplay(1),
);
}
private createWellKnown(environment$: Observable<Environment>) {
return environment$.pipe(
catchError((err) => {
console.error('Getting well-known OIDC configuration failed', err);
return throwError(() => err);
}),
switchMap((env) => {
return this.http.get<WellKnown>(`${env.issuer}${this.wellknownPath}`);
}),
// Cache the first response, then replay it
shareReplay(1),
);
}
}
@@ -0,0 +1,41 @@
import { Injectable } from '@angular/core';
import { MatLegacyDialog as MatDialog } from '@angular/material/legacy-dialog';
import { map, Observable, of, switchMap, tap } from 'rxjs';
import { WarnDialogComponent } from '../modules/warn-dialog/warn-dialog.component';
import { Environment } from './environment.service';
@Injectable({
providedIn: 'root',
})
export class ExhaustedService {
private isClosed = true;
constructor(private dialog: MatDialog) {}
public showExhaustedDialog(env$: Observable<Environment>) {
if (!this.isClosed) {
return of(undefined);
}
this.isClosed = false;
return this.dialog
.open(WarnDialogComponent, {
data: {
confirmKey: 'ACTIONS.CONTINUE',
titleKey: 'ERRORS.EXHAUSTED.TITLE',
descriptionKey: 'ERRORS.EXHAUSTED.DESCRIPTION',
},
disableClose: true,
width: '400px',
id: 'authenticated-requests-exhausted-dialog',
})
.afterClosed()
.pipe(
switchMap(() => env$),
tap((env) => {
// Just reload if there is no instance management url
location.href = env.instance_management_url || location.href;
}),
map(() => undefined),
);
}
}
+32 -19
View File
@@ -1,18 +1,22 @@
import { PlatformLocation } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatLegacyDialog as MatDialog } from '@angular/material/legacy-dialog';
import { TranslateService } from '@ngx-translate/core';
import { AuthConfig } from 'angular-oauth2-oidc';
import { catchError, switchMap, tap, throwError } from 'rxjs';
import { AdminServiceClient } from '../proto/generated/zitadel/AdminServiceClientPb';
import { AuthServiceClient } from '../proto/generated/zitadel/AuthServiceClientPb';
import { ManagementServiceClient } from '../proto/generated/zitadel/ManagementServiceClientPb';
import { AuthenticationService } from './authentication.service';
import { EnvironmentService } from './environment.service';
import { ExhaustedService } from './exhausted.service';
import { AuthInterceptor } from './interceptors/auth.interceptor';
import { ExhaustedGrpcInterceptor } from './interceptors/exhausted.grpc.interceptor';
import { I18nInterceptor } from './interceptors/i18n.interceptor';
import { OrgInterceptor } from './interceptors/org.interceptor';
import { StorageService } from './storage.service';
import { ThemeService } from './theme.service';
@Injectable({
providedIn: 'root',
@@ -23,22 +27,30 @@ export class GrpcService {
public admin!: AdminServiceClient;
constructor(
private http: HttpClient,
private envService: EnvironmentService,
private platformLocation: PlatformLocation,
private authenticationService: AuthenticationService,
private storageService: StorageService,
private dialog: MatDialog,
private translate: TranslateService,
private exhaustedService: ExhaustedService,
private themeService: ThemeService,
) {}
public async loadAppEnvironment(): Promise<any> {
return this.http
.get('./assets/environment.json')
.toPromise()
.then((data: any) => {
if (data && data.api && data.issuer) {
public loadAppEnvironment(): Promise<any> {
this.themeService.applyLabelPolicy();
// We use the browser language until we can make API requests to get the users configured language.
return this.translate
.use(this.translate.getBrowserLang() || this.translate.defaultLang)
.pipe(
switchMap(() => this.envService.env),
tap((env) => {
if (!env?.api || !env?.issuer) {
return;
}
const interceptors = {
unaryInterceptors: [
new ExhaustedGrpcInterceptor(this.exhaustedService, this.envService),
new OrgInterceptor(this.storageService),
new AuthInterceptor(this.authenticationService, this.storageService, this.dialog),
new I18nInterceptor(this.translate),
@@ -46,19 +58,19 @@ export class GrpcService {
};
this.auth = new AuthServiceClient(
data.api,
env.api,
null,
// @ts-ignore
interceptors,
);
this.mgmt = new ManagementServiceClient(
data.api,
env.api,
null,
// @ts-ignore
interceptors,
);
this.admin = new AdminServiceClient(
data.api,
env.api,
null,
// @ts-ignore
interceptors,
@@ -68,19 +80,20 @@ export class GrpcService {
scope: 'openid profile email',
responseType: 'code',
oidc: true,
clientId: data.clientid,
issuer: data.issuer,
clientId: env.clientid,
issuer: env.issuer,
redirectUri: window.location.origin + this.platformLocation.getBaseHrefFromDOM() + 'auth/callback',
postLogoutRedirectUri: window.location.origin + this.platformLocation.getBaseHrefFromDOM() + 'signedout',
requireHttps: false,
};
this.authenticationService.initConfig(authConfig);
}
return Promise.resolve(data);
})
.catch(() => {
console.error('Failed to load environment from assets');
});
}),
catchError((err) => {
console.error('Failed to load environment from assets', err);
return throwError(() => err);
}),
)
.toPromise();
}
}
@@ -43,7 +43,7 @@ export class AuthInterceptor<TReq = unknown, TResp = unknown> implements UnaryIn
.then((response: any) => {
return response;
})
.catch((error: any) => {
.catch(async (error: any) => {
if (error.code === 16) {
this.triggerDialog.next(true);
}
@@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import { Request, StatusCode, UnaryInterceptor, UnaryResponse } from 'grpc-web';
import { EnvironmentService } from '../environment.service';
import { ExhaustedService } from '../exhausted.service';
/**
* ExhaustedGrpcInterceptor shows the exhausted dialog after receiving a gRPC response status 8.
*/
@Injectable({ providedIn: 'root' })
export class ExhaustedGrpcInterceptor<TReq = unknown, TResp = unknown> implements UnaryInterceptor<TReq, TResp> {
constructor(private exhaustedSvc: ExhaustedService, private envSvc: EnvironmentService) {}
public async intercept(
request: Request<TReq, TResp>,
invoker: (request: Request<TReq, TResp>) => Promise<UnaryResponse<TReq, TResp>>,
): Promise<UnaryResponse<TReq, TResp>> {
return invoker(request).catch((error: any) => {
if (error.code === StatusCode.RESOURCE_EXHAUSTED) {
return this.exhaustedSvc
.showExhaustedDialog(this.envSvc.env)
.toPromise()
.then(() => {
throw error;
});
}
throw error;
});
}
}
@@ -0,0 +1,24 @@
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, switchMap, throwError } from 'rxjs';
import { EnvironmentService } from '../environment.service';
import { ExhaustedService } from '../exhausted.service';
/**
* ExhaustedHttpInterceptor shows the exhausted dialog after receiving an HTTP response status 429.
*/
@Injectable()
export class ExhaustedHttpInterceptor implements HttpInterceptor {
constructor(private exhaustedSvc: ExhaustedService, private envSvc: EnvironmentService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 429) {
return this.exhaustedSvc.showExhaustedDialog(this.envSvc.env).pipe(switchMap(() => throwError(() => error)));
}
return throwError(() => error);
}),
);
}
}
@@ -1,43 +0,0 @@
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { OAuthModuleConfig } from 'angular-oauth2-oidc';
import { Observable } from 'rxjs';
import { Org } from '../../proto/generated/zitadel/org_pb';
import { StorageKey, StorageLocation, StorageService } from '../storage.service';
const orgKey = 'x-zitadel-orgid';
export abstract class HttpOrgInterceptor implements HttpInterceptor {
private org!: Org.AsObject;
protected get validUrls(): string[] {
return this.oauthModuleConfig.resourceServer.allowedUrls || [];
}
constructor(private storageService: StorageService, protected oauthModuleConfig: OAuthModuleConfig) {
const org: Org.AsObject | null = this.storageService.getItem(StorageKey.organization, StorageLocation.session);
if (org) {
this.org = org;
}
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!this.urlValidation(req.url)) {
return next.handle(req);
}
return next.handle(
req.clone({
setHeaders: {
[orgKey]: this.org.id,
},
}),
);
}
private urlValidation(toIntercept: string): boolean {
const URLS = ['https://api.zitadel.dev/assets', 'https://api.zitadel.ch/assets'];
return URLS.findIndex((url) => toIntercept.startsWith(url)) > -1;
}
}