Skip to content

Commit

Permalink
feat: respond with unique error message when blocked API key is used (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
e-schneid committed May 20, 2022
1 parent 306c19e commit faae1db
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
16 changes: 16 additions & 0 deletions packages/api/src/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
MagicTokenRequiredError,
NoTokenError,
PinningUnauthorizedError,
TokenBlockedError,
TokenNotFoundError,
UnrecognisedTokenError,
UserNotFoundError
Expand Down Expand Up @@ -171,6 +172,17 @@ async function tryWeb3ApiToken (token, env) {
// we have a web3 api token, but it's no longer valid
throw new TokenNotFoundError()
}

if (apiToken.isDeleted) {
const isBlocked = await checkIsTokenBlocked(apiToken, env)

if (isBlocked) {
throw new TokenBlockedError()
} else {
throw new TokenNotFoundError()
}
}

return apiToken
}

Expand All @@ -182,6 +194,10 @@ function getUserTags (userId, env) {
return env.db.getUserTags(userId)
}

function checkIsTokenBlocked (token, env) {
return env.db.checkIsTokenBlocked(token)
}

function verifyAuthToken (token, decoded, env) {
return env.db.getKey(decoded.sub, token)
}
Expand Down
9 changes: 9 additions & 0 deletions packages/api/src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ export class TokenNotFoundError extends HTTPError {
}
TokenNotFoundError.CODE = 'ERROR_TOKEN_NOT_FOUND'

export class TokenBlockedError extends HTTPError {
constructor (msg = 'API token is blocked, please contact support@web3.storage') {
super(msg, 403)
this.name = 'TokenBlocked'
this.code = TokenBlockedError.CODE
}
}
TokenBlockedError.CODE = 'ERROR_TOKEN_BLOCKED'

export class UnrecognisedTokenError extends HTTPError {
constructor (msg = 'Could not parse provided API token') {
super(msg, 401)
Expand Down
20 changes: 18 additions & 2 deletions packages/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,13 +751,13 @@ export class DBClient {
keys:auth_key_user_id_fkey(
_id:id::text,
name,
secret
secret,
deleted_at
)
`)
.match({
issuer
})
.filter('keys.deleted_at', 'is', null)
.eq('keys.secret', secret)

if (error) {
Expand All @@ -776,13 +776,29 @@ export class DBClient {
return {
_id: keyData.keys[0]._id,
name: keyData.keys[0].name,
isDeleted: Boolean(keyData.keys[0].deleted_at),
user: {
_id: keyData._id,
issuer: keyData.issuer
}
}
}

async checkIsTokenBlocked (token) {
const { data, error } = await this._client
.from('auth_key_history')
.select('status')
.filter('deleted_at', 'is', null)
.eq('auth_key_id', token._id)
.single()

if (error) {
throw new DBError(error)
}

return data?.status === 'Blocked'
}

/**
* List auth keys of a given user.
*
Expand Down

0 comments on commit faae1db

Please sign in to comment.