Skip to content
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

Change: check expiration of legacy tokens, reject if necessary #3645

Merged
merged 2 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 1 addition & 18 deletions node-packages/commons/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,24 +113,7 @@ let transportOptions: {
timeout: 60000
};

if (!envHasConfig('JWTSECRET') || !envHasConfig('JWTAUDIENCE')) {
logger.error(
'Unable to create api token due to missing `JWTSECRET`/`JWTAUDIENCE` environment variables'
);
} else {
const apiAdminToken = createJWTWithoutUserId({
payload: {
role: 'admin',
iss: 'lagoon-commons',
aud: getConfigFromEnv('JWTAUDIENCE')
},
jwtSecret: getConfigFromEnv('JWTSECRET')
});

transportOptions.headers.Authorization = `Bearer ${apiAdminToken}`;
}

const transport = new Transport(`${getConfigFromEnv('API_HOST', 'http://api:3000')}/graphql`, transportOptions);
const transport = new Transport(`${getConfigFromEnv('API_HOST', 'http://api:3000')}/graphql`, {transportOptions});

export const graphqlapi = new Lokka({ transport });

Expand Down
33 changes: 31 additions & 2 deletions node-packages/commons/src/lokka-transport-http-retry.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
import { Transport as LokkaTransportHttp } from '@lagoon/lokka-transport-http';
import fetchUrl from 'node-fetch';
import { createJWTWithoutUserId } from './jwt';
import { logger } from './logs/local-logger';
import { envHasConfig, getConfigFromEnv } from './util/config';

// generate a fresh token for each operation
const generateToken = () => {
if (!envHasConfig('JWTSECRET') || !envHasConfig('JWTAUDIENCE')) {
logger.error(
'Unable to create api token due to missing `JWTSECRET`/`JWTAUDIENCE` environment variables'
);
} else {
const apiAdminToken = createJWTWithoutUserId({
payload: {
role: 'admin',
iss: 'lagoon-internal',
aud: getConfigFromEnv('JWTAUDIENCE'),
// set a 60s expiry on the token
exp: Math.floor(Date.now() / 1000) + 60
},
jwtSecret: getConfigFromEnv('JWTSECRET')
});

return `Bearer ${apiAdminToken}`;
}
return ""
}

class NetworkError extends Error {}
class ApiError extends Error {}

// Retries the fetch if operational/network errors occur
const retryFetch = (endpoint, options, retriesLeft = 5, interval = 1000) =>
new Promise((resolve, reject) =>
fetchUrl(endpoint, options)
new Promise((resolve, reject) => {
// get a fresh token for every request
options.headers.Authorization = generateToken()
return fetchUrl(endpoint, options)
.then(response => {
if (response.status !== 200 && response.status !== 400) {
throw new NetworkError(`Invalid status code: ${response.status}`);
Expand Down Expand Up @@ -38,6 +66,7 @@ const retryFetch = (endpoint, options, retriesLeft = 5, interval = 1000) =>
retryFetch(endpoint, options, retriesLeft - 1).then(resolve, reject);
}, interval);
})
}
);

export class Transport extends LokkaTransportHttp {
Expand Down
22 changes: 21 additions & 1 deletion services/api/src/util/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { saveRedisKeycloakCache } from '../clients/redisClient';

interface ILegacyToken {
iat: string;
exp: string;
iss: string;
sub: string;
aud: string;
Expand Down Expand Up @@ -105,7 +106,26 @@ export const getCredentialsForLegacyToken = async token => {
throw new Error('Decoding token resulted in "null" or "undefined".');
}

const { role = 'none', aud, sub, iss, iat } = decoded;
const { role = 'none', aud, sub, iss, iat, exp } = decoded;

// check the expiration on legacy tokens, reject them if necessary
const maxExpiry = getConfigFromEnv('LEGACY_EXPIRY_MAX', '3600') // 1hour default
const rejectLegacyExpiry = getConfigFromEnv('LEGACY_EXPIRY_REJECT', 'false') // don't reject intially, just log
if (exp) {
if ((parseInt(exp)-parseInt(iat)) > parseInt(maxExpiry)) {
const msg = `Legacy token (sub:${sub}; iss:${iss}) expiry ${(parseInt(exp)-parseInt(iat))} is greater than ${parseInt(maxExpiry)}`
logger.warn(msg);
if (rejectLegacyExpiry == "true") {
throw new Error(msg);
}
}
} else {
rocketeerbkw marked this conversation as resolved.
Show resolved Hide resolved
const msg = `Legacy token (sub:${sub}; iss:${iss}) has no expiry`
logger.warn(msg);
if (rejectLegacyExpiry == "true") {
throw new Error(msg);
}
}

if (aud !== getConfigFromEnv('JWTAUDIENCE')) {
throw new Error('Token audience mismatch.');
Expand Down