You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.7 KiB
Go
57 lines
1.7 KiB
Go
package auth_test
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"net/http"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.luoli.live/root/virt/agent/auth"
|
|
"git.luoli.live/root/virt/agent/operation"
|
|
)
|
|
|
|
func TestDurableNonceRejectsReplayAfterRestart(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "operations.db")
|
|
now := time.Unix(2_000_000_000, 0)
|
|
secret := []byte("0123456789abcdef0123456789abcdef")
|
|
body := []byte(`{"action":"start"}`)
|
|
|
|
firstJournal, err := operation.Open(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
first, err := auth.NewWithNonceStore(secret, 5*time.Minute, 10*time.Minute, firstJournal)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
first.SetClockForTesting(func() time.Time { return now })
|
|
request, _ := http.NewRequest(http.MethodPost, "https://agent.test/v1/vms/123/actions", bytes.NewReader(body))
|
|
// A timestamp at the positive skew boundary remains valid until twice the
|
|
// skew after first receipt. The nonce must remain live at that exact edge.
|
|
if err := auth.Sign(request, body, auth.Actor{UserID: 1, CanManage: true, OperationID: "operation-restart"}, secret, now.Add(5*time.Minute).Unix(), "restartNonce1234"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := first.Authenticate(request, body); err != nil {
|
|
t.Fatalf("first authentication: %v", err)
|
|
}
|
|
if err := firstJournal.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
reopened, err := operation.Open(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer reopened.Close()
|
|
second, err := auth.NewWithNonceStore(secret, 5*time.Minute, 10*time.Minute, reopened)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
second.SetClockForTesting(func() time.Time { return now.Add(10 * time.Minute) })
|
|
if _, err := second.Authenticate(request, body); !errors.Is(err, auth.ErrReplay) {
|
|
t.Fatalf("restart replay error = %v, want ErrReplay", err)
|
|
}
|
|
}
|