package pkg import ( "bytes" "context" "fmt" "io" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "reflect" "strings" "testing" "time" "golang.org/x/oauth2" ) const testClientSecret = `{ "installed": { "client_id": "test-client", "client_secret": "test-secret", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "redirect_uris": ["http://127.0.0.1"] } }` func TestHasScope(t *testing.T) { scopes := []string{scopeUpload} if !hasScope(scopes, scopeUpload) { t.Error("hasScope() = false for a present scope") } if hasScope(scopes, scopeReadonly) { t.Error("hasScope() = true for a missing scope") } } func TestGrantedScopes(t *testing.T) { token := (&oauth2.Token{AccessToken: "x"}).WithExtra(map[string]any{ "scope": scopeUpload + " " + scopeReadonly, }) got := grantedScopes(token, []string{"fallback"}) want := []string{scopeUpload, scopeReadonly} if !reflect.DeepEqual(got, want) { t.Errorf("grantedScopes() = %v, want %v", got, want) } } func TestGrantedScopesFallback(t *testing.T) { got := grantedScopes(&oauth2.Token{}, []string{scopeUpload}) want := []string{scopeUpload} if !reflect.DeepEqual(got, want) { t.Errorf("grantedScopes() = %v, want %v", got, want) } } func TestSaveLoadToken(t *testing.T) { token := (&oauth2.Token{ AccessToken: "access", RefreshToken: "refresh", Expiry: time.Now().Add(time.Hour).Truncate(time.Second), }).WithExtra(map[string]any{ "scope": scopeUpload + " " + scopeReadonly, }) path := filepath.Join(t.TempDir(), "token.json") if err := saveToken(path, token, []string{scopeUpload}); err != nil { t.Fatalf("saveToken() error = %v", err) } stored, err := loadToken(path) if err != nil { t.Fatalf("loadToken() error = %v", err) } if stored.AccessToken != "access" || stored.RefreshToken != "refresh" { t.Errorf("stored token = %#v, want the saved access and refresh tokens", stored) } wantScopes := []string{scopeUpload, scopeReadonly} if !reflect.DeepEqual(stored.Scopes, wantScopes) { t.Errorf("stored scopes = %v, want %v", stored.Scopes, wantScopes) } if !stored.token().Expiry.Equal(token.Expiry) { t.Errorf("stored expiry = %v, want %v", stored.token().Expiry, token.Expiry) } } func TestSaveTokenOmitsZeroExpiry(t *testing.T) { path := filepath.Join(t.TempDir(), "token.json") if err := saveToken(path, &oauth2.Token{AccessToken: "access"}, []string{scopeUpload}); err != nil { t.Fatalf("saveToken() error = %v", err) } data, err := os.ReadFile(path) if err != nil { t.Fatalf("could not read token file: %v", err) } if bytes.Contains(data, []byte(`"expiry"`)) { t.Errorf("token file contains expiry for a zero expiry: %s", data) } } func TestAuthorizeReauthorizesForReadonly(t *testing.T) { dir := t.TempDir() secretPath := filepath.Join(dir, "client_secret.json") if err := os.WriteFile(secretPath, []byte(testClientSecret), 0o600); err != nil { t.Fatalf("could not write client secret: %v", err) } tokenPath := filepath.Join(dir, "token.json") token := (&oauth2.Token{ AccessToken: "access", RefreshToken: "refresh", Expiry: time.Now().Add(time.Hour), }).WithExtra(map[string]any{"scope": scopeUpload}) if err := saveToken(tokenPath, token, []string{scopeUpload}); err != nil { t.Fatalf("saveToken() error = %v", err) } ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := Authorize(ctx, AuthOptions{ ClientSecretFile: secretPath, TokenFile: tokenPath, NeedReadonly: true, Out: io.Discard, }); err == nil { t.Fatal("Authorize() error = nil, want the re-authorization flow to be entered") } } func TestAuthorizeUsesCachedReadonlyToken(t *testing.T) { dir := t.TempDir() secretPath := filepath.Join(dir, "client_secret.json") if err := os.WriteFile(secretPath, []byte(testClientSecret), 0o600); err != nil { t.Fatalf("could not write client secret: %v", err) } tokenPath := filepath.Join(dir, "token.json") token := (&oauth2.Token{ AccessToken: "access", RefreshToken: "refresh", Expiry: time.Now().Add(time.Hour), }).WithExtra(map[string]any{"scope": scopeUpload + " " + scopeReadonly}) if err := saveToken(tokenPath, token, []string{scopeUpload, scopeReadonly}); err != nil { t.Fatalf("saveToken() error = %v", err) } if _, err := Authorize(context.Background(), AuthOptions{ ClientSecretFile: secretPath, TokenFile: tokenPath, NeedReadonly: true, Out: io.Discard, }); err != nil { t.Fatalf("Authorize() error = %v, want cached token to be used", err) } } func TestAuthorizeManual(t *testing.T) { exchanges := make(chan url.Values, 1) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { t.Errorf("could not parse token request: %v", err) } exchanges <- r.PostForm w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"access_token":"access","token_type":"Bearer","refresh_token":"refresh","expires_in":3600}`) })) defer server.Close() conf := &oauth2.Config{ ClientID: "client", ClientSecret: "secret", Endpoint: oauth2.Endpoint{ AuthURL: "https://example.com/auth", TokenURL: server.URL, }, Scopes: []string{scopeUpload}, } var out bytes.Buffer reader := &manualRedirectReader{out: &out, port: defaultManualAuthPort} token, err := authorizeManual(context.Background(), conf, defaultManualAuthPort, reader, &out) if err != nil { t.Fatalf("authorizeManual() error = %v", err) } if token.AccessToken != "access" { t.Errorf("AccessToken = %q, want %q", token.AccessToken, "access") } select { case form := <-exchanges: if got := form.Get("code"); got != "test-code" { t.Errorf("exchanged code = %q, want %q", got, "test-code") } wantRedirect := fmt.Sprintf("http://127.0.0.1:%d", defaultManualAuthPort) if got := form.Get("redirect_uri"); got != wantRedirect { t.Errorf("redirect_uri = %q, want %q", got, wantRedirect) } default: t.Error("token endpoint was not called") } } // manualRedirectReader extracts the generated state from the auth URL in out // and returns the redirect URL a browser would have produced. type manualRedirectReader struct { out *bytes.Buffer port int done bool } func (r *manualRedirectReader) Read(p []byte) (int, error) { if r.done { return 0, io.EOF } r.done = true state := "" for _, line := range strings.Split(r.out.String(), "\n") { if !strings.HasPrefix(line, "https://") { continue } u, err := url.Parse(line) if err != nil { return 0, err } state = u.Query().Get("state") break } if state == "" { return 0, fmt.Errorf("auth URL with state not found in %q", r.out.String()) } redirect := fmt.Sprintf("http://127.0.0.1:%d/?state=%s&code=test-code\n", r.port, state) return copy(p, redirect), nil } func TestAuthorizationCode(t *testing.T) { const state = "expected-state" tests := []struct { name string input string want string wantErr string }{ { name: "full URL", input: "http://127.0.0.1:8090/?state=expected-state&code=abc", want: "abc", }, { name: "without scheme", input: "127.0.0.1:8090/?state=expected-state&code=abc", want: "abc", }, { name: "wrong state", input: "http://127.0.0.1:8090/?state=other&code=abc", wantErr: "invalid OAuth state", }, { name: "missing code", input: "http://127.0.0.1:8090/?state=expected-state", wantErr: "does not contain a code", }, { name: "error parameter", input: "http://127.0.0.1:8090/?error=access_denied&state=expected-state", wantErr: "access_denied", }, { name: "empty", input: "", wantErr: "empty redirect URL", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got, err := authorizationCode(test.input, state) if test.wantErr != "" { if err == nil { t.Fatalf("authorizationCode() error = nil, want it to contain %q", test.wantErr) } if !strings.Contains(err.Error(), test.wantErr) { t.Errorf("authorizationCode() error = %q, want it to contain %q", err, test.wantErr) } return } if err != nil { t.Fatalf("authorizationCode() error = %v", err) } if got != test.want { t.Errorf("authorizationCode() = %q, want %q", got, test.want) } }) } }