Instabug / Instabug-React-Native

In-app feedback and bug reporting tool for React Native
https://instabug.com/platforms/react-native
MIT License
312 stars 100 forks source link

NetworkLogger.setNetworkDataObfuscationHandler not working as expected in iOS (React Native) #1003

Open Sergirsanchez opened 1 year ago

Sergirsanchez commented 1 year ago

Steps to Reproduce the Problem

Call init method and the try to obfuscate some data in requests headers with NetworkLogger.setNetworkDataObfuscationHandler

Expected Behavior

Some headers should have their data obfuscated in reports

Actual Behavior

For Android works as expected, but for iOS seems that the method is not trigger when we send requests against our own API, with third party services seems to works. We are using redux-saga to do queries against our own API.

Instabug integration code

...

SDK Version

v11.9.1, but I'm seeing the error from v10.13.0 . Didn't check in previous versions

React Native, iOS and Android Versions

Device Model

a7medev commented 1 year ago

Hi @Sergirsanchez! Thanks for reporting this issue. Can you please provide the initialization code and the code for sending the network request? Also, can you please confirm if this issue is still relevant on the latest version of our SDK v11.13.0?

Sergirsanchez commented 1 year ago

Hi @a7medev! I upgrade the SDK to v11.13.0 and I can confirm that the problem still happens. I attach a code snippet about what you requested me:

Instabug service file:

class InstabugService {
  ...
  public setup = (attributes?: Record<string, string>): void => {

      Instabug.init({
        token: INSTABUG_TOKEN,
        invocationEvents: isProductionEnv ? [InvocationEvent.none] : [InvocationEvent.shake],
      });

      if (!isProductionEnv) {
        BugReporting.setShakingThresholdForAndroid(this.androidThreshold);
        BugReporting.setShakingThresholdForiPhone(this.iosThreshold);
      }

      Instabug.setColorTheme(ColorTheme.dark);
      Instabug.setWelcomeMessageMode(WelcomeMessageMode.disabled);
      Instabug.setString(StringKey.invocationHeader, XXX);

      if (attributes) {
        Object.entries(attributes).forEach(([key, value]) => {
          Instabug.setUserAttribute(key, value);
        });
      }

      BugReporting.setReportTypes([ReportType.bug, ReportType.feedback]);

      NetworkLogger.setNetworkDataObfuscationHandler(async (networkData) => {
        let data = { ...networkData };
        try {
          if (data.requestBody) {
            data.requestBody = JSON.parse(data.requestBody);
          }
          data = obfuscateSensitiveData(data);
        } catch (error) {
          if (isDebugEnv) console.warn('[Instabug] Obfuscate Network Logs Error:', error);
        }
        return data;
      });
    };
 ...
  }

Call from App file: InstabugService.setup(attributes);

a7medev commented 1 year ago

@Sergirsanchez Can you also provide me with the snippet where you make the network call?

Sergirsanchez commented 1 year ago

Sorry for not replying, but I'm a bit busy these days. During today or tomorrow I'll send you the snippet 😄

a7medev commented 1 year ago

@Sergirsanchez No problem. To keep you updated, we were able to reproduce it and are looking into possible solutions to this problem, we will update you once we have something to share. Again, thanks for reporting this issue and for the very helpful details 🙏🏼.

Sergirsanchez commented 1 year ago

@a7medev Sorry for the delay, I attach some code snippets about how we do the queries. If you need anything else feel free to ask for it, and thanks for the update!

// Saga to make requests
export function* makeRequestSaga<T>(query){

  const headers = new Headers([
    ['Content-Type', 'application/json'],
    ['Accept', 'application/json'],
    ['authorization', token || ''],
    ['apollographql-client-name', XXX],
    ['apollographql-client-version', VersionNumber.appVersion],
  ]);
  ...

  try {
    const [{ data }] = (yield all([
      call(graphQLRequest, `${env.API_BASE_URL}`, document, variables, headers),
      delay(minDelay || 0),
    ])) as [{ data: T }, boolean];
    ...
    return data;
  } catch (error) {
    ...
  }
  ...
}

// graphQLRequest method code

export const graphQLRequest = async <T>(
  url,
  document,
  variables,
  headers,
) => {
  let response: GraphQLResponse;

  // Just to make sure we're working with DocumentNodes, query could also be a string
  const query = isString(document)
    ? gql`
        ${document}
      `
    : document;

  const operationName = getOperationAST(query)?.name?.value;
  const body = JSON.stringify({
    query: query.loc && query.loc.source.body,
    variables,
    ...(operationName ? { operationName } : {}),
  });
  ...
  if (isIOS)
    // iOS native fetch implemented by us
    response = JSON.parse(await nativeFetch({ url, method: 'POST', body, headers }));
  }
  ...
};
a7medev commented 1 year ago

Hi @Sergirsanchez! Another update on this issue, we will be handling this issue in an upcoming cycle not in support so it might take some time. Until then you can add an obfuscation handler on the native iOS side in the ios/AppDelegate.mm file as below:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
  // You will need to start the SDK natively as well (don't remove the Instabug.init call on the JS side)
  [Instabug startWithToken:@"YOUR_APP_TOKEN" invocationEvents:IBGInvocationEventFloatingButton | IBGInvocationEventShake];
  // Add your obfuscation handler here
  [IBGNetworkLogger setRequestObfuscationHandler:^NSURLRequest * _Nonnull(NSURLRequest * _Nonnull request) {
      NSMutableURLRequest *myRequest = [request mutableCopy];
      NSMutableDictionary<NSString *, NSString *> *headers = [myRequest.allHTTPHeaderFields mutableCopy];
      headers[@"Authorization"] = @"SECRET_IOS";
      myRequest.allHTTPHeaderFields = headers;
      return myRequest;
  }];
  ...
}

Please note that this is a temporary solution until a fix comes out in our production SDK.

Sergirsanchez commented 1 year ago

@a7medev Thanks for the temporary solution! I'll keep an eye on future versions

SanderNiesten commented 4 months ago

Is there any update on the progress of this request. The bug is also a hinderance in our development right now.

a7medev commented 4 months ago

Hello @SanderNiesten! Can you please share more details on the issue you're facing? Also, do you use a native solution for data fetching (not using XMLHttpRequest, fetch, or anything that depends on them like Axios)?