tursodatabase / libsql

libSQL is a fork of SQLite that is both Open Source, and Open Contributions.
https://turso.tech/libsql
MIT License
10.02k stars 262 forks source link

Token in libsql connection string #165

Closed wbrijesh closed 1 year ago

wbrijesh commented 1 year ago

I was trying to connect to turso database from a go app

package main

import (
    "database/sql"
    "fmt"
    "net/http"
    "os"
)

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8000"
    }

    fmt.Println("Listening on port", port)
    http.ListenAndServe(":"+port, nil)

    db, err := sql.Open("libsql", "libsql://udealz-wbrijesh.turso.io")

        if err != nil {
            fmt.Println("Error: ", err)
            return
        }

        http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
            rows, err := db.Query("SELECT * FROM users")
            if err != nil {
                fmt.Fprintf(w, "Error: %v", err)
                return
            }
            defer rows.Close()

            for rows.Next() {
                var id int
                var name string
                var email string
                var password string
                var created_at string
                var updated_at string
                err = rows.Scan(&id, &name, &email, &password, &created_at, &updated_at)
                if err != nil {
                    fmt.Fprintf(w, "Error: %v", err)
                    return
                }
                fmt.Fprintf(w, "id: %v, name: %v, email: %v, password: %v, created_at: %v, updated_at: %v\n", id, name, email, password, created_at, updated_at)
            }
        })
}

and curl localhost:8000/users gives this error

Error: handshake error: Authentication failed: The JWT is invalid

example from turso's documentation shows that token is needed for connection

const client = createClient({
    url: "libsql://your-database.turso.io",
    authToken: "your-auth-token"
});

I am used to writing

postgres://{user}:{password}@{hostname}:{port}/{database-name}

being able to do

db, err := sql.Open("libsql", "libsql://udealz-wbrijesh.turso.io?token=xyz")

would be great

CodingDoug commented 1 year ago

If you're using the golang client library, this should probably be posted in the client library repo, as that is responsible for taking your configuration and acting on it in such a way that sqld already recognizes. With other client libraries, the library takes a custom configuration object, and internally adds the auth token to the Authentication HTTP header, but the golang client doesn't give you that amount of control over the interaction.

Could you try the add the query string ?authToken=[token] or ?jwt=[token]? The former is ideally what we want, but it might not be implemented yet. The latter I'm pretty sure works today.