2025-01-26 12:44:34 +01:00
package artifactcache
import (
"strconv"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestMac ( t * testing . T ) {
2025-09-05 11:17:57 +02:00
cache := & cachesImpl {
2025-01-26 12:44:34 +01:00
secret : "secret for testing" ,
}
t . Run ( "validate correct mac" , func ( t * testing . T ) {
name := "org/reponame"
run := "1"
ts := strconv . FormatInt ( time . Now ( ) . Unix ( ) , 10 )
2025-09-05 11:17:57 +02:00
mac := ComputeMac ( cache . secret , name , run , ts , "" )
2025-09-05 06:01:49 +00:00
rundata := RunData {
2025-01-26 12:44:34 +01:00
RepositoryFullName : name ,
RunNumber : run ,
Timestamp : ts ,
RepositoryMAC : mac ,
}
2025-09-05 11:17:57 +02:00
repoName , err := cache . validateMac ( rundata )
2025-01-26 12:44:34 +01:00
require . NoError ( t , err )
require . Equal ( t , name , repoName )
} )
t . Run ( "validate incorrect timestamp" , func ( t * testing . T ) {
name := "org/reponame"
run := "1"
ts := "9223372036854775807" // This should last us for a while...
2025-09-05 11:17:57 +02:00
mac := ComputeMac ( cache . secret , name , run , ts , "" )
2025-09-05 06:01:49 +00:00
rundata := RunData {
2025-01-26 12:44:34 +01:00
RepositoryFullName : name ,
RunNumber : run ,
Timestamp : ts ,
RepositoryMAC : mac ,
}
2025-09-05 11:17:57 +02:00
_ , err := cache . validateMac ( rundata )
2025-01-26 12:44:34 +01:00
require . Error ( t , err )
} )
t . Run ( "validate incorrect mac" , func ( t * testing . T ) {
name := "org/reponame"
run := "1"
ts := strconv . FormatInt ( time . Now ( ) . Unix ( ) , 10 )
2025-09-05 06:01:49 +00:00
rundata := RunData {
2025-01-26 12:44:34 +01:00
RepositoryFullName : name ,
RunNumber : run ,
Timestamp : ts ,
RepositoryMAC : "this is not the right mac :D" ,
}
2025-09-05 11:17:57 +02:00
repoName , err := cache . validateMac ( rundata )
2025-01-26 12:44:34 +01:00
require . Error ( t , err )
2025-03-21 13:57:25 +01:00
require . Equal ( t , "" , repoName )
2025-01-26 12:44:34 +01:00
} )
t . Run ( "compute correct mac" , func ( t * testing . T ) {
secret := "this is my cool secret string :3"
name := "org/reponame"
run := "42"
ts := "1337"
2025-09-05 06:01:49 +00:00
mac := ComputeMac ( secret , name , run , ts , "" )
expectedMac := "4754474b21329e8beadd2b4054aa4be803965d66e710fa1fee091334ed804f29" // * Precomputed, anytime the ComputeMac function changes this needs to be recalculated
2025-08-19 11:18:32 -06:00
require . Equal ( t , expectedMac , mac )
2025-01-26 12:44:34 +01:00
2025-09-05 06:01:49 +00:00
mac = ComputeMac ( secret , name , run , ts , "refs/pull/12/head" )
expectedMac = "9ca8f4cb5e1b083ee8cd215215bc00f379b28511d3ef7930bf054767de34766d" // * Precomputed, anytime the ComputeMac function changes this needs to be recalculated
2025-08-19 11:18:32 -06:00
require . Equal ( t , expectedMac , mac )
2025-01-26 12:44:34 +01:00
} )
}