0

I'm trying to query my public CloudKit database using server-to-server authentication. I've generated the key according to Apple's docs, but no matter what I do I get this error:

401 - Unauthorized

data: {
  uuid: '...',
  serverErrorCode: 'AUTHENTICATION_FAILED',
  reason: 'no auth method found'
}

As far as I can tell, I've set everything up per the docs, but obviously I'm doing something wrong. Here's what I've got in my Node app so far:


let date = moment().format('YYYY-MM-DD[T]HH:mm:ss[Z]')
let domain = 'https://api.apple-cloudkit.com'
let subpath = '/database/1/iCloud.<my container>/development/public/users/current'

let key = fs.readFileSync(__dirname +'/../eckey.pem', 'utf8')
let keyID = 'abc123...'

let requestBody = ''
let bodyHash = crypto.createHash('SHA256').update(requestBody).digest('base64')

let message = date+':'+bodyHash+':'+subpath

let signature = crypto.createSign('RSA-SHA256').update(message).sign(key, 'base64')

let headers = {
  'X-Apple-CloudKit-Request-KeyID': keyID,
  'X-Apple-CloudKit-Request-ISO8601Date': date,
  'X-Apple-CloudKit-Request-SignatureV1': signature
}

try{
  await axios.post(domain+subpath, requestBody, { headers: headers })
  console.log('--- :) ---')
}catch(error){
  console.log('=== :( ===')
  console.log(error)
}

I've already reviewed this helpful SO post, but I'm still stuck.

Can anyone see what I might be doing wrong?

Clifton Labrum
  • 9,827
  • 7
  • 45
  • 86

1 Answers1

0

I had to do a ton of troubleshooting to figure this out, but for the sake of posterity, here's what I had wrong:

=== Fix # 1 ===

My date was generating local time which was inaccurate because the format implies Zulu/UTC time (because of the Z).

The fix was to add .utc() to the Moment:

let date = moment().utc().format('YYYY-MM-DD[T]HH:mm:ss[Z]')

=== Fix # 2 ===

Apparently Axios didn't like how I was formatting the request. Changing it to this (with the baseURL and url separate) works:

let response = await axios({ 
  method: 'post', 
  baseURL: baseURL, 
  url: '/records/modify', 
  data: query, 
  headers: headers 
})

Seems to be working great now with these fixes in place.

Clifton Labrum
  • 9,827
  • 7
  • 45
  • 86