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: DefaultClientID, 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%2Fgit.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") } }