mirror of
https://github.com/apache/superset.git
synced 2026-07-10 08:45:41 +00:00
240 lines
6.7 KiB
TypeScript
240 lines
6.7 KiB
TypeScript
/**
|
||
* Licensed to the Apache Software Foundation (ASF) under one
|
||
* or more contributor license agreements. See the NOTICE file
|
||
* distributed with this work for additional information
|
||
* regarding copyright ownership. The ASF licenses this file
|
||
* to you under the Apache License, Version 2.0 (the
|
||
* "License"); you may not use this file except in compliance
|
||
* with the License. You may obtain a copy of the License at
|
||
*
|
||
* http://www.apache.org/licenses/LICENSE-2.0
|
||
*
|
||
* Unless required by applicable law or agreed to in writing,
|
||
* software distributed under the License is distributed on an
|
||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||
* KIND, either express or implied. See the License for the
|
||
* specific language governing permissions and limitations
|
||
* under the License.
|
||
*/
|
||
|
||
import { Page, APIResponse } from '@playwright/test';
|
||
|
||
export interface ApiRequestOptions {
|
||
headers?: Record<string, string>;
|
||
params?: Record<string, string>;
|
||
failOnStatusCode?: boolean;
|
||
allowMissingCsrf?: boolean;
|
||
}
|
||
|
||
/**
|
||
* Werkzeug (Flask's dev server, used in CI) periodically drops connections
|
||
* mid-request under concurrent load — surfacing as `socket hang up`,
|
||
* `ECONNRESET`, or `ERR_EMPTY_RESPONSE`. These are transport-layer
|
||
* failures, not application errors, so retrying is safe.
|
||
*
|
||
* The matcher is intentionally narrow: only retry on signatures that
|
||
* indicate the server never produced a response. Application errors
|
||
* (4xx/5xx, HTTP-level CSRF rejection) bubble up unchanged.
|
||
*/
|
||
const TRANSIENT_NETWORK_ERROR =
|
||
/socket hang up|ECONNRESET|ERR_EMPTY_RESPONSE|ECONNREFUSED|EPIPE/i;
|
||
const TRANSIENT_RETRY_ATTEMPTS = 3;
|
||
const TRANSIENT_RETRY_BACKOFF_MS = 250;
|
||
|
||
async function withTransientRetry<T>(fn: () => Promise<T>): Promise<T> {
|
||
let lastError: unknown;
|
||
for (let attempt = 0; attempt < TRANSIENT_RETRY_ATTEMPTS; attempt += 1) {
|
||
try {
|
||
return await fn();
|
||
} catch (error) {
|
||
lastError = error;
|
||
if (!TRANSIENT_NETWORK_ERROR.test(String(error))) {
|
||
throw error;
|
||
}
|
||
// Linear backoff — werkzeug recovers in 100–300 ms after a drop.
|
||
await new Promise(resolve => {
|
||
setTimeout(resolve, TRANSIENT_RETRY_BACKOFF_MS * (attempt + 1));
|
||
});
|
||
}
|
||
}
|
||
throw lastError;
|
||
}
|
||
|
||
/**
|
||
* Get base URL for Referer header
|
||
* Reads from environment variable configured in playwright.config.ts
|
||
* Preserves full base URL including path prefix (e.g., /app/prefix/)
|
||
* Normalizes to always end with '/' for consistent URL resolution
|
||
*/
|
||
function getBaseUrl(): string {
|
||
// Use environment variable which includes path prefix if configured
|
||
// Normalize to always end with '/' (matches playwright.config.ts normalization)
|
||
const url = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:8088';
|
||
return url.endsWith('/') ? url : `${url}/`;
|
||
}
|
||
|
||
export interface CsrfResult {
|
||
token: string;
|
||
error?: string;
|
||
}
|
||
|
||
/**
|
||
* Get CSRF token from the API endpoint
|
||
* Superset provides a CSRF token via api/v1/security/csrf_token/
|
||
* The session cookie is automatically included by page.request
|
||
*/
|
||
export async function getCsrfToken(page: Page): Promise<CsrfResult> {
|
||
try {
|
||
const response = await withTransientRetry(() =>
|
||
page.request.get('api/v1/security/csrf_token/', {
|
||
failOnStatusCode: false,
|
||
}),
|
||
);
|
||
|
||
if (!response.ok()) {
|
||
return {
|
||
token: '',
|
||
error: `HTTP ${response.status()} ${response.statusText()}`,
|
||
};
|
||
}
|
||
|
||
const json = await response.json();
|
||
return { token: json.result || '' };
|
||
} catch (error) {
|
||
return { token: '', error: String(error) };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Build headers for mutation requests (POST, PUT, PATCH, DELETE)
|
||
* Includes CSRF token and Referer for Flask-WTF CSRFProtect
|
||
*/
|
||
async function buildHeaders(
|
||
page: Page,
|
||
options?: ApiRequestOptions,
|
||
): Promise<Record<string, string>> {
|
||
const { token: csrfToken, error: csrfError } = await getCsrfToken(page);
|
||
const headers: Record<string, string> = {
|
||
'Content-Type': 'application/json',
|
||
...options?.headers,
|
||
};
|
||
|
||
// Include CSRF token and Referer for Flask-WTF CSRFProtect
|
||
if (csrfToken) {
|
||
headers['X-CSRFToken'] = csrfToken;
|
||
headers['Referer'] = getBaseUrl();
|
||
} else if (!options?.allowMissingCsrf) {
|
||
const errorDetail = csrfError ? ` (${csrfError})` : '';
|
||
throw new Error(
|
||
`Missing CSRF token${errorDetail} - mutation requests require authentication. ` +
|
||
'Ensure global authentication completed or test has valid session.',
|
||
);
|
||
}
|
||
|
||
return headers;
|
||
}
|
||
|
||
/**
|
||
* Send a GET request
|
||
* Uses page.request to automatically include browser authentication
|
||
*/
|
||
export async function apiGet(
|
||
page: Page,
|
||
url: string,
|
||
options?: ApiRequestOptions,
|
||
): Promise<APIResponse> {
|
||
return withTransientRetry(() =>
|
||
page.request.get(url, {
|
||
headers: options?.headers,
|
||
params: options?.params,
|
||
failOnStatusCode: options?.failOnStatusCode ?? true,
|
||
}),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Send a POST request
|
||
* Uses page.request to automatically include browser authentication
|
||
*/
|
||
export async function apiPost(
|
||
page: Page,
|
||
url: string,
|
||
data?: unknown,
|
||
options?: ApiRequestOptions,
|
||
): Promise<APIResponse> {
|
||
const headers = await buildHeaders(page, options);
|
||
|
||
return withTransientRetry(() =>
|
||
page.request.post(url, {
|
||
data,
|
||
headers,
|
||
params: options?.params,
|
||
failOnStatusCode: options?.failOnStatusCode ?? true,
|
||
}),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Send a PUT request
|
||
* Uses page.request to automatically include browser authentication
|
||
*/
|
||
export async function apiPut(
|
||
page: Page,
|
||
url: string,
|
||
data?: unknown,
|
||
options?: ApiRequestOptions,
|
||
): Promise<APIResponse> {
|
||
const headers = await buildHeaders(page, options);
|
||
|
||
return withTransientRetry(() =>
|
||
page.request.put(url, {
|
||
data,
|
||
headers,
|
||
params: options?.params,
|
||
failOnStatusCode: options?.failOnStatusCode ?? true,
|
||
}),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Send a PATCH request
|
||
* Uses page.request to automatically include browser authentication
|
||
*/
|
||
export async function apiPatch(
|
||
page: Page,
|
||
url: string,
|
||
data?: unknown,
|
||
options?: ApiRequestOptions,
|
||
): Promise<APIResponse> {
|
||
const headers = await buildHeaders(page, options);
|
||
|
||
return withTransientRetry(() =>
|
||
page.request.patch(url, {
|
||
data,
|
||
headers,
|
||
params: options?.params,
|
||
failOnStatusCode: options?.failOnStatusCode ?? true,
|
||
}),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Send a DELETE request
|
||
* Uses page.request to automatically include browser authentication
|
||
*/
|
||
export async function apiDelete(
|
||
page: Page,
|
||
url: string,
|
||
options?: ApiRequestOptions,
|
||
): Promise<APIResponse> {
|
||
const headers = await buildHeaders(page, options);
|
||
|
||
return withTransientRetry(() =>
|
||
page.request.delete(url, {
|
||
headers,
|
||
params: options?.params,
|
||
failOnStatusCode: options?.failOnStatusCode ?? true,
|
||
}),
|
||
);
|
||
}
|