Skip to content

Commit

Permalink
fix: add extra logging for incorrect headers (#637)
Browse files Browse the repository at this point in the history
* fix: add extra logging for incorrect headers

* fix header

* respond to comments

* Update src/index.ts

Co-authored-by: d-goog <[email protected]>

* Update test/index.test.ts

Co-authored-by: d-goog <[email protected]>

* Update test/index.test.ts

Co-authored-by: d-goog <[email protected]>

* Update index.ts

---------

Co-authored-by: d-goog <[email protected]>
  • Loading branch information
sofisl and d-goog committed Jan 30, 2025
1 parent bd79ae1 commit edafa87
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ package-lock.json
gcp-metadata.tgz
docs/
__pycache__
.DS_Store
.DS_Store
*.tgz
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"license": "Apache-2.0",
"dependencies": {
"gaxios": "^6.1.1",
"google-logging-utils": "^0.0.2",
"json-bigint": "^1.0.0"
},
"devDependencies": {
Expand Down
13 changes: 10 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {GaxiosError, GaxiosOptions, GaxiosResponse, request} from 'gaxios';
import {OutgoingHttpHeaders} from 'http';
import jsonBigint = require('json-bigint');
import {detectGCPResidency} from './gcp-residency';
import * as logger from 'google-logging-utils';

export const BASE_PATH = '/computeMetadata/v1';
export const HOST_ADDRESS = 'http://169.254.169.254';
Expand All @@ -27,6 +28,8 @@ export const HEADER_NAME = 'Metadata-Flavor';
export const HEADER_VALUE = 'Google';
export const HEADERS = Object.freeze({[HEADER_NAME]: HEADER_VALUE});

const log = logger.log('gcp metadata');

/**
* Metadata server detection override options.
*
Expand Down Expand Up @@ -151,18 +154,22 @@ async function metadataAccessor<T>(
}

const requestMethod = fastFail ? fastFailMetadataRequest : request;
const res = await requestMethod<T>({
const req: GaxiosOptions = {
url: `${getBaseUrl()}/${metadataKey}`,
headers: {...HEADERS, ...headers},
retryConfig: {noResponseRetries},
params,
responseType: 'text',
timeout: requestTimeout(),
});
} as GaxiosOptions;
log.info('instance request %j', req);

const res = await requestMethod<T>(req);
log.info('instance metadata is %s', res.data);
// NOTE: node.js converts all incoming headers to lower case.
if (res.headers[HEADER_NAME.toLowerCase()] !== HEADER_VALUE) {
throw new Error(
`Invalid response from metadata service: incorrect ${HEADER_NAME} header.`
`Invalid response from metadata service: incorrect ${HEADER_NAME} header. Expected '${HEADER_VALUE}', got ${res.headers[HEADER_NAME.toLowerCase()] ? `'${res.headers[HEADER_NAME.toLowerCase()]}'` : 'no header'}`,
);
}

Expand Down
46 changes: 46 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,52 @@ describe('unit test', () => {
scope.done();
});

it('should throw a valuable error when headers do not match', async () => {
const scope = nock(HOST)
.get(`${PATH}/${TYPE}/${PROPERTY}`)
.reply(
200,
{},
{
[gcp.HEADER_NAME.toLowerCase()]: 'wrongHeader',
},
);

await assert.rejects(
async () => {
await gcp.instance({property: PROPERTY});
},
err => {
assert(err instanceof Error);
assert.strictEqual(
err.message,
"Invalid response from metadata service: incorrect Metadata-Flavor header. Expected 'Google', got 'wrongHeader'",
);
scope.done();
return true;
},
);
});

it('should throw a valuable error when header does not exist', async () => {
const scope = nock(HOST).get(`${PATH}/${TYPE}/${PROPERTY}`).reply(200, {});

await assert.rejects(
async () => {
await gcp.instance({property: PROPERTY});
},
err => {
assert(err instanceof Error);
assert.strictEqual(
err.message,
"Invalid response from metadata service: incorrect Metadata-Flavor header. Expected 'Google', got no header",
);
scope.done();
return true;
},
);
});

it('should return large numbers as BigNumber values', async () => {
const BIG_NUMBER_STRING = '3279739563200103600';
const scope = nock(HOST)
Expand Down

0 comments on commit edafa87

Please sign in to comment.