Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogvm): add sha1 and hmac-sha1 to the stl (#77480)

Tom Owers40cdbbf34403
diff --git a/common/hogvm/CHANGELOG.md b/common/hogvm/CHANGELOG.md
index 15a0e3ae22de..ae93724b1b7c 100644
--- a/common/hogvm/CHANGELOG.md
+++ b/common/hogvm/CHANGELOG.md
@@ -1,5 +1,24 @@
# HogQL bytecode changelog
+## 2026-08-04 - 1.0.68
+
+Added SHA-1 primitives to the standard library. No bytecode operations changed.
+
+```bash
+sha1Hex(data) # SHA-1 of a string, hex encoded
+sha1(data, encoding) # SHA-1 of a string, encoding defaults to 'hex'
+sha1HmacChainHex(data) # HMAC-SHA1 chained over an array of strings, hex encoded
+sha1HmacChain(data, encoding) # same, encoding defaults to 'hex'
+```
+
+`encoding` is one of `hex`, `base64`, `base64url`, or `binary`, matching `md5`, `sha256`, and
+`sha256HmacChain`. A two element chain is a plain HMAC-SHA1 of a key and a message, which is what
+webhook signature verification needs.
+
+SHA-1 is broken for collision resistance and must not be picked for new work. HMAC-SHA1 is still
+sound for message authentication, and it is here only because some vendors sign their webhooks
+with it.
+
## 2023-06-30 - 1.0.2
Rolled back cohort matching instructions.
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.hoge b/common/hogvm/__tests__/__snapshots__/crypto.hoge
index faff6799cf52..7e4817c42f61 100644
--- a/common/hogvm/__tests__/__snapshots__/crypto.hoge
+++ b/common/hogvm/__tests__/__snapshots__/crypto.hoge
@@ -12,9 +12,27 @@
32, "binary", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(string, 'base64'):", 36, 0, 32, "base64", 2, "sha256", 2,
2, "print", 2, 35, 32, "sha256(null, 'base64'):", 31, 32, "base64", 2, "sha256", 2, 2, "print", 2, 35, 32,
"sha256(string, 'base64url'):", 36, 0, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32,
-"sha256(null, 'base64url'):", 31, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32, "1", 32, "string", 32, "more",
-32, "keys", 43, 4, 32, "data:", 36, 1, 2, "print", 2, 35, 32, "sha256HmacChainHex(data):", 36, 1, 2,
-"sha256HmacChainHex", 1, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'hex'):", 36, 1, 32, "hex", 2, "sha256HmacChain",
-2, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2, "sha256HmacChain", 2, 2, "print",
-2, 35, 32, "sha256HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
-"sha256HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 35, 35]
+"sha256(null, 'base64url'):", 31, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha1Hex(string):", 36, 0, 2,
+"sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(null):", 31, 2, "sha1Hex", 1, 2, "print", 2, 35, 32,
+"sha1(string, 'hex'):", 36, 0, 32, "hex", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'hex'):", 31, 32, "hex", 2,
+"sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'binary'):", 36, 0, 32, "binary", 2, "sha1", 2, 2, "print", 2, 35, 32,
+"sha1(null, 'binary'):", 31, 32, "binary", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'base64'):", 36, 0, 32,
+"base64", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'base64'):", 31, 32, "base64", 2, "sha1", 2, 2, "print", 2,
+35, 32, "sha1(string, 'base64url'):", 36, 0, 32, "base64url", 2, "sha1", 2, 2, "print", 2, 35, 32,
+"sha1(null, 'base64url'):", 31, 32, "base64url", 2, "sha1", 2, 2, "print", 2, 35, 32, "1", 32, "string", 32, "more", 32,
+"keys", 43, 4, 32, "data:", 36, 1, 2, "print", 2, 35, 32, "sha256HmacChainHex(data):", 36, 1, 2, "sha256HmacChainHex",
+1, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'hex'):", 36, 1, 32, "hex", 2, "sha256HmacChain", 2, 2, "print", 2, 35,
+32, "sha256HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
+"sha256HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
+"sha256HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
+"sha1HmacChainHex(data):", 36, 1, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'hex'):", 36, 1,
+32, "hex", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2,
+"sha1HmacChain", 2, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha1HmacChain", 2,
+2, "print", 2, 35, 32, "sha1HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha1HmacChain", 2, 2, "print",
+2, 35, 32, "sha1Hex('abc'):", 32, "abc", 2, "sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(''):", 32, "", 2, "sha1Hex",
+1, 2, "print", 2, 35, 32, "rfc2202 case 1:", 32,
+"\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b",
+32, "Hi There", 43, 2, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "rfc2202 case 2:", 32, "Jefe", 32,
+"what do ya want for nothing?", 43, 2, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "rfc2202 case 5:", 32,
+"\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f", 32, "Test With Truncation", 43, 2, 2, "sha1HmacChainHex", 1, 2, "print", 2,
+35, 35, 35]
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.js b/common/hogvm/__tests__/__snapshots__/crypto.js
index 09063b28dc3e..fabb79868a98 100644
--- a/common/hogvm/__tests__/__snapshots__/crypto.js
+++ b/common/hogvm/__tests__/__snapshots__/crypto.js
@@ -2,6 +2,10 @@ function sha256HmacChainHex (data, options) { return 'sha256HmacChainHex not imp
function sha256HmacChain (data, encoding, options) { return 'sha256HmacChain not implemented' }
function sha256Hex(data) {if (data === null || data == undefined) return null; let h0=0x6a09e667,h1=0xbb67ae85,h2=0x3c6ef372,h3=0xa54ff53a,h4=0x510e527f,h5=0x9b05688c,h6=0x1f83d9ab,h7=0x5be0cd19,tsz=0,bp=0;const k=[0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2],rrot=(x,n)=>(x>>>n)|(x<<(32-n)),w=new Uint32Array(64),buf=new Uint8Array(64),process=()=>{for(let j=0,r=0;j<16;j++,r+=4){w[j]=(buf[r]<<24)|(buf[r+1]<<16)|(buf[r+2]<<8)|buf[r+3]}for(let j=16;j<64;j++){let s0=rrot(w[j-15],7)^rrot(w[j-15],18)^(w[j-15]>>>3);let s1=rrot(w[j-2],17)^rrot(w[j-2],19)^(w[j-2]>>>10);w[j]=(w[j-16]+s0+w[j-7]+s1)|0}let a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7;for(let j=0;j<64;j++){let S1=rrot(e,6)^rrot(e,11)^rrot(e,25),ch=(e&f)^((~e)&g),t1=(h+S1+ch+k[j]+w[j])|0,S0=rrot(a,2)^rrot(a,13)^rrot(a,22),maj=(a&b)^(a&c)^(b&c),t2=(S0+maj)|0;h=g;g=f;f=e;e=(d+t1)|0;d=c;c=b;b=a;a=(t1+t2)|0}h0=(h0+a)|0;h1=(h1+b)|0;h2=(h2+c)|0;h3=(h3+d)|0;h4=(h4+e)|0;h5=(h5+f)|0;h6=(h6+g)|0;h7=(h7+h)|0;bp=0},add=data=>{if(typeof data==="string"){data=typeof TextEncoder==="undefined"?Buffer.from(data):(new TextEncoder).encode(data)}for(let i=0;i<data.length;i++){buf[bp++]=data[i];if(bp===64)process();}tsz+=data.length},digest=()=>{buf[bp++]=0x80;if(bp==64)process();if(bp+8>64){while(bp<64)buf[bp++]=0x00;process()}while(bp<58)buf[bp++]=0x00;let L=tsz*8;buf[bp++]=(L/1099511627776.)&255;buf[bp++]=(L/4294967296.)&255;buf[bp++]=L>>>24;buf[bp++]=(L>>>16)&255;buf[bp++]=(L>>>8)&255;buf[bp++]=L&255;process();let reply=new Uint8Array(32);reply[0]=h0>>>24;reply[1]=(h0>>>16)&255;reply[2]=(h0>>>8)&255;reply[3]=h0&255;reply[4]=h1>>>24;reply[5]=(h1>>>16)&255;reply[6]=(h1>>>8)&255;reply[7]=h1&255;reply[8]=h2>>>24;reply[9]=(h2>>>16)&255;reply[10]=(h2>>>8)&255;reply[11]=h2&255;reply[12]=h3>>>24;reply[13]=(h3>>>16)&255;reply[14]=(h3>>>8)&255;reply[15]=h3&255;reply[16]=h4>>>24;reply[17]=(h4>>>16)&255;reply[18]=(h4>>>8)&255;reply[19]=h4&255;reply[20]=h5>>>24;reply[21]=(h5>>>16)&255;reply[22]=(h5>>>8)&255;reply[23]=h5&255;reply[24]=h6>>>24;reply[25]=(h6>>>16)&255;reply[26]=(h6>>>8)&255;reply[27]=h6&255;reply[28]=h7>>>24;reply[29]=(h7>>>16)&255;reply[30]=(h7>>>8)&255;reply[31]=h7&255;reply.hex=()=>{let res="";reply.forEach(x=>res+=("0"+x.toString(16)).slice(-2));return res};return reply};if(data===undefined)return{add,digest};add(data);return digest().hex()}
function sha256 (data, encoding, options) { return 'sha256 not implemented' }
+function sha1HmacChainHex (data, options) { return 'sha1HmacChainHex not implemented' }
+function sha1HmacChain (data, encoding, options) { return 'sha1HmacChain not implemented' }
+function sha1Hex (data) { return 'sha1Hex not implemented' }
+function sha1 (data, encoding, options) { return 'sha1 not implemented' }
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function md5Hex(s) {if (s === null || s == undefined) return null; var k=[],i=0;for(;i<64;){k[i]=0|Math.sin(++i%Math.PI)*4294967296}var b,c,d,h=[b=0x67452301,c=0xEFCDAB89,~b,~c],words=[],j=unescape(encodeURI(s))+'€',a=j.length;s=(--a/4+2)|15;words[--s]=a*8;for(;~a;){words[a>>2]|=j.charCodeAt(a)<<8*a--}for(i=j=0;i<s;i+=16){a=h;for(;j<64;a=[d=a[3],(b+((d=a[0]+[b&c|~b&d,d&b|~d&c,b^c^d,c^(b|~d)][a=j>>4]+k[j]+~~words[i|[j,5*j+1,3*j+5,7*j][a]&15])<<(a=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21][4*a+j++%4])|d>>>-a)),b,c]){b=a[1]|0;c=a[2]}for(j=4;j;)h[--j]+=a[j]}for(s='';j<32;){s+=((h[j>>3]>>((1^j++)*4))&15).toString(16)}return s}
function md5 (data, encoding, options) { return 'md5 not implemented' }
@@ -65,6 +69,16 @@ print("sha256(string, 'base64'):", sha256(string, "base64"));
print("sha256(null, 'base64'):", sha256(null, "base64"));
print("sha256(string, 'base64url'):", sha256(string, "base64url"));
print("sha256(null, 'base64url'):", sha256(null, "base64url"));
+print("sha1Hex(string):", sha1Hex(string));
+print("sha1Hex(null):", sha1Hex(null));
+print("sha1(string, 'hex'):", sha1(string, "hex"));
+print("sha1(null, 'hex'):", sha1(null, "hex"));
+print("sha1(string, 'binary'):", sha1(string, "binary"));
+print("sha1(null, 'binary'):", sha1(null, "binary"));
+print("sha1(string, 'base64'):", sha1(string, "base64"));
+print("sha1(null, 'base64'):", sha1(null, "base64"));
+print("sha1(string, 'base64url'):", sha1(string, "base64url"));
+print("sha1(null, 'base64url'):", sha1(null, "base64url"));
let data = ["1", "string", "more", "keys"];
print("data:", data);
print("sha256HmacChainHex(data):", sha256HmacChainHex(data));
@@ -72,3 +86,13 @@ print("sha256HmacChain(data, 'hex'):", sha256HmacChain(data, "hex"));
print("sha256HmacChain(data, 'base64'):", sha256HmacChain(data, "base64"));
print("sha256HmacChain(data, 'binary'):", sha256HmacChain(data, "binary"));
print("sha256HmacChain(data, 'base64url'):", sha256HmacChain(data, "base64url"));
+print("sha1HmacChainHex(data):", sha1HmacChainHex(data));
+print("sha1HmacChain(data, 'hex'):", sha1HmacChain(data, "hex"));
+print("sha1HmacChain(data, 'base64'):", sha1HmacChain(data, "base64"));
+print("sha1HmacChain(data, 'binary'):", sha1HmacChain(data, "binary"));
+print("sha1HmacChain(data, 'base64url'):", sha1HmacChain(data, "base64url"));
+print("sha1Hex('abc'):", sha1Hex("abc"));
+print("sha1Hex(''):", sha1Hex(""));
+print("rfc2202 case 1:", sha1HmacChainHex(["\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b", "Hi There"]));
+print("rfc2202 case 2:", sha1HmacChainHex(["Jefe", "what do ya want for nothing?"]));
+print("rfc2202 case 5:", sha1HmacChainHex(["\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f", "Test With Truncation"]));
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs b/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs
index e509e62cf4ca..340003bcefcb 100644
--- a/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs
+++ b/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs
@@ -19,9 +19,29 @@ sha256(string, 'base64'): sha256 not implemented
sha256(null, 'base64'): sha256 not implemented
sha256(string, 'base64url'): sha256 not implemented
sha256(null, 'base64url'): sha256 not implemented
+sha1Hex(string): sha1Hex not implemented
+sha1Hex(null): sha1Hex not implemented
+sha1(string, 'hex'): sha1 not implemented
+sha1(null, 'hex'): sha1 not implemented
+sha1(string, 'binary'): sha1 not implemented
+sha1(null, 'binary'): sha1 not implemented
+sha1(string, 'base64'): sha1 not implemented
+sha1(null, 'base64'): sha1 not implemented
+sha1(string, 'base64url'): sha1 not implemented
+sha1(null, 'base64url'): sha1 not implemented
data: ['1', 'string', 'more', 'keys']
sha256HmacChainHex(data): sha256HmacChainHex not implemented
sha256HmacChain(data, 'hex'): sha256HmacChain not implemented
sha256HmacChain(data, 'base64'): sha256HmacChain not implemented
sha256HmacChain(data, 'binary'): sha256HmacChain not implemented
sha256HmacChain(data, 'base64url'): sha256HmacChain not implemented
+sha1HmacChainHex(data): sha1HmacChainHex not implemented
+sha1HmacChain(data, 'hex'): sha1HmacChain not implemented
+sha1HmacChain(data, 'base64'): sha1HmacChain not implemented
+sha1HmacChain(data, 'binary'): sha1HmacChain not implemented
+sha1HmacChain(data, 'base64url'): sha1HmacChain not implemented
+sha1Hex('abc'): sha1Hex not implemented
+sha1Hex(''): sha1Hex not implemented
+rfc2202 case 1: sha1HmacChainHex not implemented
+rfc2202 case 2: sha1HmacChainHex not implemented
+rfc2202 case 5: sha1HmacChainHex not implemented
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs b/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs
index 3dec94e8303b..466d121779cb 100644
Binary files a/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs and b/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs differ
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.python b/common/hogvm/__tests__/__snapshots__/crypto.stdout.python
index 3dec94e8303b..466d121779cb 100644
Binary files a/common/hogvm/__tests__/__snapshots__/crypto.stdout.python and b/common/hogvm/__tests__/__snapshots__/crypto.stdout.python differ
diff --git a/common/hogvm/__tests__/crypto.hog b/common/hogvm/__tests__/crypto.hog
index 63691c9f4190..a3f49a24b673 100644
--- a/common/hogvm/__tests__/crypto.hog
+++ b/common/hogvm/__tests__/crypto.hog
@@ -20,6 +20,16 @@ print('sha256(string, \'base64\'):', sha256(string, 'base64'))
print('sha256(null, \'base64\'):', sha256(null, 'base64'))
print('sha256(string, \'base64url\'):', sha256(string, 'base64url'))
print('sha256(null, \'base64url\'):', sha256(null, 'base64url'))
+print('sha1Hex(string):', sha1Hex(string))
+print('sha1Hex(null):', sha1Hex(null))
+print('sha1(string, \'hex\'):', sha1(string, 'hex'))
+print('sha1(null, \'hex\'):', sha1(null, 'hex'))
+print('sha1(string, \'binary\'):', sha1(string, 'binary'))
+print('sha1(null, \'binary\'):', sha1(null, 'binary'))
+print('sha1(string, \'base64\'):', sha1(string, 'base64'))
+print('sha1(null, \'base64\'):', sha1(null, 'base64'))
+print('sha1(string, \'base64url\'):', sha1(string, 'base64url'))
+print('sha1(null, \'base64url\'):', sha1(null, 'base64url'))
let data := ['1', 'string', 'more', 'keys']
print('data:', data)
@@ -28,3 +38,16 @@ print('sha256HmacChain(data, \'hex\'):', sha256HmacChain(data, 'hex'))
print('sha256HmacChain(data, \'base64\'):', sha256HmacChain(data, 'base64'))
print('sha256HmacChain(data, \'binary\'):', sha256HmacChain(data, 'binary'))
print('sha256HmacChain(data, \'base64url\'):', sha256HmacChain(data, 'base64url'))
+print('sha1HmacChainHex(data):', sha1HmacChainHex(data))
+print('sha1HmacChain(data, \'hex\'):', sha1HmacChain(data, 'hex'))
+print('sha1HmacChain(data, \'base64\'):', sha1HmacChain(data, 'base64'))
+print('sha1HmacChain(data, \'binary\'):', sha1HmacChain(data, 'binary'))
+print('sha1HmacChain(data, \'base64url\'):', sha1HmacChain(data, 'base64url'))
+
+// Known answers, so a wrong implementation fails instead of agreeing on a wrong snapshot.
+// SHA-1 vectors from FIPS 180-1, HMAC-SHA1 vectors from RFC 2202 (the cases with textual keys).
+print('sha1Hex(\'abc\'):', sha1Hex('abc'))
+print('sha1Hex(\'\'):', sha1Hex(''))
+print('rfc2202 case 1:', sha1HmacChainHex(['\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v', 'Hi There']))
+print('rfc2202 case 2:', sha1HmacChainHex(['Jefe', 'what do ya want for nothing?']))
+print('rfc2202 case 5:', sha1HmacChainHex(['\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f', 'Test With Truncation']))
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.py
index 3d65dd791328..65f69f256512 100644
--- a/common/hogvm/python/stl/__init__.py
+++ b/common/hogvm/python/stl/__init__.py
@@ -12,7 +12,7 @@ import pytz
from ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_error, to_hog_interval
from ..utils import HogVMException, _require_string, get_nested_value, like
-from .crypto import md5, sha256, sha256HmacChain
+from .crypto import md5, sha1, sha1HmacChain, sha256, sha256HmacChain
from .date import (
formatDateTime,
fromUnixTimestamp,
@@ -1060,10 +1060,26 @@ STL: dict[str, STLFunction] = {
minArgs=1,
maxArgs=2,
),
+ "sha1Hex": STLFunction(fn=lambda args, team, stdout, timeout: sha1(args[0]), minArgs=1, maxArgs=1),
+ "sha1": STLFunction(
+ fn=lambda args, team, stdout, timeout: sha1(args[0], args[1] if len(args) > 1 else "hex"),
+ minArgs=1,
+ maxArgs=2,
+ ),
"md5Hex": STLFunction(fn=lambda args, team, stdout, timeout: md5(args[0]), minArgs=1, maxArgs=1),
"md5": STLFunction(
fn=lambda args, team, stdout, timeout: md5(args[0], args[1] if len(args) > 1 else "hex"), minArgs=1, maxArgs=2
),
+ "sha1HmacChainHex": STLFunction(
+ fn=lambda args, team, stdout, timeout: sha1HmacChain(args[0], "hex"),
+ minArgs=1,
+ maxArgs=1,
+ ),
+ "sha1HmacChain": STLFunction(
+ fn=lambda args, team, stdout, timeout: sha1HmacChain(args[0], args[1] if len(args) > 1 else "hex"),
+ minArgs=1,
+ maxArgs=2,
+ ),
"sha256HmacChainHex": STLFunction(
fn=lambda args, team, stdout, timeout: sha256HmacChain(args[0], "hex"),
minArgs=1,
diff --git a/common/hogvm/python/stl/crypto.py b/common/hogvm/python/stl/crypto.py
index e628bf6d86c5..2eb04d48d5b5 100644
--- a/common/hogvm/python/stl/crypto.py
+++ b/common/hogvm/python/stl/crypto.py
@@ -32,14 +32,32 @@ def sha256(data: str | None, encoding: Literal["hex", "base64", "base64url", "bi
return encode_digest(encoding, digest)
-def sha256HmacChain(data: list, encoding: Literal["hex", "base64", "base64url", "binary"] = "hex") -> str:
+def sha1(data: str | None, encoding: Literal["hex", "base64", "base64url", "binary"] = "hex") -> str | None:
+ if data is None:
+ return None
+ # SHA-1 is only here because vendors sign webhooks with it. Never pick it for new work.
+ # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1
+ digest = hashlib.sha1(data.encode()).digest()
+
+ return encode_digest(encoding, digest)
+
+
+def _hmac_chain(data: list, digestmod: str, encoding: Literal["hex", "base64", "base64url", "binary"]) -> str:
if len(data) < 2:
raise ValueError("Data array must contain at least two elements.")
- hmac_obj = hmac.new(data[0].encode(), data[1].encode(), hashlib.sha256)
+ hmac_obj = hmac.new(data[0].encode(), data[1].encode(), digestmod)
for i in range(2, len(data)):
- hmac_obj = hmac.new(hmac_obj.digest(), data[i].encode(), hashlib.sha256)
+ hmac_obj = hmac.new(hmac_obj.digest(), data[i].encode(), digestmod)
digest = hmac_obj.digest()
return encode_digest(encoding, digest)
+
+
+def sha256HmacChain(data: list, encoding: Literal["hex", "base64", "base64url", "binary"] = "hex") -> str:
+ return _hmac_chain(data, "sha256", encoding)
+
+
+def sha1HmacChain(data: list, encoding: Literal["hex", "base64", "base64url", "binary"] = "hex") -> str:
+ return _hmac_chain(data, "sha1", encoding)
diff --git a/common/hogvm/python/test/test_crypto.py b/common/hogvm/python/test/test_crypto.py
new file mode 100644
index 000000000000..8d514b19e460
--- /dev/null
+++ b/common/hogvm/python/test/test_crypto.py
@@ -0,0 +1,93 @@
+import hmac
+import hashlib
+
+import pytest
+
+from parameterized import parameterized
+
+from common.hogvm.python.stl import STL
+from common.hogvm.python.stl.crypto import sha1, sha1HmacChain
+
+# RFC 2202 HMAC-SHA1 test vectors, limited to the cases whose key and message are text (the STL
+# only takes strings). A two-element chain is a plain HMAC of key and message.
+RFC_2202_VECTORS = [
+ ("case_1", "\x0b" * 20, "Hi There", "b617318655057264e28bc0b6fb378c8ef146be00"),
+ ("case_2", "Jefe", "what do ya want for nothing?", "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"),
+ ("case_5", "\x0c" * 20, "Test With Truncation", "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"),
+]
+
+
+class TestSha1:
+ @parameterized.expand(
+ [
+ ("empty", "", "hex", "da39a3ee5e6b4b0d3255bfef95601890afd80709"),
+ ("abc", "abc", "hex", "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("hello", "hello", "hex", "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"),
+ ("base64", "abc", "base64", "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="),
+ ("base64url", "abc", "base64url", "qZk-NkcGgWq6PiVxeFDCbJzQ2J0"),
+ ]
+ )
+ def test_known_answers(self, _name: str, data: str, encoding: str, expected: str) -> None:
+ assert sha1(data, encoding) == expected # type: ignore[arg-type]
+
+ def test_defaults_to_hex(self) -> None:
+ assert sha1("abc") == sha1("abc", "hex")
+
+ def test_null_passes_through(self) -> None:
+ assert sha1(None) is None
+
+ def test_binary_encoding_holds_the_raw_digest(self) -> None:
+ binary = sha1("abc", "binary")
+ assert binary is not None
+ assert binary.encode("latin1").hex() == sha1("abc", "hex")
+
+
+class TestSha1HmacChain:
+ @parameterized.expand(RFC_2202_VECTORS)
+ def test_rfc_2202(self, _name: str, key: str, message: str, expected: str) -> None:
+ assert sha1HmacChain([key, message]) == expected
+
+ def test_rekeys_with_the_previous_raw_digest(self) -> None:
+ # SHA-1 here is the algorithm under test, computed independently of the STL to pin the
+ # re-keying step. Not used for secrecy or collision resistance.
+ # nosemgrep: python.lang.security.insecure-hash-algorithms-sha1.insecure-hash-algorithm-sha1
+ key = hmac.new(b"1", b"string", hashlib.sha1).digest()
+ # nosemgrep: python.lang.security.insecure-hash-algorithms-sha1.insecure-hash-algorithm-sha1
+ expected = hmac.new(key, b"more", hashlib.sha1).hexdigest()
+ assert sha1HmacChain(["1", "string", "more"]) == expected
+
+ @parameterized.expand(
+ [
+ ("hex", "hex", "e559ff0c3fc9c9e13a5b5d78fcd722b4f7ec6a9a"),
+ ("base64", "base64", "5Vn/DD/JyeE6W114/NcitPfsapo="),
+ ("base64url", "base64url", "5Vn_DD_JyeE6W114_NcitPfsapo"),
+ ]
+ )
+ def test_encodings(self, _name: str, encoding: str, expected: str) -> None:
+ assert sha1HmacChain(["1", "string", "more", "keys"], encoding) == expected # type: ignore[arg-type]
+
+ def test_rejects_short_input(self) -> None:
+ with pytest.raises(ValueError):
+ sha1HmacChain(["only-a-key"])
+
+
+class TestStlRegistration:
+ @parameterized.expand(
+ [
+ ("sha1Hex", ["abc"], "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("sha1", ["abc"], "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("sha1", ["abc", "base64"], "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="),
+ (
+ "sha1HmacChainHex",
+ [["Jefe", "what do ya want for nothing?"]],
+ "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
+ ),
+ (
+ "sha1HmacChain",
+ [["Jefe", "what do ya want for nothing?"], "hex"],
+ "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
+ ),
+ ]
+ )
+ def test_callable_through_stl(self, name: str, args: list, expected: str) -> None:
+ assert STL[name].fn(args, None, None, 10.0) == expected
diff --git a/common/hogvm/typescript/package.json b/common/hogvm/typescript/package.json
index 3cb1d2471201..73e8264ea771 100644
--- a/common/hogvm/typescript/package.json
+++ b/common/hogvm/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@posthog/hogvm",
- "version": "1.0.67",
+ "version": "1.0.68",
"description": "PostHog Hog Virtual Machine",
"license": "MIT",
"author": "PostHog <[email protected]>",
diff --git a/common/hogvm/typescript/src/__tests__/crypto.test.ts b/common/hogvm/typescript/src/__tests__/crypto.test.ts
new file mode 100644
index 000000000000..1e93f1f4a447
--- /dev/null
+++ b/common/hogvm/typescript/src/__tests__/crypto.test.ts
@@ -0,0 +1,89 @@
+import crypto from 'crypto'
+
+import { sha1, sha1HmacChain } from '../stl/crypto'
+import { STL } from '../stl/stl'
+import { ExecOptions } from '../types'
+
+describe('sha1 and sha1HmacChain', () => {
+ const options: ExecOptions = { external: { crypto } }
+
+ describe('sha1', () => {
+ test.each([
+ ['', 'hex', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
+ ['abc', 'hex', 'a9993e364706816aba3e25717850c26c9cd0d89d'],
+ ['hello', 'hex', 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'],
+ ['abc', 'base64', 'qZk+NkcGgWq6PiVxeFDCbJzQ2J0='],
+ ['abc', 'base64url', 'qZk-NkcGgWq6PiVxeFDCbJzQ2J0'],
+ ] as const)('sha1(%p, %p)', (data, encoding, expected) => {
+ expect(sha1(data, encoding, options)).toBe(expected)
+ })
+
+ test('defaults to hex', () => {
+ expect(sha1('abc', undefined, options)).toBe(sha1('abc', 'hex', options))
+ })
+
+ test('passes null through', () => {
+ expect(sha1(null, 'hex', options)).toBeNull()
+ })
+
+ test('binary encoding holds the raw digest', () => {
+ const binary = sha1('abc', 'binary', options) as string
+ expect(Buffer.from(binary, 'binary').toString('hex')).toBe(sha1('abc', 'hex', options))
+ })
+
+ test('throws without the crypto module', () => {
+ expect(() => sha1('abc', 'hex', {})).toThrow('The crypto module is required for "sha1Hex" to work.')
+ })
+ })
+
+ describe('sha1HmacChain', () => {
+ // RFC 2202 HMAC-SHA1 test vectors, limited to the cases whose key and message are text.
+ // A two-element chain is a plain HMAC of key and message.
+ test.each([
+ ['\x0b'.repeat(20), 'Hi There', 'b617318655057264e28bc0b6fb378c8ef146be00'],
+ ['Jefe', 'what do ya want for nothing?', 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'],
+ ['\x0c'.repeat(20), 'Test With Truncation', '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04'],
+ ])('matches RFC 2202 for %p', (key, message, expected) => {
+ expect(sha1HmacChain([key, message], 'hex', options)).toBe(expected)
+ })
+
+ test('rekeys with the previous raw digest', () => {
+ const key = crypto.createHmac('sha1', '1').update('string').digest()
+ const expected = crypto.createHmac('sha1', key).update('more').digest('hex')
+ expect(sha1HmacChain(['1', 'string', 'more'], 'hex', options)).toBe(expected)
+ })
+
+ test.each([
+ ['hex', 'e559ff0c3fc9c9e13a5b5d78fcd722b4f7ec6a9a'],
+ ['base64', '5Vn/DD/JyeE6W114/NcitPfsapo='],
+ ['base64url', '5Vn_DD_JyeE6W114_NcitPfsapo'],
+ ] as const)('encodes as %p', (encoding, expected) => {
+ expect(sha1HmacChain(['1', 'string', 'more', 'keys'], encoding, options)).toBe(expected)
+ })
+
+ test('rejects fewer than two elements', () => {
+ expect(() => sha1HmacChain(['only-a-key'], 'hex', options)).toThrow(
+ 'Data array must contain at least two elements.'
+ )
+ })
+ })
+
+ describe('STL registration', () => {
+ test.each([
+ ['sha1Hex', ['abc'], 'a9993e364706816aba3e25717850c26c9cd0d89d'],
+ ['sha1', ['abc', 'base64'], 'qZk+NkcGgWq6PiVxeFDCbJzQ2J0='],
+ [
+ 'sha1HmacChainHex',
+ [['Jefe', 'what do ya want for nothing?']],
+ 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79',
+ ],
+ [
+ 'sha1HmacChain',
+ [['Jefe', 'what do ya want for nothing?'], 'hex'],
+ 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79',
+ ],
+ ])('%p is callable through the STL', (name, args, expected) => {
+ expect(STL[name].fn(args, name, options)).toBe(expected)
+ })
+ })
+})
diff --git a/common/hogvm/typescript/src/stl/crypto.ts b/common/hogvm/typescript/src/stl/crypto.ts
index c157048c7fcd..d20d956fc2f3 100644
--- a/common/hogvm/typescript/src/stl/crypto.ts
+++ b/common/hogvm/typescript/src/stl/crypto.ts
@@ -30,23 +30,57 @@ export function md5(
return crypto.createHash('md5').update(data).digest(encoding)
}
-export function sha256HmacChain(
- data: string[],
+// SHA-1 is only here because vendors sign webhooks with it. Never pick it for new work.
+export function sha1(
+ data: string | null,
encoding: 'hex' | 'base64' | 'base64url' | 'binary' = 'hex',
options?: ExecOptions
+): string | null {
+ if (data === null) {
+ return null
+ }
+ const crypto = options?.external?.crypto
+ if (!crypto) {
+ throw new Error('The crypto module is required for "sha1Hex" to work.')
+ }
+ return crypto.createHash('sha1').update(data).digest(encoding)
+}
+
+function hmacChain(
+ algorithm: 'sha256' | 'sha1',
+ name: string,
+ data: string[],
+ encoding: 'hex' | 'base64' | 'base64url' | 'binary',
+ options?: ExecOptions
): string {
const crypto = options?.external?.crypto
if (!crypto) {
- throw new Error('The crypto module is required for "sha256HmacChainHex" to work.')
+ throw new Error(`The crypto module is required for "${name}" to work.`)
}
if (data.length < 2) {
throw new Error('Data array must contain at least two elements.')
}
- let hmac = crypto.createHmac('sha256', data[0])
+ let hmac = crypto.createHmac(algorithm, data[0])
hmac.update(data[1])
for (let i = 2; i < data.length; i++) {
- hmac = crypto.createHmac('sha256', hmac.digest())
+ hmac = crypto.createHmac(algorithm, hmac.digest())
hmac.update(data[i])
}
return hmac.digest(encoding)
}
+
+export function sha256HmacChain(
+ data: string[],
+ encoding: 'hex' | 'base64' | 'base64url' | 'binary' = 'hex',
+ options?: ExecOptions
+): string {
+ return hmacChain('sha256', 'sha256HmacChainHex', data, encoding, options)
+}
+
+export function sha1HmacChain(
+ data: string[],
+ encoding: 'hex' | 'base64' | 'base64url' | 'binary' = 'hex',
+ options?: ExecOptions
+): string {
+ return hmacChain('sha1', 'sha1HmacChainHex', data, encoding, options)
+}
diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.ts
index d56fca82e4c9..1665299406a2 100644
--- a/common/hogvm/typescript/src/stl/stl.ts
+++ b/common/hogvm/typescript/src/stl/stl.ts
@@ -3,7 +3,7 @@ import { DateTime } from 'luxon'
import { isHogAST, isHogCallable, isHogClosure, isHogDate, isHogDateTime, isHogError, newHogError } from '../objects'
import { AsyncSTLFunction, HogDate, HogDateTime, HogInterval, STLFunction } from '../types'
import { getNestedValue, like } from '../utils'
-import { md5, sha256, sha256HmacChain } from './crypto'
+import { md5, sha1, sha1HmacChain, sha256, sha256HmacChain } from './crypto'
import {
formatDateTime,
fromUnixTimestamp,
@@ -1120,6 +1120,20 @@ export const STL: Record<string, STLFunction> = {
minArgs: 1,
maxArgs: 2,
},
+ sha1Hex: {
+ fn: ([str], _, options) => sha1(str, 'hex', options),
+ description: 'Computes SHA-1 hash of a string. Only for compatibility with vendors that use SHA-1',
+ example: 'sha1($1)',
+ minArgs: 1,
+ maxArgs: 1,
+ },
+ sha1: {
+ fn: ([str, encoding], _, options) => sha1(str, encoding, options),
+ description: 'Computes SHA-1 hash of a string. Only for compatibility with vendors that use SHA-1',
+ example: 'sha1($1, $2)',
+ minArgs: 1,
+ maxArgs: 2,
+ },
md5Hex: {
fn: ([str], _, options) => md5(str, 'hex', options),
description: 'Computes MD5 hash of a string',
@@ -1134,6 +1148,20 @@ export const STL: Record<string, STLFunction> = {
minArgs: 1,
maxArgs: 2,
},
+ sha1HmacChainHex: {
+ fn: ([data], _, options) => sha1HmacChain(data, 'hex', options),
+ description: 'Computes SHA-1 HMAC chain hash. Two elements give a plain HMAC-SHA1 of key and message',
+ example: 'sha1HmacChainHex($1)',
+ minArgs: 1,
+ maxArgs: 1,
+ },
+ sha1HmacChain: {
+ fn: ([data, encoding], _, options) => sha1HmacChain(data, encoding, options),
+ description: 'Computes SHA-1 HMAC chain hash. Two elements give a plain HMAC-SHA1 of key and message',
+ example: 'sha1HmacChain($1, $2)',
+ minArgs: 1,
+ maxArgs: 2,
+ },
sha256HmacChainHex: {
fn: ([data], _, options) => sha256HmacChain(data, 'hex', options),
description: 'Computes SHA-256 HMAC chain hash',
diff --git a/posthog/hogql/compiler/javascript_stl.py b/posthog/hogql/compiler/javascript_stl.py
index 2e11a00ecdcc..604b90eb845d 100644
--- a/posthog/hogql/compiler/javascript_stl.py
+++ b/posthog/hogql/compiler/javascript_stl.py
@@ -326,6 +326,14 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
"function md5 (data, encoding, options) { return 'md5 not implemented' }",
[],
],
+ "sha1Hex": [
+ "function sha1Hex (data) { return 'sha1Hex not implemented' }",
+ [],
+ ],
+ "sha1": [
+ "function sha1 (data, encoding, options) { return 'sha1 not implemented' }",
+ [],
+ ],
"sha256HmacChainHex": [
"function sha256HmacChainHex (data, options) { return 'sha256HmacChainHex not implemented' }",
[],
@@ -334,6 +342,14 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
"function sha256HmacChain (data, encoding, options) { return 'sha256HmacChain not implemented' }",
[],
],
+ "sha1HmacChainHex": [
+ "function sha1HmacChainHex (data, options) { return 'sha1HmacChainHex not implemented' }",
+ [],
+ ],
+ "sha1HmacChain": [
+ "function sha1HmacChain (data, encoding, options) { return 'sha1HmacChain not implemented' }",
+ [],
+ ],
"isIPAddressInRange": [
"""
function isIPAddressInRange(address, prefix) {
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a4cc108196b5..259074e8b0a4 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -5417,6 +5417,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
+ "sha1",
"sha2 0.10.9",
"thiserror 2.0.18",
]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 8e9157795fb6..e40a7f49a137 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -267,5 +267,6 @@ clickhouse = { version = "0.13.2", features = [
fernet = "0.2"
tiktoken-rs = "0.7.0"
sha2 = "0.10"
+sha1 = "0.10"
hmac = "0.12"
testcontainers = "0.27.2"
diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.toml
index 0e04374fb141..af787b7b0f05 100644
--- a/rust/common/hogvm/Cargo.toml
+++ b/rust/common/hogvm/Cargo.toml
@@ -17,6 +17,7 @@ chrono-tz.workspace = true
indexmap = "2"
md-5 = "0.10"
sha2.workspace = true
+sha1.workspace = true
hmac.workspace = true
base64.workspace = true
once_cell.workspace = true
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 213c7c5463cf..199da3ac6165 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -4,6 +4,7 @@ use std::sync::Arc;
use base64::Engine as _;
use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike};
+use hmac::digest::KeyInit;
use hmac::{Hmac, Mac};
use indexmap::IndexMap;
use md5::Md5;
@@ -11,6 +12,7 @@ use once_cell::sync::Lazy;
use rand::Rng;
use serde::de::{MapAccess, SeqAccess, Visitor};
use serde_json::{json, Value as JsonValue};
+use sha1::Sha1;
use sha2::{Digest, Sha256};
use crate::{
@@ -1126,11 +1128,25 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
hash_optional_encoding(vm, &args, "sha256", |data| Sha256::digest(data).to_vec())
}),
),
+ // SHA-1 is only here because vendors sign webhooks with it. Never pick it for new work.
+ (
+ "sha1Hex",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "sha1Hex")?;
+ hash_with_encoding(vm, &args, |data| Sha1::digest(data).to_vec(), "hex")
+ }),
+ ),
+ (
+ "sha1",
+ native_func(|vm, args| {
+ hash_optional_encoding(vm, &args, "sha1", |data| Sha1::digest(data).to_vec())
+ }),
+ ),
(
"sha256HmacChainHex",
native_func(|vm, args| {
assert_argc(&args, 1, "sha256HmacChainHex")?;
- let digest = sha256_hmac_chain(vm, &args[0])?;
+ let digest = hmac_chain::<HmacSha256>(vm, &args[0], "sha256HmacChain")?;
Ok(HogLiteral::String(to_hex(&digest)).into())
}),
),
@@ -1142,7 +1158,28 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"sha256HmacChain takes 1 or 2 arguments".to_string(),
));
}
- let digest = sha256_hmac_chain(vm, &args[0])?;
+ let digest = hmac_chain::<HmacSha256>(vm, &args[0], "sha256HmacChain")?;
+ let encoding = encoding_arg(vm, &args, 1)?;
+ Ok(HogLiteral::String(encode_digest(&digest, &encoding)?).into())
+ }),
+ ),
+ (
+ "sha1HmacChainHex",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "sha1HmacChainHex")?;
+ let digest = hmac_chain::<HmacSha1>(vm, &args[0], "sha1HmacChain")?;
+ Ok(HogLiteral::String(to_hex(&digest)).into())
+ }),
+ ),
+ (
+ "sha1HmacChain",
+ native_func(|vm, args| {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "sha1HmacChain takes 1 or 2 arguments".to_string(),
+ ));
+ }
+ let digest = hmac_chain::<HmacSha1>(vm, &args[0], "sha1HmacChain")?;
let encoding = encoding_arg(vm, &args, 1)?;
Ok(HogLiteral::String(encode_digest(&digest, &encoding)?).into())
}),
@@ -2342,6 +2379,7 @@ fn ip_to_bytes(ip: &str, is_v4: bool) -> Option<Vec<u8>> {
}
type HmacSha256 = Hmac<Sha256>;
+type HmacSha1 = Hmac<Sha1>;
// Hash `data` with the supplied digest fn, then encode. Used by md5Hex/sha256Hex (fixed "hex").
// `null` data returns `null`, matching the reference.
@@ -2376,15 +2414,20 @@ fn hash_optional_encoding(
hash_with_encoding(vm, args, hasher, &encoding)
}
-// sha256HmacChain: HMAC-SHA256 chained across an array of strings, re-keying each step with the
-// previous raw digest. Mirrors common/hogvm/typescript/src/stl/crypto.ts.
-fn sha256_hmac_chain(vm: &HogVM, arg: &HogValue) -> Result<Vec<u8>, VmError> {
+// sha256HmacChain / sha1HmacChain: HMAC chained across an array of strings, re-keying each step
+// with the previous raw digest. A two-element array is a plain HMAC of key and message.
+// Mirrors common/hogvm/typescript/src/stl/crypto.ts.
+fn hmac_chain<M: Mac + KeyInit>(
+ vm: &HogVM,
+ arg: &HogValue,
+ name: &str,
+) -> Result<Vec<u8>, VmError> {
let arr = match arg.deref(&vm.heap)? {
HogLiteral::Array(a) => a.clone(),
_ => {
- return Err(VmError::NativeCallFailed(
- "sha256HmacChain expects an array".to_string(),
- ))
+ return Err(VmError::NativeCallFailed(format!(
+ "{name} expects an array"
+ )))
}
};
if arr.len() < 2 {
@@ -2393,13 +2436,13 @@ fn sha256_hmac_chain(vm: &HogVM, arg: &HogValue) -> Result<Vec<u8>, VmError> {
));
}
let key0: &str = arr[0].deref(&vm.heap)?.try_as()?;
- let mut mac = HmacSha256::new_from_slice(key0.as_bytes())
+ let mut mac = <M as Mac>::new_from_slice(key0.as_bytes())
.map_err(|e| VmError::NativeCallFailed(e.to_string()))?;
let msg1: &str = arr[1].deref(&vm.heap)?.try_as()?;
mac.update(msg1.as_bytes());
let mut digest = mac.finalize().into_bytes().to_vec();
for elem in &arr[2..] {
- let mut next = HmacSha256::new_from_slice(&digest)
+ let mut next = <M as Mac>::new_from_slice(&digest)
.map_err(|e| VmError::NativeCallFailed(e.to_string()))?;
let msg: &str = elem.deref(&vm.heap)?.try_as()?;
next.update(msg.as_bytes());
diff --git a/rust/common/hogvm/tests/stl.rs b/rust/common/hogvm/tests/stl.rs
index 08eac3e6afd5..0d5c326bedf5 100644
--- a/rust/common/hogvm/tests/stl.rs
+++ b/rust/common/hogvm/tests/stl.rs
@@ -67,6 +67,13 @@ fn crypto_and_encoding_known_answers() {
"hello",
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
),
+ (
+ "sha1Hex",
+ "hello",
+ "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d",
+ ),
+ ("sha1Hex", "abc", "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("sha1Hex", "", "da39a3ee5e6b4b0d3255bfef95601890afd80709"),
("base64Encode", "hello", "aGVsbG8="),
("base64Decode", "aGVsbG8=", "hello"),
];
@@ -75,6 +82,73 @@ fn crypto_and_encoding_known_answers() {
}
}
+#[test]
+fn hmac_sha1_matches_rfc_2202_vectors() {
+ // RFC 2202 HMAC-SHA1 test vectors. A two-element chain is a plain HMAC of key and message, so
+ // these pin the sha1 dependency and the chain wiring to the standard answers.
+ let key_0b = "\u{0b}".repeat(20);
+ let key_0c = "\u{0c}".repeat(20);
+ let cases: [(&str, &str, &str); 3] = [
+ (
+ &key_0b,
+ "Hi There",
+ "b617318655057264e28bc0b6fb378c8ef146be00",
+ ),
+ (
+ "Jefe",
+ "what do ya want for nothing?",
+ "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
+ ),
+ (
+ &key_0c,
+ "Test With Truncation",
+ "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04",
+ ),
+ ];
+ for (key, message, expected) in cases {
+ let arr = collection(OP_ARRAY, &[str_lit(key), str_lit(message)]);
+ assert_eq!(
+ run(call("sha1HmacChainHex", &[arr])),
+ json!(expected),
+ "sha1HmacChainHex([key, {message:?}])"
+ );
+ }
+}
+
+#[test]
+fn hmac_sha1_chain_rekeys_and_encodes() {
+ // Three or more elements re-key each step with the previous raw digest, and the optional
+ // second argument selects the encoding — both must match the Python and Node implementations.
+ let data = || {
+ collection(
+ OP_ARRAY,
+ &[
+ str_lit("1"),
+ str_lit("string"),
+ str_lit("more"),
+ str_lit("keys"),
+ ],
+ )
+ };
+ let cases: &[(&str, &str)] = &[
+ ("hex", "e559ff0c3fc9c9e13a5b5d78fcd722b4f7ec6a9a"),
+ ("base64", "5Vn/DD/JyeE6W114/NcitPfsapo="),
+ ("base64url", "5Vn_DD_JyeE6W114_NcitPfsapo"),
+ ];
+ for (encoding, expected) in cases {
+ assert_eq!(
+ run(call("sha1HmacChain", &[data(), str_lit(encoding)])),
+ json!(expected),
+ "sha1HmacChain(data, {encoding:?})"
+ );
+ }
+ // No encoding argument defaults to hex, matching sha1HmacChainHex.
+ assert_eq!(
+ run(call("sha1HmacChain", &[data()])),
+ run(call("sha1HmacChainHex", &[data()]))
+ );
+}
+
#[test]
fn base64_round_trips() {
let encoded = run(call("base64Encode", &[str_lit("Hello, World! 🦔")]));