-
Notifications
You must be signed in to change notification settings - Fork 124
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add server side connection auth management
- Loading branch information
Showing
15 changed files
with
382 additions
and
66 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
{ | ||
"//": "private refers to what's internal to snyk, i.e. the snyk.io server", | ||
"private": [ | ||
{ | ||
"//": "send any type of request to our connected clients", | ||
"method": "any", | ||
"path": "/*" | ||
} | ||
], | ||
"public": [ | ||
{ | ||
"//": "send any type of request to our connected clients", | ||
"method": "any", | ||
"path": "/*" | ||
} | ||
] | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { getConfig } from '../../common/config/config'; | ||
import { PostFilterPreparedRequest } from '../../common/relay/prepareRequest'; | ||
import { maskToken } from '../../common/utils/token'; | ||
import { makeSingleRawRequestToDownstream } from '../../hybrid-sdk/http/request'; | ||
import { log as logger } from '../../logs/logger'; | ||
|
||
export const validateBrokerClientCredentials = async ( | ||
authHeaderValue: string, | ||
brokerClientId: string, | ||
brokerConnectionIdentifier: string, | ||
) => { | ||
const body = { | ||
data: { | ||
type: 'broker_connection', | ||
attributes: { | ||
broker_client_id: brokerClientId, | ||
}, | ||
}, | ||
}; | ||
|
||
const req: PostFilterPreparedRequest = { | ||
url: `${ | ||
getConfig().apiHostname | ||
}/hidden/brokers/connections/${brokerConnectionIdentifier}/auth/validate?version=2024-02-08~experimental`, | ||
headers: { | ||
authorization: authHeaderValue, | ||
'Content-type': 'application/vnd.api+json', | ||
}, | ||
method: 'POST', | ||
body: JSON.stringify(body), | ||
}; | ||
logger.debug( | ||
{ maskToken: maskToken(brokerConnectionIdentifier) }, | ||
`Validate Broker Client Credentials request`, | ||
); | ||
const response = await makeSingleRawRequestToDownstream(req); | ||
logger.debug( | ||
{ validationResponseCode: response.statusCode }, | ||
'Validate Broker Client Credentials response', | ||
); | ||
if (response.statusCode === 201) { | ||
return true; | ||
} else { | ||
logger.debug( | ||
{ statusCode: response.statusCode, message: response.statusText }, | ||
`Broker ${brokerConnectionIdentifier} client ID ${brokerClientId} failed validation.`, | ||
); | ||
return false; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { getConfig } from '../../common/config/config'; | ||
import { getSocketConnections } from '../socket'; | ||
import { log as logger } from '../../logs/logger'; | ||
|
||
export const disconnectConnectionsWithStaleCreds = async () => { | ||
const connections = getSocketConnections(); | ||
const connectionsIterator = connections.entries(); | ||
for (const [identifier, connection] of connectionsIterator) { | ||
connection.forEach((client) => { | ||
if (!isDateWithinAnHourAndFiveSec(client.credsValidationTime!)) { | ||
logger.debug( | ||
{ | ||
connection: `${identifier}`, | ||
credsLastValidated: client.credsValidationTime, | ||
}, | ||
'Cutting off connection.', | ||
); | ||
client.socket!.end(); | ||
} | ||
}); | ||
} | ||
}; | ||
|
||
const isDateWithinAnHourAndFiveSec = (date: string): boolean => { | ||
const dateInMs = new Date(date); // Convert ISO string to Date | ||
const now = Date.now(); // Get current time in milliseconds | ||
const staleConnectionsCleanupInterval = | ||
getConfig().STALE_CONNECTIONS_CLEANUP_FREQUENCY ?? 65 * 60 * 1000; // 1h05 hour in milliseconds | ||
return now - dateInMs.getTime() < staleConnectionsCleanupInterval; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import { Request, Response } from 'express'; | ||
import { validateBrokerClientCredentials } from '../auth/authHelpers'; | ||
import { log as logger } from '../../logs/logger'; | ||
import { validate } from 'uuid'; | ||
import { getSocketConnectionByIdentifier } from '../socket'; | ||
import { maskToken } from '../../common/utils/token'; | ||
interface BrokerConnectionAuthRequest { | ||
data: { | ||
attributes: { | ||
broker_client_id: string; | ||
}; | ||
id: string; | ||
type: 'broker_connection'; | ||
}; | ||
} | ||
export const authRefreshHandler = async (req: Request, res: Response) => { | ||
const credentialsFromHeader = | ||
req.headers['Authorization'] ?? req.headers['authorization']; | ||
const role = req.query['connection_role']; | ||
const credentials = `${credentialsFromHeader}`; | ||
const brokerAppClientId = | ||
req.headers[`${process.env.SNYK_INTERNAL_AUTH_CLIENT_ID_HEADER}`]; | ||
const identifier = req.params.identifier; | ||
logger.debug( | ||
{ maskedToken: maskToken(identifier), brokerAppClientId, role }, | ||
`Auth Refresh`, | ||
); | ||
const body = JSON.parse(req.body.toString()) as BrokerConnectionAuthRequest; | ||
const brokerClientId = body.data.attributes.broker_client_id; | ||
if (!validate(brokerClientId) || !validate(brokerAppClientId)) { | ||
logger.warn( | ||
{ identifier, brokerClientId, brokerAppClientId }, | ||
'Invalid credentials', | ||
); | ||
return res.status(401).send('Invalid parameters or credentials.'); | ||
} | ||
|
||
const connection = getSocketConnectionByIdentifier(identifier); | ||
const currentClient = connection | ||
? connection.find( | ||
(x) => x.metadata.clientId === brokerClientId && x.role === role, | ||
) | ||
: null; | ||
logger.debug({ identifier, brokerClientId, role }, 'Validating credentials'); | ||
if ( | ||
credentials === undefined || | ||
brokerAppClientId === undefined || | ||
!connection || | ||
!currentClient | ||
) { | ||
logger.debug( | ||
{ identifier, brokerClientId, role, credentials }, | ||
'Invalid credentials', | ||
); | ||
return res.status(401).send('Invalid credentials.'); | ||
} else { | ||
const credsCheckResponse = await validateBrokerClientCredentials( | ||
credentials, | ||
brokerClientId as string, | ||
identifier, | ||
); | ||
logger.debug( | ||
{ credsCheckResponse: credsCheckResponse }, | ||
'Client Creds validation response.', | ||
); | ||
if (credsCheckResponse) { | ||
// Refresh client validation time | ||
const nowDate = new Date().toISOString(); | ||
currentClient.credsValidationTime = nowDate; | ||
const currentClientIndex = connection.findIndex( | ||
(x) => x.brokerClientId === brokerClientId && x.role === role, | ||
); | ||
if (currentClientIndex > -1) { | ||
connection[currentClientIndex] = currentClient; | ||
return res.status(201).send('OK'); | ||
} else { | ||
return res.status(500).send('Unable to find client connection.'); | ||
} | ||
} else { | ||
logger.debug( | ||
{ identifier, brokerClientId, role, credentials }, | ||
'Invalid credentials - Creds check response returned false', | ||
); | ||
currentClient.socket!.end(); | ||
return res.status(401).send('Invalid credentials.'); | ||
} | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.