setAppMetadata after a mgmt API call fails with invalid JSON

Migrating a rule to an pre-login action. We have other actions in place that have successfully used api.user.setAppMetadata() to set values for the user logging in.

The rule in question essentially would look up a user in an existing Auth0 DB (by e-mail) and copy over app_metadata from that user to the user logging in. It took a minute to transition the call to the updated 4.10.0 management interface, but the basics of the action code is this:

// Guard against expensive API call
if (event.user.app_metadata !== undefined
          && Object.keys(event.user.app_metadata).length !== 0)) {
  return;
}

var ManagementClient = require('auth0').ManagementClient; // 4.10.0 as a dependency
var mgmt = new ManagementClient({ domain: event.secrets.domain, clientId: event.secrets.clientId, clientSecret: event.secrets.clientSecret});

// Non-auth0 users have an ID like: samlp|idpx|joe@example.com
var emailToLookup = event.user.user_id.split('|')[2].toLowerCase();

try {
  const userResponse = await mgmt.usersByEmail.getByEmail({ email: emailToLookup });
  var users = userResponse.data;  // This returns the correct information as expected
  var user = // ... Choose a user from the array

  if (auth0User && auth0User.app_metadata) {
    var global_uid = auth0User.app_metadata.global_uid; // typeof global_uid === string

    // This next line fails with the error below
    api.user.setAppMetadata("global_uid", global_uid);
  }
} catch (err) {
  console.log(err);
}

The error we receive is:

Error: Unexpected app_metadata format. Must be a valid JSON object
    at Rc.setAppMetadata (/data/io/e7f6ebd25690877b78ef07f4f34675b7b703741f.js:5:14152)
    at exports.onExecutePostLogin (/data/io/node18-actions/fe636bd9-4add-4e2e-871d-33bf16f5ba39/webtask.js:77:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /data/io/e7f6ebd25690877b78ef07f4f34675b7b703741f.js:7:846

I have verified that the value for our global_uid is a string. Could this be because we have a mgmt API call before this? Are we using the results from the API call incorrectly?

Hi @mwilberbp,

Welcome to the Auth0 Community!

There seems to be an issue with how you use the api.user.setAppMetadata() method.

I recommend using the Actions built-in debugger interface to test your Action script and verify that the values are a valid JSON object.

If you need to test this in a legitimate login flow, you could use the Real-time Webtask Logs Extension to trace the login events.

You could also do a quick test by passing in a legitimate value, such as api.user.setAppMetadata("test," "value") to deduce whether the error is originating from the global_uid variable.

Thanks,
Rueben

Thanks Rueben. I do have console.log messages in the code that I am executing and it shows for instance that the item I’m pulling off for the global_uid is a string.

var auth0User = users.find((user) => user.user_id.split('|')[0] === 'auth0');
    console.log("Found " + auth0User.app_metadata["global_uid"] 
        + "  ["+ typeof auth0User.app_metadata.global_uid+"] ");

Prints Found 289aa82f-d406-4c1a-af59-715012025d01 [string]

The other suggestion was to simply call the API with known values so I tried:

api.user.setAppMetadata("global_uid", "testing123");

For this I get the same JSON error:

Error: Unexpected app_metadata format. Must be a valid JSON object
    at Rc.setAppMetadata (/data/io/e8af224db65b3cc135716846bfcfd0349b36d4e8.js:5:14152)
    at exports.onExecutePostLogin (/data/io/node18-actions/74bea806-3ba4-4828-b1cb-2e7074f6325c/webtask.js:70:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /data/io/e8af224db65b3cc135716846bfcfd0349b36d4e8.js:7:846

My first thought was that it had to do with the types being returns from the ManagementAPI calls, but this second test makes it appear that there’s something amiss to call api.user. after I’ve called the Management interface. Odd, but that’s one explanation I can think of.

1 Like

Hi @mwilberbp,

I have double-checked your code and tested it on my side. The api.user.setAppMetadata() method works fine when tested alone.

It’s hard to tell what is causing this error at the moment. Perhaps you could comment out the api.user.setAppMetadata() method and see if that resolves the issue.

If the error persists, then it must be coming from somewhere else.

Thanks,
Rueben

Thank you. I have found that this error occurs simply because I have added auth0@4.10.0 as a dependency. If I remove this dependency (and the mgmt api call of course) and call the api.user.setAppMetadata("global_uid", "testing123") with those static values, the action finishes with an API call as expected.

Before concluding that the auth0@4.10.0 dependency was the issue. I have also tried commenting out the Mgmt API call and then calling api.user.setAppMetadata("global_uid", "testing123"). This throws the same error. I have then stepped further back and commented out the creation of the the ManagementClient as well, with the same error being thrown.

1 Like

Hi @rueben.tiow -

I am facing the exact same issue.

Trying something as basic as:
await api.user.setAppMetadata('test', {});

throws the same error that @mwilberbp had.

I can’t even follow the guidance to null out a property:
await api.user.setAppMetadata('test', null);

This also throws the same error:
Error: Unexpected app_metadata format. Must be a valid JSON object

I am also adding the auth@4.10.0 library to my action.

I will try to remove that dependency for now, but was using it to gain access to the AuthorizationClient versus using axios or something.

Quick update @rueben.tiow and @mwilberbp:

I tried removing the Auth@4.10.0 and replacing it with Axios and still received the same error.

Here are some logs in my action during testing. I shouldn’t be receiving empty arrays for these three items, but I am.

Auth0-Auth-Extension: Policy data { groups: [], roles: [], permissions: [] }
Auth0-Auth-Extension: Error: Unexpected app_metadata format. Must be a valid JSON object

It’s possible that the test data I’m using is not working correctly or invalid and that’s causing some issue?

I did deploy the action into production and a real trigger workflow. In that environment, everything seems work. So my hunch is that something either in my input test data is causing issues or there is some conflict with the IDE editor/test environment on Auth0 side.

@mwilberbp you might try your code in a production trigger/workflow, but I would remove any api.deny requests until you confirm via logging or other means that the action is indeed not throwing an error at those setAppMetadata code lines.

1 Like

Thanks @chimpeenuts! I had that on my list to try. I had assumed that if it didn’t work in the sim environment there wasn’t any hope for it in a deployed environment.

I can confirm that deploying the original code using auth0@4.10.0 as a dependency does work when deployed into an action pipeline but still does not work in the action custom library environment.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.