// audit-verify.go - check one page of an IndyKite Audit Log API export without the platform.
//
// Usage:
//
//	go run audit-verify.go -logs response-logs.json -jwks response-jwks.json
//
// Needs Go 1.25 or later. The two files are the saved responses of
// GET /audit/v1/logs?project_id=<gid> and GET /audit/.well-known/jwks.json?project_id=<gid>.
//
// When the logs page does not start at sequence 1, pass the chain_hash of the batch before
// it with -prev, or the first link is reported as unchecked.
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"os"
)

// alg is the only algorithm the platform signs with: ECDSA P-256 over SHA-256, ASN.1 DER encoded.
const alg = "ES256-DER"

type logsPage struct {
	NextCursor string     `json:"next_cursor"`
	Items      []logEntry `json:"items"`
	HasMore    bool       `json:"has_more"`
}

type logEntry struct {
	BatchID    string          `json:"batch_id"`
	ProjectID  string          `json:"project_id"`
	Hash       string          `json:"hash"`
	Signature  string          `json:"signature"`
	KID        string          `json:"kid"`
	Alg        string          `json:"alg"`
	ChainHash  string          `json:"chain_hash"`
	ManifestID string          `json:"manifest_id"`
	Data       json.RawMessage `json:"data"`
	Sequence   uint64          `json:"sequence"`
}

type jwks struct {
	Keys []struct {
		Kty string `json:"kty"`
		Crv string `json:"crv"`
		Kid string `json:"kid"`
		X   string `json:"x"`
		Y   string `json:"y"`
	} `json:"keys"`
}

func main() {
	logsPath := flag.String("logs", "response-logs.json", "saved /audit/v1/logs response")
	jwksPath := flag.String("jwks", "response-jwks.json", "saved /audit/.well-known/jwks.json response")
	prev := flag.String("prev", "", "chain_hash of the batch before the first one in -logs (empty for sequence 1)")
	flag.Parse()

	keys, err := loadKeys(*jwksPath)
	if err != nil {
		fail(err)
	}
	var page logsPage
	if err = readJSON(*logsPath, &page); err != nil {
		fail(err)
	}
	if len(page.Items) == 0 {
		fail(errors.New("the logs response has no items"))
	}

	failures := 0
	prevHash, prevKnown := *prev, *prev != "" || page.Items[0].Sequence == 1
	for i, e := range page.Items {
		problems := verifyEntry(e, keys, prevHash, prevKnown)
		if i > 0 {
			before := page.Items[i-1]
			if e.Sequence != before.Sequence+1 {
				problems = append(problems, fmt.Sprintf("sequence %d follows %d: a batch is missing or out of order",
					e.Sequence, before.Sequence))
			}
			if e.ProjectID != before.ProjectID {
				problems = append(problems, fmt.Sprintf("project %s differs from %s", e.ProjectID, before.ProjectID))
			}
		}

		status := "OK  "
		if len(problems) > 0 {
			status = "FAIL"
			failures++
		}
		fmt.Printf("%s seq=%d batch=%s events=%d\n", status, e.Sequence, e.BatchID, countEvents(e.Data))
		if !prevKnown {
			fmt.Println("     chain link to the previous batch not checked: pass -prev")
		}
		for _, p := range problems {
			fmt.Println("     -", p)
		}

		// The next link is checked against what this batch records, so one bad batch is
		// reported once and does not fail every batch after it.
		prevHash, prevKnown = e.ChainHash, true
	}

	fmt.Printf("\n%d batches, %d failed\n", len(page.Items), failures)
	if page.HasMore {
		fmt.Println("has_more is true: this is not the end of the chain, fetch the next page with cursor=" +
			page.NextCursor)
	}
	if failures > 0 {
		os.Exit(1)
	}
}

