-
Notifications
You must be signed in to change notification settings - Fork 2k
feat(cloudrun): Add service-to-service authentication sample #4072
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
16609f3
7270cd0
70985f8
6e4451d
d7df2f2
214df19
a6ac296
a3cfac3
21cf2c3
7f4edb8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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(); | ||
|
|
||
| app.get('/', async (req, res) => { | ||
| try { | ||
| const response = await receiveRequestAndParseAuthHeader(req); | ||
|
|
||
| const status = response.includes('Hello') ? 200 : 401; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
||
| res.status(status).send(response); | ||
| } catch (e) { | ||
| res.status(401).send(`Error verifying ID token: ${e.message}`); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: See previous comment about replacing |
||
| } | ||
| }); | ||
|
|
||
|
|
||
| const PORT = process.env.PORT || 8080; | ||
| app.listen(PORT, () => { | ||
| console.log(`Server is running on port ${PORT}`); | ||
| }); | ||
|
|
||
| module.exports = app; | ||
| 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 .", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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" | ||
| } | ||
| } | ||
| 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 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 To give more info about |
||
| try { | ||
| const ticket = await client.verifyIdToken({ | ||
| idToken: token, | ||
| audience: process.env.CLIENT_ID, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: What does 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}; | ||
| 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'; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: 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'); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: You should verify the valid token with |
||
| 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; | ||
| }); | ||
| }); | ||
There was a problem hiding this comment.
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
runfolder (for Cloud Run project), you might follow that approach.