Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions run/service-auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const express = require('express');
const {receiveRequestAndParseAuthHeader} = require('./receive');

const app = express();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: How are you running this app during the tests?

For example, on Python receive_test.py#L15 it's creating a Cloud Run Service.
As the sample is inside the run folder (for Cloud Run project), you might follow that approach.


app.get('/', async (req, res) => {
try {
const response = await receiveRequestAndParseAuthHeader(req);

const status = response.includes('Hello') ? 200 : 401;
Copy link
Copy Markdown
Contributor

@eapl-gemugami eapl-gemugami Apr 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: I'd recommend to use a standard enumeration of HTTP Status codes instead of an int, which is not as descriptive for people still learning

For example http.html#httpstatus_codes
Or https://www.npmjs.com/package/http-status-codes

const status = response.includes('Hello') ? StatusCodes.OK : StatusCodes.UNAUTHORIZED;

res.status(status).send(response);
} catch (e) {
res.status(401).send(`Error verifying ID token: ${e.message}`);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: See previous comment about replacing 401 with StatusCodes.UNAUTHORIZED

}
});
Comment thread Dismissed

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

module.exports = app;
27 changes: 27 additions & 0 deletions run/service-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "service-auth",
"description": "Node.js samples for authenticated service-to-service communication",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"author": "Google LLC",
"engines": {
"node": "20.x"
},
"scripts": {
"start": "node index.js",
"deploy": "gcloud run deploy service-auth --source .",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: Is this deploy being run during the tests, or is it more oriented for the developer?

"unit-test": "c8 mocha -p -j 2 test/ --timeout=10000 --exit",
"test": "npm run unit-test"
},
"dependencies": {
"express": "^4.17.1",
"google-auth-library": "^9.0.0"
},
"devDependencies": {
"c8": "^10.0.0",
"chai": "^4.5.0",
"mocha": "^10.0.0",
"sinon": "^18.0.0"
}
}
60 changes: 60 additions & 0 deletions run/service-auth/receive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(req) {
// [START auth_validate_and_decode_bearer_token_on_express]
// [START cloudrun_service_to_service_receive]
const {OAuth2Client} = require('google-auth-library');

const client = new OAuth2Client();

// Inner function that parses and verifies the token.
async function receiveRequestAndParseAuthHeader(request) {
const authHeader = request.headers.authorization;
if (authHeader) {
// Split the auth type and token value from the Authorization header.
const [type, token] = authHeader.split(' ');

if (type.toLowerCase() === 'bearer') {
// More info on verifyIdToken:
// https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thought: Linking to another sample is not the best way to give more information about a function. Linking to a documentation page (explaining the function or the sample) might be better.

suggestion: In verifyIdToken-iap.js I can't find the verifyIdToken function, and I only see verifySignedJwtWithCertsAsync which might be misleading.

To give more info about verifyIdToken you might link to oauth2client#google_auth_library_OAuth2Client_verifyIdToken

try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: process.env.CLIENT_ID,
Copy link
Copy Markdown
Contributor

@eapl-gemugami eapl-gemugami Apr 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: What does env.CLIENT_ID contain?

In the linked sample I see this pattern for the audience:

expectedAudience = `/projects/${projectNumber}/global/backendServices/${backendServiceId}`;

});
const payload = ticket.getPayload();
console.log(`Hello, ${payload.email}!\n`);
return;
} catch (err) {
console.log(`Invalid token: ${err.message}\n`);
return;
}
} else {
console.log(`Unhandled header format(${type}).\n`);
return;
}
}

console.log('Hello, anonymous user.\n');
}

await receiveRequestAndParseAuthHeader(req);
}
// [END cloudrun_service_to_service_receive]
// [END auth_validate_and_decode_bearer_token_on_express]

module.exports = {main};
73 changes: 73 additions & 0 deletions run/service-auth/test/receive.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {expect} = require('chai');
const sinon = require('sinon');
const {OAuth2Client} = require('google-auth-library');
const {main} = require('../receive');

const TEST_VALID_TOKEN = 'test-valid-token';
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thought: I don't think this is correct, you should get a valid token with the following command:
gcloud auth print-identity-token

See an example here: receive_test.py#L117

const TEST_INVALID_TOKEN = 'test-invalid-token';

describe('receiveRequestAndParseAuthHeader sample', () => {
let verifyStub, consoleStub;

beforeEach(() => {
verifyStub = sinon.stub(OAuth2Client.prototype, 'verifyIdToken');
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: You should verify the valid token with OAuth2Client.verifyIdToken, not creating a stub.

consoleStub = sinon.stub(console, 'log');
});

afterEach(() => {
sinon.restore();
});

it('should log greeting if token is valid', async () => {
const mockReq = {
headers: {
authorization: `Bearer ${TEST_VALID_TOKEN}`,
},
};

verifyStub.resolves({
getPayload: () => ({email: 'test@example.com'}),
});

await main(mockReq);
expect(consoleStub.calledWith('Hello, test@example.com!\n')).to.be.true;
});

it('should log error message if token is invalid', async () => {
const mockReq = {
headers: {
authorization: `Bearer ${TEST_INVALID_TOKEN}`,
},
};

verifyStub.rejects(new Error('invalid'));

await main(mockReq);
expect(consoleStub.calledWithMatch(/Invalid token: invalid/)).to.be.true;
});

it('should log anonymous message if no auth header', async () => {
const mockReq = {
headers: {},
};

await main(mockReq);
expect(consoleStub.calledWith('Hello, anonymous user.\n')).to.be.true;
});
});
Loading