package coderunner import ( "crypto/hmac" "crypto/sha256" "encoding/binary" "github.com/google/uuid" "lincodex/backend/internal/port/outbound" ) // runIDDomain separates run IDs from any other use of the same HMAC key. const runIDDomain = "lincodex.code-run.v1" // deriveRunID maps a run key to the opaque ID the runner stores the run under. // // The ID is deterministic, so a retry of the same submission reuses the run // instead of starting a second one (the runner is idempotent by run ID). It is // keyed with a secret that only the backend knows, so the runner cannot link // an ID back to an attempt item or a submission, and nobody can guess the ID // of another submission. The result is a valid UUID (version 8, RFC 9562) as // the runner contract requires. func deriveRunID(secret []byte, key outbound.CodeRunKey) uuid.UUID { mac := hmac.New(sha256.New, secret) mac.Write([]byte(runIDDomain)) mac.Write([]byte{0}) mac.Write(key.AttemptItemID[:]) mac.Write(key.SubmissionID[:]) var generation [4]byte binary.BigEndian.PutUint32(generation[:], key.Generation) mac.Write(generation[:]) var id uuid.UUID copy(id[:], mac.Sum(nil)) id[6] = id[6]&0x0f | 0x80 id[8] = id[8]&0x3f | 0x80 return id }