nix-cache-login/cmd/status_test.go
Abel Luck f0e29d38a4
All checks were successful
buildbot/nix-eval Build done.
buildbot/nix-build Build done.
buildbot/nix-effects Build done.
Release v0.1.3
2026-02-28 20:12:46 +01:00

148 lines
2.8 KiB
Go

package cmd
import (
"testing"
"guardianproject.dev/ops/nix-cache-login/internal/config"
)
func TestIsConfiguredServiceAccountMode(t *testing.T) {
tests := []struct {
name string
cfg *config.Config
want bool
}{
{
name: "nil config",
cfg: nil,
want: false,
},
{
name: "user mode",
cfg: &config.Config{},
want: false,
},
{
name: "service account mode",
cfg: &config.Config{
ClientSecretFile: "/run/secrets/nix-cache-client-secret",
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isConfiguredServiceAccountMode(tt.cfg); got != tt.want {
t.Fatalf("isConfiguredServiceAccountMode() = %v, want %v", got, tt.want)
}
})
}
}
func TestIsServiceAccountToken(t *testing.T) {
tests := []struct {
name string
claims map[string]interface{}
want bool
}{
{
name: "grant type client_credentials",
claims: map[string]interface{}{
"gty": "client_credentials",
},
want: true,
},
{
name: "grant type client-credentials",
claims: map[string]interface{}{
"gty": "client-credentials",
},
want: true,
},
{
name: "service-account preferred_username",
claims: map[string]interface{}{
"preferred_username": "service-account-nix-cache-server",
},
want: true,
},
{
name: "service-account subject",
claims: map[string]interface{}{
"sub": "service-account-nix-cache-server",
},
want: true,
},
{
name: "normal user token",
claims: map[string]interface{}{
"preferred_username": "alice",
"sub": "9f788180-5f78-4ce4-8126-8f9406de5628",
},
want: false,
},
{
name: "nil claims",
claims: nil,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isServiceAccountToken(tt.claims); got != tt.want {
t.Fatalf("isServiceAccountToken() = %v, want %v", got, tt.want)
}
})
}
}
func TestTokenClientID(t *testing.T) {
tests := []struct {
name string
claims map[string]interface{}
want string
}{
{
name: "from azp",
claims: map[string]interface{}{
"azp": "nix-cache-server",
},
want: "nix-cache-server",
},
{
name: "from client_id",
claims: map[string]interface{}{
"client_id": "nix-cache-server",
},
want: "nix-cache-server",
},
{
name: "prefer azp over client_id",
claims: map[string]interface{}{
"azp": "nix-cache-server",
"client_id": "other",
},
want: "nix-cache-server",
},
{
name: "not present",
claims: map[string]interface{}{},
want: "",
},
{
name: "nil claims",
claims: nil,
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tokenClientID(tt.claims); got != tt.want {
t.Fatalf("tokenClientID() = %q, want %q", got, tt.want)
}
})
}
}