Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 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;
29 changes: 29 additions & 0 deletions run/service-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"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": {
"axios": "^1.8.4",
"c8": "^10.0.0",
"chai": "^4.5.0",
"mocha": "^10.0.0",
"sinon": "^18.0.0",
"uuid": "^11.1.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};
96 changes: 96 additions & 0 deletions run/service-auth/test/receive.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// 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 axios = require('axios');
const {execSync} = require('child_process');
const {v4: uuidv4} = require('uuid');

const INVALID_TOKEN = 'invalid-token';
Comment thread Fixed
const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT;
const REGION = 'us-central1';

describe('receiveRequestAndParseAuthHeader sample (Cloud Run integration)', function () {
this.timeout(5 * 60 * 1000); // 5 minutes for deploy + test
const serviceName = `receive-${uuidv4().slice(0, 8)}`;
let serviceUrl;

before(() => {
console.log(`Deploying Cloud Run service: ${serviceName}...`);
execSync(
`gcloud run deploy ${serviceName} \
--project=${PROJECT_ID} \
--region=${REGION} \
--source=. \
--allow-unauthenticated \
--quiet`,
{stdio: 'inherit'}
);

console.log('Fetching service URL...');
serviceUrl = execSync(`gcloud run services describe ${serviceName} \
--project=${PROJECT_ID} \
--region=${REGION} \
--format='value(status.url)'`)
.toString()
.trim();

console.log(`Service URL: ${serviceUrl}`);
});

after(() => {
console.log(`Deleting service: ${serviceName}...`);
execSync(`gcloud run services delete ${serviceName} \
--project=${PROJECT_ID} \
--region=${REGION} \
--quiet`);
});

function getIdentityToken() {
return execSync('gcloud auth print-identity-token').toString().trim();
}

it('should respond with greeting if token is valid', async () => {
const token = getIdentityToken();
const res = await axios.get(serviceUrl, {
headers: {
Authorization: `Bearer ${token}`,
},
});

expect(res.status).to.equal(200);
expect(res.data).to.match(/^Hello, .@.\.\w+!\n$/);
});

it('should respond with anonymous if no token is provided', async () => {
const res = await axios.get(serviceUrl);
expect(res.status).to.equal(200);
expect(res.data).to.equal('Hello, anonymous user.\n');
});

it('should respond with 401 if token is invalid', async () => {
try {
await axios.get(serviceUrl, {
headers: {
Authorization: `Bearer ${INVALID_TOKEN}`,
},
});
} catch (err) {
expect(err.response.status).to.equal(401);
expect(err.response.data).to.include('Invalid token');
}
});
});
Loading