-
Notifications
You must be signed in to change notification settings - Fork 17
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
feat(clients): add generateSecuredApiKey to java #3167
Changes from 3 commits
6d22ffd
47cbfc4
1c21d7a
890a7f3
02ff7d7
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 |
---|---|---|
|
@@ -181,10 +181,10 @@ public GetApiKeyResponse waitForApiKey( | |
} | ||
|
||
/** | ||
* Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. | ||
* Helper: Wait for an API key to be added or deleted based on a given `operation`. | ||
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. how come it's not updated anymore? 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. this is just an override, because the apiKey param is optional, if you don't provide it you can't do an update, but just below you have the version with apiKey, they supports 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. ahhh yes my bad then all good |
||
* | ||
* @param operation The `operation` that was done on a `key`. (ADD or DELETE only) | ||
* @param key The `key` that has been added, deleted or updated. | ||
* @param key The `key` that has been added or deleted. | ||
* @param maxRetries The maximum number of retry. 50 by default. (optional) | ||
* @param timeout The function to decide how long to wait between retries. min(retries * 200, 5000) by default. (optional) | ||
* @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) | ||
|
@@ -204,10 +204,10 @@ public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, Ap | |
return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); | ||
} | ||
/** | ||
* Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. | ||
* Helper: Wait for an API key to be added or deleted based on a given `operation`. | ||
* | ||
* @param operation The `operation` that was done on a `key`. (ADD or DELETE only) | ||
* @param key The `key` that has been added, deleted or updated. | ||
* @param key The `key` that has been added or deleted. | ||
* @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) | ||
*/ | ||
public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, RequestOptions requestOptions) { | ||
|
@@ -226,10 +226,10 @@ public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, Ap | |
return this.waitForApiKey(operation, key, apiKey, maxRetries, timeout, null); | ||
} | ||
/** | ||
* Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. | ||
* Helper: Wait for an API key to be added or deleted based on a given `operation`. | ||
* | ||
* @param operation The `operation` that was done on a `key`. (ADD or DELETE only) | ||
* @param key The `key` that has been added, deleted or updated. | ||
* @param key The `key` that has been added or deleted. | ||
* @param maxRetries The maximum number of retry. 50 by default. (optional) | ||
* @param timeout The function to decide how long to wait between retries. min(retries * 200, 5000) by default. (optional) | ||
*/ | ||
|
@@ -247,10 +247,10 @@ public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, Ap | |
return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); | ||
} | ||
/** | ||
* Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. | ||
* Helper: Wait for an API key to be added or deleted based on a given `operation`. | ||
* | ||
* @param operation The `operation` that was done on a `key`. (ADD or DELETE only) | ||
* @param key The `key` that has been added, deleted or updated. | ||
* @param key The `key` that has been added or deleted. | ||
*/ | ||
public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key) { | ||
return this.waitForApiKey(operation, key, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); | ||
|
@@ -640,4 +640,89 @@ return new ReplaceAllObjectsResponse() | |
.setBatchResponses(batchResponses) | ||
.setMoveOperationResponse(moveOperationResponse); | ||
} | ||
|
||
/** | ||
* Helper: Generates a secured API key based on the given `parent_api_key` and given | ||
* `restrictions`. | ||
* | ||
* @param parentApiKey API key to generate from. | ||
* @param restrictions Restrictions to add the key | ||
* @throws Exception if an error occurs during the encoding | ||
* @throws AlgoliaRetryException When the retry has failed on all hosts | ||
* @throws AlgoliaApiException When the API sends an http error code | ||
* @throws AlgoliaRuntimeException When an error occurred during the serialization | ||
*/ | ||
public String generateSecuredApiKey(@Nonnull String parentApiKey, @Nonnull SecuredAPIKeyRestrictions restrictions) throws Exception { | ||
Map<String, String> restrictionsMap = new HashMap<>(); | ||
if (restrictions.getFilters() != null) restrictionsMap.put("filters", StringUtils.paramToString(restrictions.getFilters())); | ||
if (restrictions.getValidUntil() != 0) restrictionsMap.put("validUntil", StringUtils.paramToString(restrictions.getValidUntil())); | ||
if (restrictions.getRestrictIndices() != null) restrictionsMap.put( | ||
"restrictIndices", | ||
StringUtils.paramToString(restrictions.getRestrictIndices()) | ||
); | ||
if (restrictions.getRestrictSources() != null) restrictionsMap.put( | ||
"restrictSources", | ||
StringUtils.paramToString(restrictions.getRestrictSources()) | ||
); | ||
if (restrictions.getUserToken() != null) restrictionsMap.put("userToken", StringUtils.paramToString(restrictions.getUserToken())); | ||
|
||
if (restrictions.getSearchParams() != null) { | ||
Map<String, Object> searchParamsMap = JsonSerializer | ||
.getObjectMapper() | ||
.convertValue(restrictions.getSearchParams(), new TypeReference<Map<String, Object>>() {}); | ||
searchParamsMap.forEach((key, value) -> restrictionsMap.put(key, StringUtils.paramToString(value))); | ||
} | ||
|
||
String queryStr = restrictionsMap | ||
.entrySet() | ||
.stream() | ||
.sorted(Map.Entry.comparingByKey()) | ||
.map(entry -> String.format("%s=%s", entry.getKey(), entry.getValue())) | ||
.collect(Collectors.joining("&")); | ||
|
||
String key = hmac(parentApiKey, queryStr); | ||
|
||
return new String(Base64.getEncoder().encode(String.format("%s%s", key, queryStr).getBytes(Charset.forName("UTF8")))); | ||
} | ||
|
||
private String hmac(String key, String msg) throws NoSuchAlgorithmException, InvalidKeyException { | ||
Mac hmac = Mac.getInstance("HmacSHA256"); | ||
hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256")); | ||
byte[] rawHmac = hmac.doFinal(msg.getBytes()); | ||
StringBuilder sb = new StringBuilder(rawHmac.length * 2); | ||
for (byte b : rawHmac) { | ||
sb.append(String.format("%02x", b & 0xff)); | ||
} | ||
return sb.toString(); | ||
} | ||
|
||
/** | ||
* Helper: Retrieves the remaining validity of the previous generated `secured_api_key`, the | ||
* `validUntil` parameter must have been provided. | ||
* | ||
* @param securedApiKey The secured API Key to check | ||
* @throws AlgoliaRuntimeException if <code>securedApiKey</code> is null, empty or whitespaces. | ||
* @throws AlgoliaRuntimeException if <code>securedApiKey</code> doesn't have a <code>validUntil | ||
* </code> parameter. | ||
*/ | ||
public Duration getSecuredApiKeyRemainingValidity(@Nonnull String securedApiKey) { | ||
if (securedApiKey == null || securedApiKey.trim().isEmpty()) { | ||
throw new AlgoliaRuntimeException("securedAPIKey must not be empty, null or whitespaces"); | ||
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. technically not possible if they used generateSecuredApiKey, right? we should maybe be more precise here and recommend to report the bug or something non blocking 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. nothing forces the user to use this with |
||
} | ||
|
||
byte[] decodedBytes = Base64.getDecoder().decode(securedApiKey); | ||
String decodedString = new String(decodedBytes); | ||
|
||
Pattern pattern = Pattern.compile("validUntil=\\d+"); | ||
Matcher matcher = pattern.matcher(decodedString); | ||
|
||
if (!matcher.find()) { | ||
throw new AlgoliaRuntimeException("The Secured API Key doesn't have a validUntil parameter."); | ||
} | ||
|
||
String validUntilMatch = matcher.group(0); | ||
long timeStamp = Long.parseLong(validUntilMatch.replace("validUntil=", "")); | ||
|
||
return Duration.ofSeconds(timeStamp - Instant.now().getEpochSecond()); | ||
} | ||
{{/isSearchClient}} |
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.
this should be configurable no?
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.
disabled by default is nice anyway
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.
actually this is only used for the
generateSecuredApiKey
helper, the other json serializer used for http body is configurable.I'm not sure if I can make this one configurable since its static
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.
this is how it's done in the legacy client too, it's just a way to have a json serializer in hard to reach places
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.
ah oki i'm fine with that then