Service Account Error: Forbidden Image Access with Google Docs BatchUpdate

Encountering forbidden errors when updating public images in Google Docs via a service account. Code sample:

function sendApiReq(endpoint, dataObj) {
  var auth = retrieveAuth();
  auth.resetToken();
  var response = UrlFetchApp.fetch(endpoint, {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + auth.getToken() },
    contentType: 'application/json',
    payload: JSON.stringify(dataObj),
    muteHttpExceptions: true
  });
  return JSON.parse(response.getContentText());
}

function buildImgUpdate(imgId, docId, tag) {
  var updates = [];
  var driveEndpoint = Utilities.formatString('https://www.googleapis.com/drive/v3/files/%s?supportsAllDrives=true&fields=webContentLink', imgId);
  var driveResp = UrlFetchApp.fetch(driveEndpoint, { muteHttpExceptions: true });
  var imgUrl = JSON.parse(driveResp.getContentText()).webContentLink;

  var docsEndpoint = Utilities.formatString('https://docs.googleapis.com/v1/documents/%s?fields=inlineObjects', docId);
  var docsResp = UrlFetchApp.fetch(docsEndpoint, { muteHttpExceptions: true });
  var docData = JSON.parse(docsResp.getContentText());
  for (var key in docData.inlineObjects) {
    var caption = docData.inlineObjects[key].inlineObjectProperties.embeddedObject.title;
    if (caption && caption === tag) {
      updates.push({
        updateImage: {
          imageObjectId: key,
          uri: imgUrl,
          method: 'CENTER_CROP'
        }
      });
    }
  }
  return updates;
}

var apiURL = 'https://docs.googleapis.com/v1/documents/YOUR_DOC_ID:batchUpdate';
var payload = { requests: buildImgUpdate('YOUR_IMAGE_ID', 'YOUR_DOC_ID', 'MERGE_FIELD') };
var result = sendApiReq(apiURL, payload);

The challenge you’re facing appears to be related to permission issues when the service account tries to access the image on Drive. In my experience, I discovered that even if the document is public, device-level authentication does not automatically extend to file-level access. I resolved a similar issue by ensuring that the image had explicit sharing permissions for the service account. It was also important to verify that the access token was properly refreshed between calls, as an outdated token can trigger these errors. Reviewing both Drive and Docs API permissions can help identify the root cause.