// verifyEntry returns what is wrong with one batch, or nothing when every check passes.
func verifyEntry(e logEntry, keys map[string]*ecdsa.PublicKey, prevHash string, prevKnown bool) []string {
	var problems []string

	// The platform hashes the compact JSON encoding of data, with <, > and & escaped.
	// Marshalling the RawMessage again restores exactly those bytes, also when the saved
	// response was pretty-printed.
	payload, err := json.Marshal(e.Data)
	if err != nil {
		return append(problems, fmt.Sprintf("data is not valid JSON: %v", err))
	}
	digest := sha256.Sum256(payload)
	if got := hex.EncodeToString(digest[:]); got != e.Hash {
		problems = append(problems, fmt.Sprintf("data hashes to %s, batch records %s", got, e.Hash))
	}

	if err = verifySignature(keys, e); err != nil {
		problems = append(problems, err.Error())
	}

	if prevKnown {
		link := fmt.Sprintf("%s|%d|%s|%s|%s", e.ProjectID, e.Sequence, prevHash, e.Hash, e.BatchID)
		head := sha256.Sum256([]byte(link))
		if got := hex.EncodeToString(head[:]); got != e.ChainHash {
			problems = append(problems, fmt.Sprintf("chain_hash recomputes to %s, batch records %s", got, e.ChainHash))
		}
	}
	return problems
}

// verifySignature checks the signature over the digest the recorded hash stands for.
// The data itself is tied to that hash by the hash check.
func verifySignature(keys map[string]*ecdsa.PublicKey, e logEntry) error {
	if e.Alg != alg {
		return fmt.Errorf("alg is %q, want %q", e.Alg, alg)
	}
	key, ok := keys[e.KID]
	if !ok {
		return fmt.Errorf("kid %q is not in the JWKS", e.KID)
	}
	digest, err := hex.DecodeString(e.Hash)
	if err != nil || len(digest) != sha256.Size {
		return fmt.Errorf("hash %q is not a hex SHA-256 digest", e.Hash)
	}
	sig, err := base64.StdEncoding.DecodeString(e.Signature)
	if err != nil {
		return errors.New("signature is not base64")
	}
	if !ecdsa.VerifyASN1(key, digest, sig) {
		return fmt.Errorf("signature does not verify under kid %q", e.KID)
	}
	return nil
}

// loadKeys reads the P-256 keys of a JWKS, by kid.
func loadKeys(path string) (map[string]*ecdsa.PublicKey, error) {
	var set jwks
	if err := readJSON(path, &set); err != nil {
		return nil, err
	}
	keys := make(map[string]*ecdsa.PublicKey, len(set.Keys))
	for _, k := range set.Keys {
		if k.Kty != "EC" || k.Crv != "P-256" {
			return nil, fmt.Errorf("key %q is %s/%s, want EC/P-256", k.Kid, k.Kty, k.Crv)
		}
		x, errX := base64.RawURLEncoding.DecodeString(k.X)
		y, errY := base64.RawURLEncoding.DecodeString(k.Y)
		if errX != nil || errY != nil || len(x) != 32 || len(y) != 32 {
			return nil, fmt.Errorf("key %q has malformed x or y", k.Kid)
		}
		// The uncompressed point form is 0x04 || X || Y. Parsing it also checks the point is on the curve.
		point := append(append([]byte{0x04}, x...), y...)
		pub, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), point)
		if err != nil {
			return nil, fmt.Errorf("key %q: %w", k.Kid, err)
		}
		keys[k.Kid] = pub
	}
	if len(keys) == 0 {
		return nil, errors.New("the JWKS has no keys")
	}
	return keys, nil
}

func countEvents(data json.RawMessage) int {
	var events []json.RawMessage
	if json.Unmarshal(data, &events) != nil {
		return -1
	}
	return len(events)
}

func readJSON(path string, v any) error {
	b, err := os.ReadFile(path)
	if err != nil {
		return err
	}
	if err = json.Unmarshal(b, v); err != nil {
		return fmt.Errorf("%s: %w", path, err)
	}
	return nil
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, "error:", err)
	os.Exit(2)
}
