a73x

internal/server/api/injectedkey_test.go

Ref:   Size: 2.7 KiB   History

package api

import (
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

// realKey is a genuine ed25519 authorized_keys line, so the fingerprint below
// is the one OpenSSH itself computes (`ssh-keygen -lf`).
const realKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM0uJyEWzAFdAelGXHwoFgSRL+py8ZMonqWw+M4wj6HG alex@laptop"

func TestDescribeKey(t *testing.T) {
	t.Run("a real key is identified by fingerprint", func(t *testing.T) {
		typ, fp, comment := describeKey(realKey)
		assert.Equal(t, "ssh-ed25519", typ)
		assert.True(t, strings.HasPrefix(fp, "SHA256:"), "fingerprint must be OpenSSH-spelled, got %q", fp)
		assert.Equal(t, "alex@laptop", comment)
	})

	t.Run("no key injected is three empties", func(t *testing.T) {
		typ, fp, comment := describeKey("")
		assert.Empty(t, typ)
		assert.Empty(t, fp)
		assert.Empty(t, comment)
	})

	// Create deliberately accepts any single-line key — the guest's sshd decides
	// what it honours — so an unreadable one must still be described, not
	// dropped. An empty fingerprint is the signal, and it must be
	// distinguishable from "no key at all".
	t.Run("an unreadable key still says what it claims to be", func(t *testing.T) {
		typ, fp, comment := describeKey("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI test@host")
		assert.Equal(t, "ssh-ed25519", typ)
		assert.Empty(t, fp, "an unreadable key has no fingerprint")
		assert.Empty(t, comment)
	})

	t.Run("bounded against a hostile line", func(t *testing.T) {
		typ, _, _ := describeKey(strings.Repeat("z", 5000))
		assert.LessOrEqual(t, len(typ), 32, "an unparseable type must be bounded")

		long := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM0uJyEWzAFdAelGXHwoFgSRL+py8ZMonqWw+M4wj6HG " +
			strings.Repeat("c", 5000)
		_, _, comment := describeKey(long)
		// 128 is a literal on both sides on purpose: the truncation itself is
		// pinned by the assertion above, but a bound compared to the constant
		// that sets it holds at 4096 too, and the number is the whole point.
		assert.LessOrEqual(t, len(comment), 128,
			"a key comment is free text that lands on the VM row and renders in the console: 128 bytes is the bound that "+
				"keeps a hostile 5000-byte line from filling the column and the page, and an authorized_keys comment is "+
				"conventionally a short user@host, so nothing legitimate is near it")

		_, _, ordinary := describeKey("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM0uJyEWzAFdAelGXHwoFgSRL+py8ZMonqWw+M4wj6HG " +
			"alex@workstation.example.com")
		assert.Equal(t, "alex@workstation.example.com", ordinary,
			"and the bound must stay well clear of a real comment: cut it short and every operator sees their own key "+
				"described by a mangled prefix of the name they gave it")
	})
}