Repository navigation
Add $hmac JSONata function #525
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
dashjoin-core/src/main/java/org/dashjoin/function/Hmac.java
This file contains hidden or 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,105 @@ | ||
| package org.dashjoin.function; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Base64; | ||
| import java.util.HexFormat; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
| import javax.crypto.Mac; | ||
| import javax.crypto.spec.SecretKeySpec; | ||
| import org.dashjoin.service.ACLContainerRequestFilter; | ||
|
|
||
| /** | ||
| * $hmac(keyId, message, algorithm?, encoding?) signs message with the secret of the Credentials | ||
| * function keyId, e.g. for signed CDN URLs or for checking webhook signatures. | ||
| * | ||
| * The secret is never returned. Only users with one of the roles of the Credentials function may | ||
| * use it (admin only if it has no roles). To let other users sign a fixed kind of message, wrap the | ||
| * call in an Invoke function with runas set to such a role. | ||
| * | ||
| * algorithm: HmacSHA256 (default), HmacSHA384, HmacSHA512. encoding: base64 (default), base64url | ||
| * (without padding) or hex. | ||
| */ | ||
| @SuppressWarnings("rawtypes") | ||
| public class Hmac extends AbstractVarArgFunction<Object> { | ||
|
|
||
| static final Set<String> ALGORITHMS = Set.of("HmacSHA256", "HmacSHA384", "HmacSHA512"); | ||
|
|
||
| @Override | ||
| public Object run(List args) throws Exception { | ||
| String keyId = arg(args, 0, null); | ||
| String message = arg(args, 1, null); | ||
| if (keyId == null || message == null) | ||
| throw new IllegalArgumentException("Syntax: $hmac(keyId, message, algorithm?, encoding?)"); | ||
| String algorithm = arg(args, 2, "HmacSHA256"); | ||
| String encoding = arg(args, 3, "base64"); | ||
|
|
||
| Credentials key = credentials(keyId); | ||
| ACLContainerRequestFilter.check(sc, key); | ||
| String secret = secret(key); | ||
| if (secret == null || secret.isEmpty()) | ||
| throw new IllegalArgumentException("$hmac: " + keyId + " has no secret"); | ||
| return sign(secret, message, algorithm, encoding); | ||
| } | ||
|
|
||
| /** | ||
| * loads the key record. Only Credentials functions qualify: other functions may hold passwords | ||
| * for other purposes. | ||
| */ | ||
| protected Credentials credentials(String keyId) throws Exception { | ||
| return asCredentials(services.getConfig().getFunction(keyId), keyId); | ||
| } | ||
|
|
||
| static Credentials asCredentials(Object function, String keyId) { | ||
| if (!(function instanceof Credentials)) | ||
| throw new IllegalArgumentException("$hmac: " + keyId + " is not a Credentials function"); | ||
| return (Credentials) function; | ||
| } | ||
|
|
||
| /** | ||
| * the secret: config value dashjoin.function.[ID].password (e.g. an environment variable) or the | ||
| * encrypted password stored with the function | ||
| */ | ||
| protected String secret(Credentials key) throws Exception { | ||
| key.init(sc, services, expressionService, readOnly); | ||
| return key.password(); | ||
| } | ||
|
|
||
| static String sign(String secret, String message, String algorithm, String encoding) | ||
| throws Exception { | ||
| if (!ALGORITHMS.contains(algorithm)) | ||
| throw new IllegalArgumentException("$hmac: unsupported algorithm " + algorithm); | ||
| Mac mac = Mac.getInstance(algorithm); | ||
| mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm)); | ||
| byte[] out = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); | ||
| switch (encoding) { | ||
| case "base64": | ||
| return Base64.getEncoder().encodeToString(out); | ||
| case "base64url": | ||
| return Base64.getUrlEncoder().withoutPadding().encodeToString(out); | ||
| case "hex": | ||
| return HexFormat.of().formatHex(out); | ||
| default: | ||
| throw new IllegalArgumentException("$hmac: unsupported encoding " + encoding); | ||
| } | ||
| } | ||
|
|
||
| static String arg(List args, int index, String fallback) { | ||
| Object value = index < args.size() ? args.get(index) : null; | ||
| if (value == null) | ||
| return fallback; | ||
| if (!(value instanceof String)) | ||
| throw new IllegalArgumentException("$hmac: argument " + (index + 1) + " must be a string"); | ||
| return (String) value; | ||
| } | ||
|
|
||
| @Override | ||
| public String getID() { | ||
| return "hmac"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getType() { | ||
| return "read"; | ||
| } | ||
| } |
This file contains hidden or 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
91 changes: 91 additions & 0 deletions
91
dashjoin-core/src/test/java/org/dashjoin/function/HmacTest.java
This file contains hidden or 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,91 @@ | ||
| package org.dashjoin.function; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import org.junit.jupiter.api.Assertions; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.mockito.ArgumentMatchers; | ||
| import org.mockito.Mockito; | ||
| import jakarta.ws.rs.NotAuthorizedException; | ||
| import jakarta.ws.rs.core.SecurityContext; | ||
|
|
||
| public class HmacTest { | ||
|
|
||
| static final String FOX = "The quick brown fox jumps over the lazy dog"; | ||
|
|
||
| // Well-known HMAC-SHA256("key", FOX) | ||
| static final String FOX_HEX = "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"; | ||
|
|
||
| static SecurityContext roles(String... roles) { | ||
| SecurityContext sc = Mockito.mock(SecurityContext.class); | ||
| for (String role : roles) | ||
| Mockito.when(sc.isUserInRole(ArgumentMatchers.eq(role))).thenReturn(true); | ||
| return sc; | ||
| } | ||
|
|
||
| /** $hmac with an in-memory key "key" that the given roles may use */ | ||
| static Hmac hmac(SecurityContext sc, List<String> keyRoles) { | ||
| Hmac f = new Hmac() { | ||
| @Override | ||
| protected Credentials credentials(String keyId) { | ||
| Assertions.assertEquals("cdnKey", keyId); | ||
| Credentials c = new Credentials(); | ||
| c.ID = keyId; | ||
| c.roles = keyRoles; | ||
| return c; | ||
| } | ||
|
|
||
| @Override | ||
| protected String secret(Credentials key) { | ||
| return "key"; | ||
| } | ||
| }; | ||
| f.sc = sc; | ||
| return f; | ||
| } | ||
|
|
||
| @Test | ||
| public void testEncodings() throws Exception { | ||
| Hmac f = hmac(roles("signer"), List.of("signer")); | ||
| Assertions.assertEquals(FOX_HEX, f.run(Arrays.asList("cdnKey", FOX, null, "hex"))); | ||
| Assertions.assertEquals("97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=", | ||
| f.run(Arrays.asList("cdnKey", FOX))); | ||
| Assertions.assertEquals("97yD9DBThCSxMpjmqm-xQ-9NWaFJRhdZl0edvC0aPNg", | ||
| f.run(Arrays.asList("cdnKey", FOX, "HmacSHA256", "base64url"))); | ||
| Assertions.assertEquals(128, | ||
| ((String) f.run(Arrays.asList("cdnKey", FOX, "HmacSHA512", "hex"))).length()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testKeyRoles() throws Exception { | ||
| // authenticated users may not use a key reserved for "signer" | ||
| Assertions.assertThrows(NotAuthorizedException.class, | ||
| () -> hmac(roles("authenticated"), List.of("signer")).run(Arrays.asList("cdnKey", FOX))); | ||
| // a key without roles is admin only | ||
| Assertions.assertThrows(NotAuthorizedException.class, | ||
| () -> hmac(roles("signer"), null).run(Arrays.asList("cdnKey", FOX))); | ||
| Assertions.assertNotNull(hmac(roles("admin"), null).run(Arrays.asList("cdnKey", FOX))); | ||
| } | ||
|
|
||
| @Test | ||
| public void testOnlyCredentials() { | ||
| Assertions.assertThrows(IllegalArgumentException.class, | ||
| () -> Hmac.asCredentials(new Invoke(), "echo")); | ||
| Assertions.assertThrows(IllegalArgumentException.class, | ||
| () -> Hmac.asCredentials(null, "missing")); | ||
| Credentials c = new Credentials(); | ||
| Assertions.assertSame(c, Hmac.asCredentials(c, "cdnKey")); | ||
| } | ||
|
|
||
| @Test | ||
| public void testInvalidArguments() { | ||
| Hmac f = hmac(roles("signer"), List.of("signer")); | ||
| Assertions.assertThrows(IllegalArgumentException.class, () -> f.run(Arrays.asList("cdnKey"))); | ||
| Assertions.assertThrows(IllegalArgumentException.class, | ||
| () -> f.run(Arrays.asList("cdnKey", 42))); | ||
| Assertions.assertThrows(IllegalArgumentException.class, | ||
| () -> f.run(Arrays.asList("cdnKey", FOX, "HmacMD5"))); | ||
| Assertions.assertThrows(IllegalArgumentException.class, | ||
| () -> f.run(Arrays.asList("cdnKey", FOX, null, "base32"))); | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 must go in /dashjoin-base/dashjoin-docs/llms/jsonata.json
also, we need to add this to Action.ts to make the function available on the client (proxied to backend if client jsonata engine)