package oidc import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" "sync/atomic" "testing" "time" ) func TestDeviceCodeFlowAndSave(t *testing.T) { var attempts atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { w.WriteHeader(http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/oauth/v2/device_authorization": if r.Form.Get("client_id") != "400047321930268787" { w.WriteHeader(http.StatusBadRequest) return } _ = json.NewEncoder(w).Encode(DeviceAuthResponse{ DeviceCode: "dev-123", UserCode: "ABCD-EFGH", VerificationURI: "https://auth.site.latha.org/device", VerificationURIComplete: "https://auth.site.latha.org/device?user_code=ABCD-EFGH", ExpiresIn: 300, Interval: 1, }) case "/oauth/v2/token": n := attempts.Add(1) if n == 1 { w.WriteHeader(http.StatusBadRequest) _ = json.NewEncoder(w).Encode(map[string]string{"error": "authorization_pending"}) return } _ = json.NewEncoder(w).Encode(TokenResponse{ AccessToken: "access-1", IDToken: "id-1", TokenType: "Bearer", ExpiresIn: 3600, }) default: w.WriteHeader(http.StatusNotFound) } })) defer srv.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() da, err := RequestDeviceCode(ctx, srv.Client(), srv.URL, DefaultK3sClientID, DefaultK3sScope) if err != nil { t.Fatalf("RequestDeviceCode: %v", err) } if da.UserCode != "ABCD-EFGH" { t.Fatalf("UserCode = %q, want ABCD-EFGH", da.UserCode) } tok, err := PollDeviceToken(ctx, srv.Client(), srv.URL, DefaultK3sClientID, da.DeviceCode, 10*time.Millisecond) if err != nil { t.Fatalf("PollDeviceToken: %v", err) } if tok.IDToken != "id-1" { t.Fatalf("IDToken = %q, want id-1", tok.IDToken) } outPath := filepath.Join(t.TempDir(), "nested", "k3s-token.json") if err := SaveTokenFile(outPath, tok); err != nil { t.Fatalf("SaveTokenFile: %v", err) } info, err := os.Stat(outPath) if err != nil { t.Fatalf("Stat: %v", err) } if info.Mode().Perm() != 0o600 { t.Fatalf("file perm = %o, want 0600", info.Mode().Perm()) } }