From fb79db4e21b3e48c6fdbf18a9bea5f35324d7822 Mon Sep 17 00:00:00 2001 From: nandi <78769380+codegod100@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:19:36 +0000 Subject: [PATCH] feat: add atproto OAuth login and token commands New internal/atproto package implements the atproto OAuth profile as a public client: handle/DID resolution with bidirectional verification, PDS and authorization-server metadata discovery, PAR + PKCE, ES256 DPoP proofs with server-nonce retry, and token exchange/refresh with sub verification. Sessions (tokens + DPoP key) are saved 0600. 'latha-auth atproto' collects the code via the existing deploy relay; 'latha-auth atproto-token' prints a refreshed access token. --- README.md | 4 +- cmd/latha-auth/main.go | 178 ++++++++++++++++- internal/atproto/atproto_test.go | 321 +++++++++++++++++++++++++++++++ internal/atproto/discover.go | 154 +++++++++++++++ internal/atproto/dpop.go | 163 ++++++++++++++++ internal/atproto/dpop_test.go | 118 ++++++++++++ internal/atproto/identity.go | 194 +++++++++++++++++++ internal/atproto/oauth.go | 251 ++++++++++++++++++++++++ internal/atproto/session.go | 154 +++++++++++++++ 9 files changed, 1531 insertions(+), 6 deletions(-) create mode 100644 internal/atproto/atproto_test.go create mode 100644 internal/atproto/discover.go create mode 100644 internal/atproto/dpop.go create mode 100644 internal/atproto/dpop_test.go create mode 100644 internal/atproto/identity.go create mode 100644 internal/atproto/oauth.go create mode 100644 internal/atproto/session.go diff --git a/README.md b/README.md index 6b2a71f..e5e77c0 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ # latha-auth -Zero-localhost OAuth CLI for remote VMs authenticating against Gitea (`git.site.latha.org`) and Zitadel (`auth.site.latha.org`). +Zero-localhost OAuth CLI for remote VMs authenticating against Gitea (`git.site.latha.org`), Zitadel (`auth.site.latha.org`), and AT Protocol (any PDS). ## Commands - `latha-auth gitea`: Authenticates with Gitea via PKCE + the `https://deploy.site.latha.org/oauth/callback` relay, configures `tea login` (`latha`), and sets up git credentials. - `latha-auth k3s`: Runs Zitadel OAuth 2.0 Device Code flow for K3s Headlamp (`dash.latha.org`, `client_id=400047321930268787`) and saves the token to `~/.config/latha-auth/k3s-token.json` (`0600`). - `latha-auth oidc --client-id [--scope "..."] [--out ]`: Generic Zitadel Device Code flow for any `auth.site.latha.org` service. +- `latha-auth atproto --identifier [--scope "..."] [--out ]`: AT Protocol OAuth (PAR + PKCE + DPoP) as a public client, collecting the code via the same deploy relay. Saves the session — tokens plus the DPoP private key they are bound to — to `~/.config/latha-auth/atproto-session.json` (`0600`). One-time setup: host the output of `latha-auth atproto --print-client-metadata` at the client_id URL (default `https://deploy.site.latha.org/oauth/atproto-client-metadata.json`, override with `--client-id` or `LATHA_ATPROTO_CLIENT_ID`). +- `latha-auth atproto-token [--refresh] [--json]`: Prints a valid access token from the saved session, refreshing in place when expired. Note tokens are DPoP-bound: consumers must sign per-request DPoP proofs with the session key, so this is for DPoP-aware tooling. ## Install diff --git a/cmd/latha-auth/main.go b/cmd/latha-auth/main.go index 48df44f..4e3adb3 100644 --- a/cmd/latha-auth/main.go +++ b/cmd/latha-auth/main.go @@ -11,12 +11,13 @@ import ( "syscall" "time" + "git.site.latha.org/experiments/latha-auth/internal/atproto" "git.site.latha.org/experiments/latha-auth/internal/gitea" "git.site.latha.org/experiments/latha-auth/internal/oidc" "git.site.latha.org/experiments/latha-auth/internal/pkce" ) -const version = "0.1.0" +const version = "0.2.0" func main() { if len(os.Args) < 2 { @@ -35,6 +36,10 @@ func main() { err = runK3s(ctx, os.Args[2:]) case "oidc": err = runOIDC(ctx, os.Args[2:]) + case "atproto": + err = runAtproto(ctx, os.Args[2:]) + case "atproto-token": + err = runAtprotoToken(ctx, os.Args[2:]) case "version", "--version", "-v": fmt.Printf("latha-auth %s\n", version) return @@ -60,10 +65,12 @@ Usage: latha-auth [flags] Commands: - gitea Authenticate with Gitea (git.site.latha.org) via PKCE + relay - k3s Authenticate with K3s Headlamp (dash.latha.org) via Zitadel Device Code - oidc Authenticate with any Zitadel service (auth.site.latha.org) via Device Code - version Print version + gitea Authenticate with Gitea (git.site.latha.org) via PKCE + relay + k3s Authenticate with K3s Headlamp (dash.latha.org) via Zitadel Device Code + oidc Authenticate with any Zitadel service (auth.site.latha.org) via Device Code + atproto Authenticate with AT Protocol via OAuth (PAR + PKCE + DPoP) + relay + atproto-token Print a valid atproto access token, refreshing the saved session if needed + version Print version Run 'latha-auth --help' for command-specific flags. `) @@ -207,3 +214,164 @@ func runDeviceFlow(ctx context.Context, authURL, clientID, scope, outPath string fmt.Printf("Saved token to %s (0600).\n", resolved) return nil } + +func runAtproto(ctx context.Context, args []string) error { + defaultClientID := os.Getenv("LATHA_ATPROTO_CLIENT_ID") + if defaultClientID == "" { + defaultClientID = atproto.DefaultClientID + } + + fs := flag.NewFlagSet("atproto", flag.ContinueOnError) + identifier := fs.String("identifier", "", "Account handle or DID (required unless --print-client-metadata)") + clientID := fs.String("client-id", defaultClientID, "OAuth client_id URL serving the client metadata JSON (or LATHA_ATPROTO_CLIENT_ID)") + scope := fs.String("scope", atproto.DefaultScope, "OAuth scope") + relayURL := fs.String("relay-url", gitea.DefaultRelayURL, "OAuth callback relay base URL") + redirectURI := fs.String("redirect-uri", "", "OAuth redirect URI (defaults to /oauth/callback)") + outPath := fs.String("out", atproto.DefaultSessionPath, "Output session JSON path") + plcURL := fs.String("plc-url", atproto.DefaultPLCURL, "PLC directory base URL") + timeout := fs.Duration("timeout", 5*time.Minute, "Authorization timeout") + printMetadata := fs.Bool("print-client-metadata", false, "Print the client metadata JSON to host at --client-id and exit") + if err := fs.Parse(args); err != nil { + return err + } + + if *redirectURI == "" { + *redirectURI = gitea.RedirectURI(*relayURL) + } + + if *printMetadata { + b, err := json.MarshalIndent(atproto.BuildClientMetadata(*clientID, *redirectURI, *scope), "", " ") + if err != nil { + return err + } + fmt.Println(string(b)) + return nil + } + if *identifier == "" { + return fmt.Errorf("--identifier is required") + } + + httpClient := &http.Client{Timeout: 15 * time.Second} + + meta, err := atproto.FetchClientMetadata(ctx, httpClient, *clientID) + if err != nil { + return fmt.Errorf("fetch client metadata: %w\nhost the output of 'latha-auth atproto --print-client-metadata' at %s first", err, *clientID) + } + if err := meta.ValidateFor(*redirectURI, *scope); err != nil { + return err + } + + resolved, err := atproto.ResolveAuthServer(ctx, httpClient, *plcURL, *identifier) + if err != nil { + return err + } + + verifier, err := pkce.GenerateVerifier() + if err != nil { + return err + } + state, err := pkce.GenerateState() + if err != nil { + return err + } + key, err := atproto.GenerateDPoPKey() + if err != nil { + return err + } + + oauthClient := &atproto.OAuthClient{ + HTTP: httpClient, + Metadata: resolved.AuthServer, + ClientID: *clientID, + Key: key, + } + par, err := oauthClient.PushAuthorizationRequest(ctx, *redirectURI, *scope, state, pkce.ChallengeS256(verifier), *identifier) + if err != nil { + return err + } + + fmt.Println("Open this URL in your browser to authorize AT Protocol access:") + fmt.Println() + fmt.Printf(" %s\n\n", atproto.BuildAuthorizeURL(resolved.AuthServer, *clientID, par.RequestURI)) + fmt.Println("Waiting for authorization callback...") + + pollCtx, cancel := context.WithTimeout(ctx, *timeout) + defer cancel() + + code, err := gitea.PollRelay(pollCtx, httpClient, *relayURL, state, 2*time.Second) + if err != nil { + return err + } + + tok, err := oauthClient.ExchangeCode(pollCtx, code, *redirectURI, verifier, resolved.DID) + if err != nil { + return err + } + + sess := atproto.NewSession(resolved, *clientID, tok, key) + if err := atproto.SaveSessionFile(*outPath, sess); err != nil { + return err + } + savedTo, _ := atproto.ExpandPath(*outPath) + who := resolved.DID + if resolved.Handle != "" { + who = "@" + resolved.Handle + " (" + resolved.DID + ")" + } + fmt.Printf("Saved atproto session for %s to %s (0600), scope %q.\n", who, savedTo, sess.Scope) + return nil +} + +func runAtprotoToken(ctx context.Context, args []string) error { + fs := flag.NewFlagSet("atproto-token", flag.ContinueOnError) + sessionPath := fs.String("session", atproto.DefaultSessionPath, "Session JSON path (updated in place on refresh)") + forceRefresh := fs.Bool("refresh", false, "Refresh even if the access token is still valid") + asJSON := fs.Bool("json", false, "Print token info as JSON instead of just the access token") + if err := fs.Parse(args); err != nil { + return err + } + + sess, err := atproto.LoadSessionFile(*sessionPath) + if err != nil { + return err + } + + if *forceRefresh || sess.ExpiresWithin(time.Minute) { + if sess.RefreshToken == "" { + return fmt.Errorf("session has no refresh_token; run 'latha-auth atproto' again") + } + key, err := sess.DPoP() + if err != nil { + return err + } + httpClient := &http.Client{Timeout: 15 * time.Second} + meta, err := atproto.FetchAuthServerMetadata(ctx, httpClient, sess.Issuer) + if err != nil { + return err + } + oauthClient := &atproto.OAuthClient{ + HTTP: httpClient, + Metadata: meta, + ClientID: sess.ClientID, + Key: key, + } + tok, err := oauthClient.Refresh(ctx, sess.RefreshToken, sess.DID) + if err != nil { + return err + } + sess.ApplyToken(tok) + if err := atproto.SaveSessionFile(*sessionPath, sess); err != nil { + return err + } + } + + if *asJSON { + b, err := json.MarshalIndent(sess.Info(), "", " ") + if err != nil { + return err + } + fmt.Println(string(b)) + return nil + } + fmt.Println(sess.AccessToken) + return nil +} diff --git a/internal/atproto/atproto_test.go b/internal/atproto/atproto_test.go new file mode 100644 index 0000000..97bc551 --- /dev/null +++ b/internal/atproto/atproto_test.go @@ -0,0 +1,321 @@ +package atproto + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +const testDID = "did:plc:test123" + +// fakeAuthServer serves PDS + authorization-server metadata, PAR and +// token endpoints on one origin, like a standalone PDS. The first PAR +// attempt is answered with a use_dpop_nonce challenge. +func fakeAuthServer(t *testing.T) *httptest.Server { + t.Helper() + var parAttempts atomic.Int32 + var codeChallenge atomic.Value + + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/oauth-protected-resource", func(w http.ResponseWriter, r *http.Request) { + origin := "http://" + r.Host + _ = json.NewEncoder(w).Encode(ProtectedResourceMetadata{ + Resource: origin, + AuthorizationServers: []string{origin}, + }) + }) + mux.HandleFunc("/.well-known/oauth-authorization-server", func(w http.ResponseWriter, r *http.Request) { + origin := "http://" + r.Host + _ = json.NewEncoder(w).Encode(AuthServerMetadata{ + Issuer: origin, + AuthorizationEndpoint: origin + "/oauth/authorize", + TokenEndpoint: origin + "/oauth/token", + PushedAuthorizationRequestEndpoint: origin + "/oauth/par", + ScopesSupported: []string{"atproto", "transition:generic"}, + GrantTypesSupported: []string{"authorization_code", "refresh_token"}, + CodeChallengeMethodsSupported: []string{"S256"}, + TokenEndpointAuthMethodsSupported: []string{"none", "private_key_jwt"}, + DPoPSigningAlgValuesSupported: []string{"ES256"}, + RequirePushedAuthorizationRequests: true, + AuthorizationResponseIssParameterSupported: true, + }) + }) + mux.HandleFunc("/oauth/par", func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + if r.Header.Get("DPoP") == "" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_dpop_proof"}) + return + } + w.Header().Set("DPoP-Nonce", "nonce-1") + if parAttempts.Add(1) == 1 { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "use_dpop_nonce"}) + return + } + // Second attempt must carry the issued nonce in its DPoP proof. + parts := strings.Split(r.Header.Get("DPoP"), ".") + claimsJSON, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil || !strings.Contains(string(claimsJSON), `"nonce":"nonce-1"`) { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_dpop_proof", ErrorDescription: "missing nonce"}) + return + } + if r.Form.Get("client_id") == "" || r.Form.Get("code_challenge_method") != "S256" || + r.Form.Get("state") == "" || r.Form.Get("redirect_uri") == "" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_request"}) + return + } + codeChallenge.Store(r.Form.Get("code_challenge")) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(PARResponse{RequestURI: "urn:ietf:params:oauth:request_uri:req-1", ExpiresIn: 90}) + }) + mux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + proof := r.Header.Get("DPoP") + if proof == "" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_dpop_proof"}) + return + } + verifyProof(t, proof) + w.Header().Set("DPoP-Nonce", "nonce-2") + switch r.Form.Get("grant_type") { + case "authorization_code": + sum := sha256.Sum256([]byte(r.Form.Get("code_verifier"))) + want, _ := codeChallenge.Load().(string) + if base64.RawURLEncoding.EncodeToString(sum[:]) != want { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_grant", ErrorDescription: "PKCE mismatch"}) + return + } + _ = json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "access-1", TokenType: "DPoP", ExpiresIn: 3600, + RefreshToken: "refresh-1", Scope: "atproto transition:generic", Sub: testDID, + }) + case "refresh_token": + if r.Form.Get("refresh_token") != "refresh-1" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "invalid_grant"}) + return + } + _ = json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "access-2", TokenType: "DPoP", ExpiresIn: 3600, + RefreshToken: "refresh-2", Scope: "atproto transition:generic", Sub: testDID, + }) + default: + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(oauthError{Error: "unsupported_grant_type"}) + } + }) + + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + +func fakePLC(t *testing.T, pdsURL string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/"+testDID { + w.WriteHeader(http.StatusNotFound) + return + } + _ = json.NewEncoder(w).Encode(DIDDocument{ + ID: testDID, + AlsoKnownAs: []string{"at://alice.test"}, + Service: []DIDService{{ + ID: "#atproto_pds", + Type: "AtprotoPersonalDataServer", + ServiceEndpoint: pdsURL, + }}, + }) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestOAuthFlowResolvePARExchangeSaveRefresh(t *testing.T) { + pds := fakeAuthServer(t) + plc := fakePLC(t, pds.URL) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + resolved, err := ResolveAuthServer(ctx, pds.Client(), plc.URL, testDID) + if err != nil { + t.Fatalf("ResolveAuthServer: %v", err) + } + if resolved.DID != testDID || resolved.Handle != "alice.test" || + resolved.PDS != pds.URL || resolved.Issuer != pds.URL { + t.Fatalf("resolved = %+v", resolved) + } + + key, err := GenerateDPoPKey() + if err != nil { + t.Fatalf("GenerateDPoPKey: %v", err) + } + client := &OAuthClient{ + HTTP: pds.Client(), + Metadata: resolved.AuthServer, + ClientID: "https://deploy.site.latha.org/oauth/atproto-client-metadata.json", + Key: key, + } + + verifier := "test-verifier-abcdefghijklmnopqrstuvwxyz-0123456789" + sum := sha256.Sum256([]byte(verifier)) + challenge := base64.RawURLEncoding.EncodeToString(sum[:]) + + par, err := client.PushAuthorizationRequest(ctx, + "https://deploy.site.latha.org/oauth/callback", DefaultScope, + "state-1", challenge, testDID) + if err != nil { + t.Fatalf("PushAuthorizationRequest: %v", err) + } + if par.RequestURI == "" { + t.Fatal("empty request_uri") + } + if client.Nonce != "nonce-1" { + t.Fatalf("client nonce = %q, want nonce-1 (captured from PAR response)", client.Nonce) + } + + authURL := BuildAuthorizeURL(resolved.AuthServer, client.ClientID, par.RequestURI) + if !strings.HasPrefix(authURL, pds.URL+"/oauth/authorize?") || + !strings.Contains(authURL, "request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3Areq-1") || + !strings.Contains(authURL, "client_id=https%3A%2F%2Fdeploy.site.latha.org") { + t.Fatalf("authorize URL = %s", authURL) + } + + tok, err := client.ExchangeCode(ctx, "code-1", "https://deploy.site.latha.org/oauth/callback", verifier, testDID) + if err != nil { + t.Fatalf("ExchangeCode: %v", err) + } + if tok.AccessToken != "access-1" || tok.Sub != testDID { + t.Fatalf("tok = %+v", tok) + } + + sess := NewSession(resolved, client.ClientID, tok, key) + outPath := filepath.Join(t.TempDir(), "nested", "atproto-session.json") + if err := SaveSessionFile(outPath, sess); err != nil { + t.Fatalf("SaveSessionFile: %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()) + } + + loaded, err := LoadSessionFile(outPath) + if err != nil { + t.Fatalf("LoadSessionFile: %v", err) + } + if loaded.ExpiresWithin(time.Minute) { + t.Fatal("fresh session must not be near expiry") + } + loadedKey, err := loaded.DPoP() + if err != nil { + t.Fatalf("loaded DPoP key: %v", err) + } + if loadedKey.Thumbprint() != key.Thumbprint() { + t.Fatal("DPoP key changed across save/load") + } + + refreshClient := &OAuthClient{ + HTTP: pds.Client(), + Metadata: resolved.AuthServer, + ClientID: loaded.ClientID, + Key: loadedKey, + } + tok2, err := refreshClient.Refresh(ctx, loaded.RefreshToken, loaded.DID) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + loaded.ApplyToken(tok2) + if loaded.AccessToken != "access-2" || loaded.RefreshToken != "refresh-2" { + t.Fatalf("after refresh: %+v", loaded) + } +} + +func TestExchangeCodeRejectsWrongAccount(t *testing.T) { + pds := fakeAuthServer(t) + ctx := context.Background() + + meta, err := FetchAuthServerMetadata(ctx, pds.Client(), pds.URL) + if err != nil { + t.Fatalf("FetchAuthServerMetadata: %v", err) + } + key, _ := GenerateDPoPKey() + client := &OAuthClient{HTTP: pds.Client(), Metadata: meta, ClientID: "https://example.com/meta.json", Key: key} + + verifier := "test-verifier-abcdefghijklmnopqrstuvwxyz-0123456789" + sum := sha256.Sum256([]byte(verifier)) + if _, err := client.PushAuthorizationRequest(ctx, "https://example.com/cb", DefaultScope, "s", base64.RawURLEncoding.EncodeToString(sum[:]), ""); err != nil { + t.Fatalf("PAR: %v", err) + } + _, err = client.ExchangeCode(ctx, "code-1", "https://example.com/cb", verifier, "did:plc:someoneelse") + if err == nil || !strings.Contains(err.Error(), "expected account") { + t.Fatalf("ExchangeCode err = %v, want sub mismatch error", err) + } +} + +func TestFetchAuthServerMetadataRejectsIssuerMismatch(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"issuer": "https://evil.example"}) + })) + defer srv.Close() + + _, err := FetchAuthServerMetadata(context.Background(), srv.Client(), srv.URL) + if err == nil || !strings.Contains(err.Error(), "does not match") { + t.Fatalf("err = %v, want issuer mismatch", err) + } +} + +func TestResolveHandleWellKnown(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/.well-known/atproto-did" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write([]byte(testDID + "\n")) + })) + defer srv.Close() + + did, err := resolveHandleWellKnown(context.Background(), srv.Client(), srv.URL) + if err != nil { + t.Fatalf("resolveHandleWellKnown: %v", err) + } + if did != testDID { + t.Fatalf("did = %q, want %q", did, testDID) + } +} + +func TestBuildClientMetadataValidation(t *testing.T) { + meta := BuildClientMetadata(DefaultClientID, "https://deploy.site.latha.org/oauth/callback", DefaultScope) + if err := meta.ValidateFor("https://deploy.site.latha.org/oauth/callback", DefaultScope); err != nil { + t.Fatalf("ValidateFor(match): %v", err) + } + if err := meta.ValidateFor("https://other.example/cb", DefaultScope); err == nil { + t.Fatal("ValidateFor must reject undeclared redirect_uri") + } + if err := meta.ValidateFor("https://deploy.site.latha.org/oauth/callback", "atproto transition:email"); err == nil { + t.Fatal("ValidateFor must reject scope not declared in metadata") + } +} diff --git a/internal/atproto/discover.go b/internal/atproto/discover.go new file mode 100644 index 0000000..7a17981 --- /dev/null +++ b/internal/atproto/discover.go @@ -0,0 +1,154 @@ +package atproto + +import ( + "context" + "fmt" + "net/http" + "net/url" + "slices" + "strings" +) + +type ProtectedResourceMetadata struct { + Resource string `json:"resource"` + AuthorizationServers []string `json:"authorization_servers"` +} + +type AuthServerMetadata struct { + Issuer string `json:"issuer"` + AuthorizationEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + PushedAuthorizationRequestEndpoint string `json:"pushed_authorization_request_endpoint"` + RevocationEndpoint string `json:"revocation_endpoint,omitempty"` + ScopesSupported []string `json:"scopes_supported"` + GrantTypesSupported []string `json:"grant_types_supported"` + CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"` + TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"` + DPoPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported"` + RequirePushedAuthorizationRequests bool `json:"require_pushed_authorization_requests"` + AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported"` +} + +// ResolvedIdentity is an account plus the authorization server that its +// own DID document (via its PDS) points at. The issuer is therefore +// bound to the session before any browser interaction happens. +type ResolvedIdentity struct { + DID string + Handle string + PDS string + Issuer string + AuthServer *AuthServerMetadata +} + +func checkHTTPSOrigin(raw, what string) error { + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("parse %s %q: %w", what, raw, err) + } + host := u.Hostname() + if u.Scheme == "http" && (host == "localhost" || host == "127.0.0.1" || host == "::1") { + return nil + } + if u.Scheme != "https" { + return fmt.Errorf("%s %q must use https", what, raw) + } + return nil +} + +func FetchProtectedResource(ctx context.Context, client *http.Client, pdsURL string) (*ProtectedResourceMetadata, error) { + client = httpClientOrDefault(client) + if err := checkHTTPSOrigin(pdsURL, "PDS URL"); err != nil { + return nil, err + } + var out ProtectedResourceMetadata + endpoint := strings.TrimRight(pdsURL, "/") + "/.well-known/oauth-protected-resource" + if err := getJSON(ctx, client, endpoint, &out); err != nil { + return nil, err + } + if len(out.AuthorizationServers) == 0 { + return nil, fmt.Errorf("protected resource metadata at %s lists no authorization_servers", endpoint) + } + issuer := strings.TrimRight(out.AuthorizationServers[0], "/") + if err := checkHTTPSOrigin(issuer, "authorization server"); err != nil { + return nil, err + } + out.AuthorizationServers[0] = issuer + return &out, nil +} + +func (m *AuthServerMetadata) validate(wantIssuer string) error { + if m.Issuer != wantIssuer { + return fmt.Errorf("authorization server issuer %q does not match %q", m.Issuer, wantIssuer) + } + if m.AuthorizationEndpoint == "" || m.TokenEndpoint == "" { + return fmt.Errorf("authorization server metadata missing authorization/token endpoint") + } + if !m.RequirePushedAuthorizationRequests || m.PushedAuthorizationRequestEndpoint == "" { + return fmt.Errorf("authorization server does not require PAR (atproto OAuth profile requires it)") + } + if !slices.Contains(m.CodeChallengeMethodsSupported, "S256") { + return fmt.Errorf("authorization server does not support PKCE S256") + } + if !slices.Contains(m.DPoPSigningAlgValuesSupported, "ES256") { + return fmt.Errorf("authorization server does not support DPoP ES256") + } + if !slices.Contains(m.ScopesSupported, "atproto") { + return fmt.Errorf("authorization server does not support the atproto scope") + } + if !slices.Contains(m.GrantTypesSupported, "authorization_code") || + !slices.Contains(m.GrantTypesSupported, "refresh_token") { + return fmt.Errorf("authorization server must support authorization_code and refresh_token grants") + } + if !slices.Contains(m.TokenEndpointAuthMethodsSupported, "none") { + return fmt.Errorf("authorization server does not support public clients (token_endpoint_auth_method none)") + } + return nil +} + +func FetchAuthServerMetadata(ctx context.Context, client *http.Client, issuer string) (*AuthServerMetadata, error) { + client = httpClientOrDefault(client) + issuer = strings.TrimRight(issuer, "/") + if err := checkHTTPSOrigin(issuer, "authorization server"); err != nil { + return nil, err + } + var out AuthServerMetadata + endpoint := issuer + "/.well-known/oauth-authorization-server" + if err := getJSON(ctx, client, endpoint, &out); err != nil { + return nil, err + } + out.Issuer = strings.TrimRight(out.Issuer, "/") + if err := out.validate(issuer); err != nil { + return nil, err + } + return &out, nil +} + +// ResolveAuthServer walks identifier -> DID document -> PDS -> +// protected-resource metadata -> authorization server metadata. +func ResolveAuthServer(ctx context.Context, client *http.Client, plcURL, identifier string) (*ResolvedIdentity, error) { + client = httpClientOrDefault(client) + did, handle, doc, err := ResolveIdentifier(ctx, client, plcURL, identifier) + if err != nil { + return nil, err + } + pds, ok := doc.PDSEndpoint() + if !ok { + return nil, fmt.Errorf("DID document for %s has no #atproto_pds service", did) + } + pr, err := FetchProtectedResource(ctx, client, pds) + if err != nil { + return nil, err + } + issuer := pr.AuthorizationServers[0] + meta, err := FetchAuthServerMetadata(ctx, client, issuer) + if err != nil { + return nil, err + } + return &ResolvedIdentity{ + DID: did, + Handle: handle, + PDS: pds, + Issuer: issuer, + AuthServer: meta, + }, nil +} diff --git a/internal/atproto/dpop.go b/internal/atproto/dpop.go new file mode 100644 index 0000000..37b01ed --- /dev/null +++ b/internal/atproto/dpop.go @@ -0,0 +1,163 @@ +package atproto + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "math/big" + "net/url" + "strings" + "time" +) + +// JWK is an EC P-256 key in JSON Web Key form. D is only set for the +// private key stored in the session file; the DPoP proof header carries +// the public subset (kty/crv/x/y). +type JWK struct { + Kty string `json:"kty"` + Crv string `json:"crv"` + X string `json:"x"` + Y string `json:"y"` + D string `json:"d,omitempty"` + Kid string `json:"kid,omitempty"` +} + +// DPoPKey is the per-session ES256 key all tokens in a session are bound +// to (RFC 9449). It must be persisted with the tokens: without it the +// access token cannot be used. +type DPoPKey struct { + priv *ecdsa.PrivateKey + pub JWK +} + +func pad32(b []byte) []byte { + out := make([]byte, 32) + copy(out[32-len(b):], b) + return out +} + +func publicJWK(pub *ecdsa.PublicKey) JWK { + return JWK{ + Kty: "EC", + Crv: "P-256", + X: base64.RawURLEncoding.EncodeToString(pad32(pub.X.Bytes())), + Y: base64.RawURLEncoding.EncodeToString(pad32(pub.Y.Bytes())), + } +} + +// Thumbprint returns the RFC 7638 JWK thumbprint of the public key, +// which servers use as the DPoP key binding (jkt) for the session. +func (k *DPoPKey) Thumbprint() string { + canonical := fmt.Sprintf(`{"crv":%q,"kty":%q,"x":%q,"y":%q}`, k.pub.Crv, k.pub.Kty, k.pub.X, k.pub.Y) + sum := sha256.Sum256([]byte(canonical)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// PrivateJWK returns the full key (including the private scalar) for +// storage in the 0600 session file. +func (k *DPoPKey) PrivateJWK() JWK { + jwk := k.pub + jwk.D = base64.RawURLEncoding.EncodeToString(pad32(k.priv.D.Bytes())) + jwk.Kid = k.Thumbprint() + return jwk +} + +func GenerateDPoPKey() (*DPoPKey, error) { + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, fmt.Errorf("generate DPoP key: %w", err) + } + return &DPoPKey{priv: priv, pub: publicJWK(&priv.PublicKey)}, nil +} + +func ParseDPoPKey(jwk JWK) (*DPoPKey, error) { + if jwk.Kty != "EC" || jwk.Crv != "P-256" { + return nil, fmt.Errorf("unsupported DPoP key type %q/%q", jwk.Kty, jwk.Crv) + } + x, err := base64.RawURLEncoding.DecodeString(jwk.X) + if err != nil { + return nil, fmt.Errorf("decode DPoP key x: %w", err) + } + y, err := base64.RawURLEncoding.DecodeString(jwk.Y) + if err != nil { + return nil, fmt.Errorf("decode DPoP key y: %w", err) + } + d, err := base64.RawURLEncoding.DecodeString(jwk.D) + if err != nil { + return nil, fmt.Errorf("decode DPoP key d: %w", err) + } + priv := &ecdsa.PrivateKey{ + PublicKey: ecdsa.PublicKey{ + Curve: elliptic.P256(), + X: new(big.Int).SetBytes(x), + Y: new(big.Int).SetBytes(y), + }, + D: new(big.Int).SetBytes(d), + } + if !elliptic.P256().IsOnCurve(priv.X, priv.Y) { + return nil, fmt.Errorf("DPoP public key is not on P-256") + } + pub := jwk + pub.D = "" + pub.Kid = "" + return &DPoPKey{priv: priv, pub: pub}, nil +} + +// Proof builds a signed DPoP JWT for one HTTP request. A fresh proof is +// required per request. accessToken, when non-empty, adds the ath claim +// (required when presenting an access token to a resource server). +func (k *DPoPKey) Proof(method, rawURL, nonce, accessToken string) (string, error) { + u, err := url.Parse(rawURL) + if err != nil { + return "", fmt.Errorf("parse DPoP target URL: %w", err) + } + u.RawQuery = "" + u.Fragment = "" + + jti := make([]byte, 16) + if _, err := rand.Read(jti); err != nil { + return "", fmt.Errorf("generate DPoP jti: %w", err) + } + + header := map[string]any{ + "typ": "dpop+jwt", + "alg": "ES256", + "jwk": k.pub, + } + claims := map[string]any{ + "jti": base64.RawURLEncoding.EncodeToString(jti), + "htm": strings.ToUpper(method), + "htu": u.String(), + "iat": time.Now().Unix(), + } + if nonce != "" { + claims["nonce"] = nonce + } + if accessToken != "" { + sum := sha256.Sum256([]byte(accessToken)) + claims["ath"] = base64.RawURLEncoding.EncodeToString(sum[:]) + } + + headerJSON, err := json.Marshal(header) + if err != nil { + return "", err + } + claimsJSON, err := json.Marshal(claims) + if err != nil { + return "", err + } + signingInput := base64.RawURLEncoding.EncodeToString(headerJSON) + "." + + base64.RawURLEncoding.EncodeToString(claimsJSON) + + digest := sha256.Sum256([]byte(signingInput)) + r, s, err := ecdsa.Sign(rand.Reader, k.priv, digest[:]) + if err != nil { + return "", fmt.Errorf("sign DPoP proof: %w", err) + } + sig := append(pad32(r.Bytes()), pad32(s.Bytes())...) + return signingInput + "." + base64.RawURLEncoding.EncodeToString(sig), nil +} diff --git a/internal/atproto/dpop_test.go b/internal/atproto/dpop_test.go new file mode 100644 index 0000000..94056ff --- /dev/null +++ b/internal/atproto/dpop_test.go @@ -0,0 +1,118 @@ +package atproto + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "math/big" + "strings" + "testing" +) + +func verifyProof(t *testing.T, proof string) (header map[string]any, claims map[string]any) { + t.Helper() + parts := strings.Split(proof, ".") + if len(parts) != 3 { + t.Fatalf("proof has %d parts, want 3", len(parts)) + } + headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + t.Fatalf("decode header: %v", err) + } + claimsJSON, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + t.Fatalf("decode claims: %v", err) + } + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) + if err != nil { + t.Fatalf("decode signature: %v", err) + } + if err := json.Unmarshal(headerJSON, &header); err != nil { + t.Fatalf("unmarshal header: %v", err) + } + if err := json.Unmarshal(claimsJSON, &claims); err != nil { + t.Fatalf("unmarshal claims: %v", err) + } + + jwkRaw, err := json.Marshal(header["jwk"]) + if err != nil { + t.Fatalf("marshal jwk: %v", err) + } + var jwk JWK + if err := json.Unmarshal(jwkRaw, &jwk); err != nil { + t.Fatalf("unmarshal jwk: %v", err) + } + if jwk.D != "" { + t.Fatal("proof header jwk leaks the private key") + } + x, _ := base64.RawURLEncoding.DecodeString(jwk.X) + y, _ := base64.RawURLEncoding.DecodeString(jwk.Y) + pub := &ecdsa.PublicKey{ + Curve: elliptic.P256(), + X: new(big.Int).SetBytes(x), + Y: new(big.Int).SetBytes(y), + } + if len(sig) != 64 { + t.Fatalf("signature is %d bytes, want 64 (r||s)", len(sig)) + } + digest := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + r := new(big.Int).SetBytes(sig[:32]) + s := new(big.Int).SetBytes(sig[32:]) + if !ecdsa.Verify(pub, digest[:], r, s) { + t.Fatal("DPoP proof signature does not verify") + } + return header, claims +} + +func TestDPoPProofAndKeyRoundTrip(t *testing.T) { + key, err := GenerateDPoPKey() + if err != nil { + t.Fatalf("GenerateDPoPKey: %v", err) + } + + proof, err := key.Proof("post", "https://bsky.social/oauth/token?ignored=1#frag", "nonce-1", "access-1") + if err != nil { + t.Fatalf("Proof: %v", err) + } + header, claims := verifyProof(t, proof) + if header["typ"] != "dpop+jwt" || header["alg"] != "ES256" { + t.Fatalf("header = %v, want typ dpop+jwt alg ES256", header) + } + if claims["htm"] != "POST" { + t.Fatalf("htm = %v, want POST", claims["htm"]) + } + if claims["htu"] != "https://bsky.social/oauth/token" { + t.Fatalf("htu = %v, want query/fragment stripped", claims["htu"]) + } + if claims["nonce"] != "nonce-1" { + t.Fatalf("nonce = %v, want nonce-1", claims["nonce"]) + } + sum := sha256.Sum256([]byte("access-1")) + if claims["ath"] != base64.RawURLEncoding.EncodeToString(sum[:]) { + t.Fatalf("ath = %v, want sha256(access_token)", claims["ath"]) + } + if claims["jti"] == nil || claims["iat"] == nil { + t.Fatalf("claims missing jti/iat: %v", claims) + } + + parsed, err := ParseDPoPKey(key.PrivateJWK()) + if err != nil { + t.Fatalf("ParseDPoPKey: %v", err) + } + if parsed.Thumbprint() != key.Thumbprint() { + t.Fatal("thumbprint changed across key round-trip") + } + proof2, err := parsed.Proof("GET", "https://example.com/xrpc/test", "", "") + if err != nil { + t.Fatalf("Proof after round-trip: %v", err) + } + _, claims2 := verifyProof(t, proof2) + if _, ok := claims2["ath"]; ok { + t.Fatal("ath must be omitted without an access token") + } + if _, ok := claims2["nonce"]; ok { + t.Fatal("nonce must be omitted when empty") + } +} diff --git a/internal/atproto/identity.go b/internal/atproto/identity.go new file mode 100644 index 0000000..7ccc204 --- /dev/null +++ b/internal/atproto/identity.go @@ -0,0 +1,194 @@ +package atproto + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "strings" + "time" +) + +const DefaultPLCURL = "https://plc.directory" + +type DIDService struct { + ID string `json:"id"` + Type string `json:"type"` + ServiceEndpoint string `json:"serviceEndpoint"` +} + +type DIDDocument struct { + ID string `json:"id"` + AlsoKnownAs []string `json:"alsoKnownAs"` + Service []DIDService `json:"service"` +} + +// PDSEndpoint returns the account's PDS URL from the DID document. +func (d *DIDDocument) PDSEndpoint() (string, bool) { + for _, svc := range d.Service { + if strings.HasSuffix(svc.ID, "#atproto_pds") && svc.Type == "AtprotoPersonalDataServer" { + return strings.TrimRight(svc.ServiceEndpoint, "/"), svc.ServiceEndpoint != "" + } + } + return "", false +} + +// Handle returns the first at:// alias claimed by the DID document. +func (d *DIDDocument) Handle() (string, bool) { + for _, aka := range d.AlsoKnownAs { + if h, ok := strings.CutPrefix(aka, "at://"); ok && h != "" { + return h, true + } + } + return "", false +} + +func httpClientOrDefault(client *http.Client) *http.Client { + if client == nil { + return &http.Client{Timeout: 15 * time.Second} + } + return client +} + +func getJSON(ctx context.Context, client *http.Client, endpoint string, out any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return err + } + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("GET %s failed (%d): %s", endpoint, resp.StatusCode, strings.TrimSpace(string(body))) + } + if err := json.Unmarshal(body, out); err != nil { + return fmt.Errorf("decode %s: %w", endpoint, err) + } + return nil +} + +// FetchDIDDocument resolves a did:plc (via plcURL) or did:web DID. +func FetchDIDDocument(ctx context.Context, client *http.Client, plcURL, did string) (*DIDDocument, error) { + client = httpClientOrDefault(client) + var endpoint string + switch { + case strings.HasPrefix(did, "did:plc:"): + if plcURL == "" { + plcURL = DefaultPLCURL + } + endpoint = strings.TrimRight(plcURL, "/") + "/" + did + case strings.HasPrefix(did, "did:web:"): + rest := strings.TrimPrefix(did, "did:web:") + parts := strings.Split(rest, ":") + host := parts[0] + if len(parts) == 1 { + endpoint = "https://" + host + "/.well-known/did.json" + } else { + endpoint = "https://" + host + "/" + strings.Join(parts[1:], "/") + "/did.json" + } + default: + return nil, fmt.Errorf("unsupported DID method in %q (want did:plc or did:web)", did) + } + + var doc DIDDocument + if err := getJSON(ctx, client, endpoint, &doc); err != nil { + return nil, err + } + if doc.ID != did { + return nil, fmt.Errorf("DID document id %q does not match requested %q", doc.ID, did) + } + return &doc, nil +} + +func resolveHandleDNS(ctx context.Context, handle string) (string, error) { + records, err := net.DefaultResolver.LookupTXT(ctx, "_atproto."+handle) + if err != nil { + return "", err + } + for _, rec := range records { + if did, ok := strings.CutPrefix(rec, "did="); ok && strings.HasPrefix(did, "did:") { + return did, nil + } + } + return "", fmt.Errorf("no did= TXT record at _atproto.%s", handle) +} + +func resolveHandleWellKnown(ctx context.Context, client *http.Client, baseURL string) (string, error) { + endpoint := strings.TrimRight(baseURL, "/") + "/.well-known/atproto-did" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return "", err + } + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return "", err + } + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("GET %s failed (%d)", endpoint, resp.StatusCode) + } + did := strings.TrimSpace(strings.SplitN(string(body), "\n", 2)[0]) + if !strings.HasPrefix(did, "did:") { + return "", fmt.Errorf("%s did not return a DID", endpoint) + } + return did, nil +} + +// ResolveHandle resolves a handle to its DID, trying DNS TXT first and +// then the HTTPS well-known endpoint (per the atproto Handle spec). +func ResolveHandle(ctx context.Context, client *http.Client, handle string) (string, error) { + client = httpClientOrDefault(client) + handle = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(handle, "@"))) + if handle == "" || !strings.Contains(handle, ".") { + return "", fmt.Errorf("invalid handle %q", handle) + } + if did, err := resolveHandleDNS(ctx, handle); err == nil { + return did, nil + } + return resolveHandleWellKnown(ctx, client, "https://"+handle) +} + +// ResolveIdentifier resolves a user-supplied handle or DID to a DID +// document. For handles it bidirectionally verifies that the DID +// document claims the handle, as the OAuth spec mandates. +func ResolveIdentifier(ctx context.Context, client *http.Client, plcURL, identifier string) (did, handle string, doc *DIDDocument, err error) { + client = httpClientOrDefault(client) + identifier = strings.TrimSpace(identifier) + + if strings.HasPrefix(identifier, "did:") { + doc, err := FetchDIDDocument(ctx, client, plcURL, identifier) + if err != nil { + return "", "", nil, err + } + handle, _ = doc.Handle() + return identifier, handle, doc, nil + } + + handle = strings.ToLower(strings.TrimPrefix(identifier, "@")) + did, err = ResolveHandle(ctx, client, handle) + if err != nil { + return "", "", nil, fmt.Errorf("resolve handle %q: %w", handle, err) + } + doc, err = FetchDIDDocument(ctx, client, plcURL, did) + if err != nil { + return "", "", nil, err + } + claimed, ok := doc.Handle() + if !ok || !strings.EqualFold(claimed, handle) { + return "", "", nil, fmt.Errorf("DID document for %s does not claim handle %q", did, handle) + } + return did, handle, doc, nil +} diff --git a/internal/atproto/oauth.go b/internal/atproto/oauth.go new file mode 100644 index 0000000..4dea613 --- /dev/null +++ b/internal/atproto/oauth.go @@ -0,0 +1,251 @@ +package atproto + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strings" +) + +const ( + // DefaultClientID is where the latha-auth client metadata JSON is + // expected to be hosted. Host the output of + // `latha-auth atproto --print-client-metadata` at this URL (or pass + // --client-id / LATHA_ATPROTO_CLIENT_ID). + DefaultClientID = "https://deploy.site.latha.org/oauth/atproto-client-metadata.json" + // DefaultScope covers full repo writes and blob uploads (the old + // app-password capability level), which publishing tiles needs. + DefaultScope = "atproto transition:generic" +) + +// ClientMetadata is the OAuth Client ID Metadata Document. latha-auth +// is a public client: no client secret, no assertion key. +type ClientMetadata struct { + ClientID string `json:"client_id"` + ClientName string `json:"client_name,omitempty"` + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` + RedirectURIs []string `json:"redirect_uris"` + Scope string `json:"scope"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + DPoPBoundAccessTokens bool `json:"dpop_bound_access_tokens"` +} + +func BuildClientMetadata(clientID, redirectURI, scope string) ClientMetadata { + return ClientMetadata{ + ClientID: clientID, + ClientName: "latha-auth", + GrantTypes: []string{"authorization_code", "refresh_token"}, + ResponseTypes: []string{"code"}, + RedirectURIs: []string{redirectURI}, + Scope: scope, + TokenEndpointAuthMethod: "none", + DPoPBoundAccessTokens: true, + } +} + +// FetchClientMetadata preflights the hosted client metadata document so +// a missing/misconfigured one fails locally with a clear message +// instead of as an opaque PAR rejection by the authorization server. +func FetchClientMetadata(ctx context.Context, client *http.Client, clientID string) (*ClientMetadata, error) { + client = httpClientOrDefault(client) + var out ClientMetadata + if err := getJSON(ctx, client, clientID, &out); err != nil { + return nil, err + } + if out.ClientID != clientID { + return nil, fmt.Errorf("client metadata client_id %q does not match %q", out.ClientID, clientID) + } + return &out, nil +} + +func (m *ClientMetadata) ValidateFor(redirectURI, scope string) error { + if !slices.Contains(m.RedirectURIs, redirectURI) { + return fmt.Errorf("client metadata does not declare redirect_uri %q", redirectURI) + } + declared := strings.Fields(m.Scope) + for _, want := range strings.Fields(scope) { + if !slices.Contains(declared, want) { + return fmt.Errorf("client metadata scope %q does not include requested %q", m.Scope, want) + } + } + if !m.DPoPBoundAccessTokens { + return fmt.Errorf("client metadata must set dpop_bound_access_tokens: true") + } + return nil +} + +type TokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token,omitempty"` + Scope string `json:"scope,omitempty"` + Sub string `json:"sub,omitempty"` + Error string `json:"error,omitempty"` + ErrorDescription string `json:"error_description,omitempty"` +} + +type oauthError struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` +} + +// OAuthClient performs DPoP-bound requests against one authorization +// server. Nonce holds the latest server-issued DPoP nonce and is +// updated from every response. +type OAuthClient struct { + HTTP *http.Client + Metadata *AuthServerMetadata + ClientID string + Key *DPoPKey + Nonce string +} + +// postForm posts a form with a DPoP proof, retrying when the server +// demands a (fresh) DPoP nonce via a use_dpop_nonce error. +func (c *OAuthClient) postForm(ctx context.Context, endpoint string, form url.Values) (int, []byte, error) { + client := httpClientOrDefault(c.HTTP) + for attempt := 0; attempt < 3; attempt++ { + proof, err := c.Key.Proof(http.MethodPost, endpoint, c.Nonce, "") + if err != nil { + return 0, nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return 0, nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + req.Header.Set("DPoP", proof) + + resp, err := client.Do(req) + if err != nil { + return 0, nil, err + } + body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + if readErr != nil { + return 0, nil, readErr + } + if nonce := resp.Header.Get("DPoP-Nonce"); nonce != "" { + c.Nonce = nonce + } + + var oerr oauthError + _ = json.Unmarshal(body, &oerr) + if resp.StatusCode == http.StatusBadRequest && oerr.Error == "use_dpop_nonce" { + continue + } + return resp.StatusCode, body, nil + } + return 0, nil, fmt.Errorf("DPoP nonce negotiation with %s did not converge", endpoint) +} + +func errorFrom(status int, body []byte, what string) error { + var oerr oauthError + _ = json.Unmarshal(body, &oerr) + msg := oerr.ErrorDescription + if msg == "" { + msg = oerr.Error + } + if msg == "" { + msg = strings.TrimSpace(string(body)) + } + return fmt.Errorf("%s failed (%d): %s", what, status, msg) +} + +type PARResponse struct { + RequestURI string `json:"request_uri"` + ExpiresIn int `json:"expires_in"` +} + +// PushAuthorizationRequest performs PAR (RFC 9126), which the atproto +// OAuth profile requires for all clients. +func (c *OAuthClient) PushAuthorizationRequest(ctx context.Context, redirectURI, scope, state, codeChallenge, loginHint string) (*PARResponse, error) { + form := url.Values{} + form.Set("client_id", c.ClientID) + form.Set("response_type", "code") + form.Set("redirect_uri", redirectURI) + form.Set("scope", scope) + form.Set("state", state) + form.Set("code_challenge", codeChallenge) + form.Set("code_challenge_method", "S256") + if loginHint != "" { + form.Set("login_hint", loginHint) + } + + status, body, err := c.postForm(ctx, c.Metadata.PushedAuthorizationRequestEndpoint, form) + if err != nil { + return nil, err + } + var out PARResponse + if err := json.Unmarshal(body, &out); err != nil { + return nil, fmt.Errorf("decode PAR response (%d): %w", status, err) + } + if status < 200 || status >= 300 { + return nil, errorFrom(status, body, "pushed authorization request") + } + if out.RequestURI == "" { + return nil, fmt.Errorf("pushed authorization request returned empty request_uri") + } + return &out, nil +} + +func BuildAuthorizeURL(meta *AuthServerMetadata, clientID, requestURI string) string { + u, _ := url.Parse(meta.AuthorizationEndpoint) + q := u.Query() + q.Set("client_id", clientID) + q.Set("request_uri", requestURI) + u.RawQuery = q.Encode() + return u.String() +} + +func (c *OAuthClient) tokenRequest(ctx context.Context, form url.Values, expectedDID, what string) (*TokenResponse, error) { + form.Set("client_id", c.ClientID) + status, body, err := c.postForm(ctx, c.Metadata.TokenEndpoint, form) + if err != nil { + return nil, err + } + var tok TokenResponse + if err := json.Unmarshal(body, &tok); err != nil { + return nil, fmt.Errorf("decode token response (%d): %w", status, err) + } + if status < 200 || status >= 300 || tok.Error != "" { + return nil, errorFrom(status, body, what) + } + if tok.AccessToken == "" { + return nil, fmt.Errorf("%s returned empty access_token", what) + } + if !slices.Contains(strings.Fields(tok.Scope), "atproto") { + return nil, fmt.Errorf("%s granted scope %q without atproto", what, tok.Scope) + } + if expectedDID != "" && tok.Sub != expectedDID { + return nil, fmt.Errorf("%s authorized %q, expected account %q", what, tok.Sub, expectedDID) + } + return &tok, nil +} + +// ExchangeCode trades the authorization code for tokens, verifying the +// returned sub is the account the flow started from. +func (c *OAuthClient) ExchangeCode(ctx context.Context, code, redirectURI, codeVerifier, expectedDID string) (*TokenResponse, error) { + form := url.Values{} + form.Set("grant_type", "authorization_code") + form.Set("code", code) + form.Set("redirect_uri", redirectURI) + form.Set("code_verifier", codeVerifier) + return c.tokenRequest(ctx, form, expectedDID, "token exchange") +} + +// Refresh trades a refresh token for new tokens. Refresh tokens are +// single-use: the caller must persist the replacement immediately. +func (c *OAuthClient) Refresh(ctx context.Context, refreshToken, expectedDID string) (*TokenResponse, error) { + form := url.Values{} + form.Set("grant_type", "refresh_token") + form.Set("refresh_token", refreshToken) + return c.tokenRequest(ctx, form, expectedDID, "token refresh") +} diff --git a/internal/atproto/session.go b/internal/atproto/session.go new file mode 100644 index 0000000..545c89d --- /dev/null +++ b/internal/atproto/session.go @@ -0,0 +1,154 @@ +package atproto + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +const DefaultSessionPath = "~/.config/latha-auth/atproto-session.json" + +// Session is the persisted OAuth session. It contains the DPoP private +// key, so the file must stay 0600: anyone holding it holds the session. +type Session struct { + DID string `json:"did"` + Handle string `json:"handle,omitempty"` + PDS string `json:"pds"` + Issuer string `json:"issuer"` + ClientID string `json:"client_id"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + TokenType string `json:"token_type"` + Scope string `json:"scope"` + ObtainedAt string `json:"obtained_at"` + ExpiresAt string `json:"expires_at,omitempty"` + DPoPKey JWK `json:"dpop_key"` +} + +// TokenInfo is the non-secret-bearing view of a session for display to +// DPoP-aware consumers. It omits the refresh token and DPoP key. +type TokenInfo struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + DID string `json:"did"` + Handle string `json:"handle,omitempty"` + PDS string `json:"pds"` + Issuer string `json:"issuer"` + Scope string `json:"scope"` + ExpiresAt string `json:"expires_at,omitempty"` +} + +func NewSession(id *ResolvedIdentity, clientID string, tok *TokenResponse, key *DPoPKey) *Session { + s := &Session{ + DID: id.DID, + Handle: id.Handle, + PDS: id.PDS, + Issuer: id.Issuer, + ClientID: clientID, + DPoPKey: key.PrivateJWK(), + } + s.ApplyToken(tok) + return s +} + +// ApplyToken rotates the session's tokens after an exchange or refresh. +func (s *Session) ApplyToken(tok *TokenResponse) { + now := time.Now().UTC() + s.AccessToken = tok.AccessToken + if tok.RefreshToken != "" { + s.RefreshToken = tok.RefreshToken + } + if tok.TokenType != "" { + s.TokenType = tok.TokenType + } + if tok.Scope != "" { + s.Scope = tok.Scope + } + s.ObtainedAt = now.Format(time.RFC3339) + if tok.ExpiresIn > 0 { + s.ExpiresAt = now.Add(time.Duration(tok.ExpiresIn) * time.Second).Format(time.RFC3339) + } +} + +// DPoP reconstructs the session's DPoP signing key. +func (s *Session) DPoP() (*DPoPKey, error) { + return ParseDPoPKey(s.DPoPKey) +} + +// ExpiresWithin reports whether the access token is expired or will +// expire within d. An unparseable/absent expiry counts as expired. +func (s *Session) ExpiresWithin(d time.Duration) bool { + exp, err := time.Parse(time.RFC3339, s.ExpiresAt) + if err != nil { + return true + } + return time.Until(exp) <= d +} + +func (s *Session) Info() TokenInfo { + return TokenInfo{ + AccessToken: s.AccessToken, + TokenType: s.TokenType, + DID: s.DID, + Handle: s.Handle, + PDS: s.PDS, + Issuer: s.Issuer, + Scope: s.Scope, + ExpiresAt: s.ExpiresAt, + } +} + +func ExpandPath(p string) (string, error) { + if strings.HasPrefix(p, "~/") { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, p[2:]), nil + } + return p, nil +} + +func SaveSessionFile(path string, s *Session) error { + resolved, err := ExpandPath(path) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(resolved), 0o700); err != nil { + return fmt.Errorf("create config dir: %w", err) + } + data, err := json.MarshalIndent(s, "", " ") + if err != nil { + return err + } + data = append(data, '\n') + if err := os.WriteFile(resolved, data, 0o600); err != nil { + return fmt.Errorf("write session file: %w", err) + } + if err := os.Chmod(resolved, 0o600); err != nil { + return fmt.Errorf("chmod session file: %w", err) + } + return nil +} + +func LoadSessionFile(path string) (*Session, error) { + resolved, err := ExpandPath(path) + if err != nil { + return nil, err + } + data, err := os.ReadFile(resolved) + if err != nil { + return nil, fmt.Errorf("read session file: %w (run 'latha-auth atproto' first)", err) + } + var s Session + if err := json.Unmarshal(data, &s); err != nil { + return nil, fmt.Errorf("decode session file %s: %w", resolved, err) + } + if s.DID == "" || s.AccessToken == "" { + return nil, fmt.Errorf("session file %s is missing did/access_token", resolved) + } + return &s, nil +}