// Package auth handles Google OAuth2 for the CLI using a local loopback server // to receive the authorization code. package auth import ( "context" "crypto/rand" "encoding/base64" "errors" "fmt" "net" "net/http" "os/exec" "runtime" "time" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "git.onurgunduz.com/colabctl/internal/config" ) // Scopes required to use the Drive API and the Colab runtime API. // The colaboratory scope is mandatory; without it the /tun/m/assign // endpoint returns 403 SCOPE_NOT_PERMITTED. var scopes = []string{ "openid", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/colaboratory", "https://www.googleapis.com/auth/drive", } // oauthConfig builds an oauth2.Config from the supplied client credentials. func oauthConfig(clientID, clientSecret, redirectURL string) *oauth2.Config { return &oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL, Scopes: scopes, Endpoint: google.Endpoint, } } // Login performs an interactive OAuth2 flow. It starts a temporary local HTTP // server on a free port, opens the browser for the user, waits for the // authorization code, exchanges it for tokens, and persists them to disk. func Login(ctx context.Context, clientID, clientSecret string) error { // Pick a free port on localhost. listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return fmt.Errorf("start local server: %w", err) } port := listener.Addr().(*net.TCPAddr).Port redirectURL := fmt.Sprintf("http://127.0.0.1:%d/callback", port) cfg := oauthConfig(clientID, clientSecret, redirectURL) // Generate a random state value to guard against CSRF. state, err := randomState() if err != nil { return err } authURL := cfg.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.ApprovalForce) codeCh := make(chan string, 1) errCh := make(chan error, 1) mux := http.NewServeMux() srv := &http.Server{Handler: mux} mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("state") != state { http.Error(w, "state mismatch", http.StatusBadRequest) errCh <- errors.New("oauth2 state mismatch; possible CSRF") return } code := r.URL.Query().Get("code") if code == "" { msg := r.URL.Query().Get("error") http.Error(w, "authorization denied", http.StatusBadRequest) errCh <- fmt.Errorf("authorization denied: %s", msg) return } fmt.Fprintln(w, "