Move sending intern requests from client to server

Summary: This diff moves send intern request from the browser to the server. The reason to make this change is that making such requests from a browser environment causes CORS restrictions to kick in.

Reviewed By: nikoant

Differential Revision: D32835449

fbshipit-source-id: e8e92e51ca963aa50b3c859bb61c2381171e85ae
This commit is contained in:
Michel Weststrate
2021-12-08 04:25:28 -08:00
committed by Facebook GitHub Bot
parent ad4a55f263
commit 943d535e86
18 changed files with 180 additions and 96 deletions

View File

@@ -38,6 +38,13 @@ import {PluginManager} from './plugins/PluginManager';
import {runHealthcheck, getHealthChecks} from './utils/runHealthchecks';
import {openFile} from './utils/openFile';
import {getChangelog} from './utils/pathUtils';
import {sendScribeLogs} from './fb-stubs/sendScribeLogs';
import {
internGraphGETAPIRequest,
internGraphPOSTAPIRequest,
} from './fb-stubs/internRequests';
export const SERVICE_FLIPPER = 'flipper.oAuthToken';
/**
* FlipperServer takes care of all incoming device & client connections.
@@ -184,14 +191,24 @@ export class FlipperServerImpl implements FlipperServer {
exec<Event extends keyof FlipperServerCommands>(
event: Event,
...args: Parameters<FlipperServerCommands[Event]>
): ReturnType<FlipperServerCommands[Event]> {
console.debug(`[FlipperServer] command ${event}: `, args);
const handler: (...args: any[]) => Promise<any> =
this.commandHandler[event];
if (!handler) {
throw new Error(`Unimplemented server command: ${event}`);
): ReturnType<FlipperServerCommands[Event]>;
async exec<Event extends keyof FlipperServerCommands>(
event: Event,
...args: any[]
): Promise<any> {
try {
const handler: (...args: any[]) => Promise<any> =
this.commandHandler[event];
if (!handler) {
throw new Error(`Unimplemented server command: ${event}`);
}
const result = await handler(...args);
console.debug(`[FlipperServer] command '${event}' - OK`);
return result;
} catch (e) {
console.debug(`[FlipperServer] command '${event}' - ERROR: ${e} `);
throw e;
}
return handler(...args) as any;
}
private commandHandler: FlipperServerCommands = {
@@ -276,6 +293,21 @@ export class FlipperServerImpl implements FlipperServer {
'doctor-get-healthchecks': getHealthChecks,
'doctor-run-healthcheck': runHealthcheck,
'open-file': openFile,
'intern-graph-post': async (endpoint, formfields, filefields, options) => {
const token = await this.keytarManager.retrieveToken(SERVICE_FLIPPER);
return internGraphPOSTAPIRequest(
endpoint,
formfields,
filefields,
options,
token,
);
},
'intern-graph-get': async (endpoint, params, options) => {
const token = await this.keytarManager.retrieveToken(SERVICE_FLIPPER);
return internGraphGETAPIRequest(endpoint, params, options, token);
},
'intern-upload-scribe-logs': sendScribeLogs,
};
registerDevice(device: ServerDevice) {

View File

@@ -95,7 +95,6 @@ class ServerController extends EventEmitter implements ServerEventsListener {
this.timestamps = new Map();
this.certificateProvider = new CertificateProvider(
this,
this.logger,
getFlipperServerConfig().settings,
);
this.connectionTracker = new ConnectionTracker(this.logger);

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {GraphFileUpload, GraphResponse} from 'flipper-common';
/* eslint-disable @typescript-eslint/no-unused-vars */
export async function internGraphPOSTAPIRequest(
endpoint: string,
formFields: {
[key: string]: any;
},
fileFields: Record<string, GraphFileUpload>,
options: {
timeout?: number;
internGraphUrl?: string;
},
token: string,
): Promise<GraphResponse> {
throw new Error('Feature not implemented');
}
export async function internGraphGETAPIRequest(
endpoint: string,
params: {
[key: string]: any;
},
_options: {
timeout?: number;
internGraphUrl?: string;
},
token: string,
): Promise<GraphResponse> {
throw new Error('Feature not implemented');
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export async function sendScribeLogs(
_messages: {category: string; message: string}[],
): Promise<void> {}

View File

@@ -7,8 +7,6 @@
* @format
*/
import {Logger} from 'flipper-common';
import {internGraphPOSTAPIRequest} from 'flipper-common';
import ServerController from '../comms/ServerController';
import {promisify} from 'util';
import fs from 'fs-extra';
@@ -28,6 +26,8 @@ import {Client as ADBClient} from 'adbkit';
import archiver from 'archiver';
import {timeout, isTest} from 'flipper-common';
import {v4 as uuid} from 'uuid';
import {internGraphPOSTAPIRequest} from '../fb-stubs/internRequests';
import {SERVICE_FLIPPER} from '../FlipperServerImpl';
export type CertificateExchangeMedium = 'FS_ACCESS' | 'WWW' | 'NONE';
@@ -89,7 +89,6 @@ type CertificateProviderConfig = {
* Flipper CA.
*/
export default class CertificateProvider {
private logger: Logger;
private _adb: Promise<ADBClient> | undefined;
private didCertificateSetup = false;
private config: CertificateProviderConfig;
@@ -105,12 +104,7 @@ export default class CertificateProvider {
throw new Error('Android is not enabled in settings');
}
constructor(
server: ServerController,
logger: Logger,
config: CertificateProviderConfig,
) {
this.logger = logger;
constructor(server: ServerController, config: CertificateProviderConfig) {
// TODO: refactor this code to create promise lazily
this._adb = config.enableAndroid
? (getAdbClient(config).catch((_e) => {
@@ -133,15 +127,25 @@ export default class CertificateProvider {
zipPath: string,
deviceID: string,
): Promise<void> => {
const buff = await fs.readFile(zipPath);
const file = new File([buff], 'certs.zip');
return reportPlatformFailures(
timeout(
5 * 60 * 1000,
internGraphPOSTAPIRequest('flipper/certificates', {
certificate_zip: file,
device_id: deviceID,
}),
internGraphPOSTAPIRequest(
'flipper/certificates',
{
device_id: deviceID,
},
{
certificate_zip: {
path: zipPath,
filename: 'certs.zip',
},
},
{timeout: 5 * 60 * 1000},
await this.server.flipperServer.keytarManager.retrieveToken(
SERVICE_FLIPPER,
),
).then(() => {}),
'Timed out uploading Flipper certificates to WWW.',
),
'uploadCertificates',

View File

@@ -21,6 +21,7 @@ export class KeytarManager {
if (this.keytar == null) {
throw new Error('Keytar is not available.');
}
await this.keytar.deletePassword(service, os.userInfo().username);
await this.keytar.setPassword(service, os.userInfo().username, password);
}
@@ -40,6 +41,7 @@ export class KeytarManager {
if (!token) {
throw new UserNotSignedInError();
}
return token;
}
}