Skip to content

Commit

Permalink
add authorization
Browse files Browse the repository at this point in the history
Signed-off-by: Miroslav Bajtoš <[email protected]>
  • Loading branch information
bajtos committed Jan 24, 2025
1 parent b9da942 commit d83ace3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 11 deletions.
31 changes: 27 additions & 4 deletions api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,17 @@ import { recordNetworkInfoTelemetry } from '../common/telemetry.js'
import { satisfies } from 'compare-versions'
import { ethAddressFromDelegated } from '@glif/filecoin-address'

const handler = async (req, res, client, domain) => {
/** @import {IncomingMessage, ServerResponse} from 'node:http' */
/** @import pg from 'pg' */

/*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {pg.Client} client
* @param {string} domain
* @param {string} dealIngestionAccessToken
*/
const handler = async (req, res, client, domain, dealIngestionAccessToken) => {
if (req.headers.host.split(':')[0] !== domain) {
return redirect(res, `https://${domain}${req.url}`)
}
Expand Down Expand Up @@ -37,7 +47,7 @@ const handler = async (req, res, client, domain) => {
} else if (segs[0] === 'inspect-request' && req.method === 'GET') {
await inspectRequest(req, res)
} else if (segs[0] === 'eligible-deals-batch' && req.method === 'POST') {
await ingestEligibleDeals(req, res, client)
await ingestEligibleDeals(req, res, client, dealIngestionAccessToken)
} else {
notFound(res)
}
Expand Down Expand Up @@ -401,7 +411,19 @@ export const inspectRequest = async (req, res) => {
})
}

export const ingestEligibleDeals = async (req, res, client) => {
/**
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {pg.Client} client
* @param {string} dealIngestionAccessToken
*/
export const ingestEligibleDeals = async (req, res, client, dealIngestionAccessToken) => {
if (req.headers.authorization !== `Bearer ${dealIngestionAccessToken}`) {
res.statusCode = 403
res.end('Unauthorized')
return
}

const body = await getRawBody(req, { limit: '100mb' })
const deals = JSON.parse(body)
assert(Array.isArray(deals), 400, 'Invalid JSON Body, must be an array')
Expand Down Expand Up @@ -449,12 +471,13 @@ export const ingestEligibleDeals = async (req, res, client) => {
export const createHandler = async ({
client,
logger,
dealIngestionAccessToken,
domain
}) => {
return (req, res) => {
const start = new Date()
logger.request(`${req.method} ${req.url} ...`)
handler(req, res, client, domain)
handler(req, res, client, domain, dealIngestionAccessToken)
.catch(err => errorHandler(res, err, logger))
.then(() => {
logger.request(`${req.method} ${req.url} ${res.statusCode} (${new Date() - start}ms)`)
Expand Down
36 changes: 29 additions & 7 deletions api/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const participantAddress = '0x000000000000000000000000000000000000dEaD'
const sparkVersion = '1.13.0' // This must be in sync with the minimum supported client version
const currentSparkRoundNumber = 42n

const VALID_DEAL_INGESTION_TOKEN = 'authorized-token'

const VALID_MEASUREMENT = {
cid: 'bafytest',
providerAddress: '/dns4/localhost/tcp/8080',
Expand Down Expand Up @@ -70,6 +72,7 @@ describe('Routes', () => {
error: console.error,
request () {}
},
dealIngestionAccessToken: VALID_DEAL_INGESTION_TOKEN,
domain: '127.0.0.1'
})
server = http.createServer(handler)
Expand Down Expand Up @@ -775,6 +778,13 @@ describe('Routes', () => {
})

describe('POST /eligible-deals-batch', () => {
// A miner ID value not found in real data
const TEST_MINER_ID = 'f000'
// A client ID value not found in real data
const TEST_CLIENT_ID = 'f001'

const AUTH_HEADERS = { authorization: `Bearer ${VALID_DEAL_INGESTION_TOKEN}` }

beforeEach(async () => {
await client.query(
'DELETE FROM eligible_deals WHERE miner_id = $1',
Expand All @@ -783,11 +793,6 @@ describe('Routes', () => {
})

it('ingests new deals', async () => {
// A miner ID value not found in real data
const TEST_MINER_ID = 'f000'
// A client ID value not found in real data
const TEST_CLIENT_ID = 'f001'

const deals = [{
minerId: TEST_MINER_ID,
clientId: TEST_CLIENT_ID,
Expand All @@ -799,6 +804,7 @@ describe('Routes', () => {

const res = await fetch(`${spark}/eligible-deals-batch`, {
method: 'POST',
headers: AUTH_HEADERS,
body: JSON.stringify(deals)
})
await assertResponseStatus(res, 200)
Expand Down Expand Up @@ -828,6 +834,7 @@ describe('Routes', () => {

const res = await fetch(`${spark}/eligible-deals-batch`, {
method: 'POST',
headers: AUTH_HEADERS,
body: JSON.stringify([{
minerId: f05Deal.miner_id,
clientId: f05Deal.client_id,
Expand Down Expand Up @@ -858,8 +865,23 @@ describe('Routes', () => {
assert.deepStrictEqual(rows, [f05Deal])
})

it.skip('rejects unauthorized requests', async () => {
// TODO
it('rejects unauthorized requests', async () => {
const deals = [{
minerId: TEST_MINER_ID,
clientId: TEST_CLIENT_ID,
pieceCid: 'bagaone',
pieceSize: '34359738368',
payloadCid: 'bafyone',
expiresAt: '2100-01-01'
}]

const res = await fetch(`${spark}/eligible-deals-batch`, {
method: 'POST',
body: JSON.stringify(deals)
})
await assertResponseStatus(res, 403)
const body = await res.text()
assert.strictEqual(body, 'Unauthorized')
})
})
})

0 comments on commit d83ace3

Please sign in to comment.