From ce459f69b1e4ff6efc8e64ebd1ac2537fed4ead0 Mon Sep 17 00:00:00 2001 From: nandi <78769380+codegod100@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:36:15 +0000 Subject: [PATCH] feat: add /oauth/callback and /api/oauth/poll relay endpoints --- internal/server/oauth_relay.go | 113 ++++++++++++++++++++++++ internal/server/oauth_relay_test.go | 130 ++++++++++++++++++++++++++++ internal/server/server.go | 15 ++-- 3 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 internal/server/oauth_relay.go create mode 100644 internal/server/oauth_relay_test.go diff --git a/internal/server/oauth_relay.go b/internal/server/oauth_relay.go new file mode 100644 index 0000000..e46d9a5 --- /dev/null +++ b/internal/server/oauth_relay.go @@ -0,0 +1,113 @@ +package server + +import ( + "html" + "net/http" + "sync" + "time" +) + +const oauthRelayTTL = 5 * time.Minute + +type oauthRelayEntry struct { + code string + expiresAt time.Time +} + +type oauthRelayStore struct { + mu sync.Mutex + entries map[string]oauthRelayEntry + ttl time.Duration + now func() time.Time +} + +func newOAuthRelayStore() *oauthRelayStore { + return &oauthRelayStore{ + entries: make(map[string]oauthRelayEntry), + ttl: oauthRelayTTL, + now: time.Now, + } +} + +func (o *oauthRelayStore) Set(state, code string) { + o.mu.Lock() + defer o.mu.Unlock() + now := o.now() + o.pruneLocked(now) + o.entries[state] = oauthRelayEntry{ + code: code, + expiresAt: now.Add(o.ttl), + } +} + +func (o *oauthRelayStore) Take(state string) (string, bool) { + o.mu.Lock() + defer o.mu.Unlock() + now := o.now() + o.pruneLocked(now) + entry, ok := o.entries[state] + if !ok { + return "", false + } + delete(o.entries, state) + if now.After(entry.expiresAt) { + return "", false + } + return entry.code, true +} + +func (o *oauthRelayStore) pruneLocked(now time.Time) { + for k, v := range o.entries { + if now.After(v.expiresAt) { + delete(o.entries, k) + } + } +} + +func (s *Server) handleOAuthCallback(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if errParam := q.Get("error"); errParam != "" { + desc := q.Get("error_description") + if desc == "" { + desc = errParam + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`
` + html.EscapeString(desc) + `
`)) + return + } + + state := q.Get("state") + code := q.Get("code") + if state == "" || code == "" { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`Missing required code or state query parameter.
Authorized! You can close this tab.
`)) +} + +func (s *Server) handleOAuthPoll(w http.ResponseWriter, r *http.Request) { + state := r.URL.Query().Get("state") + if state == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "state is required"}) + return + } + + code, ok := s.oauth.Take(state) + if !ok { + writeJSON(w, http.StatusAccepted, map[string]string{"status": "pending"}) + return + } + + writeJSON(w, http.StatusOK, map[string]string{ + "status": "ready", + "code": code, + }) +} diff --git a/internal/server/oauth_relay_test.go b/internal/server/oauth_relay_test.go new file mode 100644 index 0000000..755bab8 --- /dev/null +++ b/internal/server/oauth_relay_test.go @@ -0,0 +1,130 @@ +package server + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" +) + +func newTestServer(t *testing.T) *Server { + t.Helper() + cfg := config.Config{ + GiteaURL: "https://git.site.latha.org", + } + st, err := store.New(filepath.Join(t.TempDir(), "state.json")) + if err != nil { + t.Fatalf("store.New: %v", err) + } + fg := &fakeGitea{} + fa := &fakeApplier{} + svc := deployer.NewService(cfg, st, fg, fa) + return New(cfg, st, svc, fa) +} + +func TestOAuthRelayFlow(t *testing.T) { + srv := newTestServer(t) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + // 1. Missing state on poll -> 400 + resp, err := http.Get(ts.URL + "/api/oauth/poll") + if err != nil { + t.Fatalf("poll missing state: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for missing state, got %d", resp.StatusCode) + } + + // 2. Poll before callback -> 202 pending + resp, err = http.Get(ts.URL + "/api/oauth/poll?state=state-123") + if err != nil { + t.Fatalf("poll pending: %v", err) + } + var pollOut map[string]string + _ = json.NewDecoder(resp.Body).Decode(&pollOut) + resp.Body.Close() + if resp.StatusCode != http.StatusAccepted || pollOut["status"] != "pending" { + t.Fatalf("expected 202 pending, got %d %v", resp.StatusCode, pollOut) + } + + // 3. Callback missing params -> 400 + resp, err = http.Get(ts.URL + "/oauth/callback?state=state-123") + if err != nil { + t.Fatalf("callback missing code: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for missing code, got %d", resp.StatusCode) + } + + // 4. Callback with error -> 400 + resp, err = http.Get(ts.URL + "/oauth/callback?error=access_denied&state=state-123") + if err != nil { + t.Fatalf("callback error: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for oauth error, got %d", resp.StatusCode) + } + + // 5. Valid callback -> 200 HTML + resp, err = http.Get(ts.URL + "/oauth/callback?state=state-123&code=auth-code-xyz") + if err != nil { + t.Fatalf("callback valid: %v", err) + } + bodyBytes, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 for callback, got %d", resp.StatusCode) + } + if !strings.Contains(string(bodyBytes), "Authorized! You can close this tab.") { + t.Fatalf("unexpected callback HTML: %s", string(bodyBytes)) + } + + // 6. Poll after callback -> 200 ready with code + resp, err = http.Get(ts.URL + "/api/oauth/poll?state=state-123") + if err != nil { + t.Fatalf("poll ready: %v", err) + } + pollOut = map[string]string{} + _ = json.NewDecoder(resp.Body).Decode(&pollOut) + resp.Body.Close() + if resp.StatusCode != http.StatusOK || pollOut["status"] != "ready" || pollOut["code"] != "auth-code-xyz" { + t.Fatalf("expected 200 ready with code, got %d %v", resp.StatusCode, pollOut) + } + + // 7. Single-use consumption: second poll -> 202 pending + resp, err = http.Get(ts.URL + "/api/oauth/poll?state=state-123") + if err != nil { + t.Fatalf("poll second time: %v", err) + } + pollOut = map[string]string{} + _ = json.NewDecoder(resp.Body).Decode(&pollOut) + resp.Body.Close() + if resp.StatusCode != http.StatusAccepted || pollOut["status"] != "pending" { + t.Fatalf("expected 202 pending after consumption, got %d %v", resp.StatusCode, pollOut) + } +} + +func TestOAuthRelayTTLExpiration(t *testing.T) { + now := time.Date(2026, 11, 17, 21, 0, 0, 0, time.UTC) + st := newOAuthRelayStore() + st.now = func() time.Time { return now } + + st.Set("s1", "c1") + now = now.Add(6 * time.Minute) + + if code, ok := st.Take("s1"); ok || code != "" { + t.Fatalf("expected expired entry to be rejected, got (%q, %v)", code, ok) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 99e2035..724b6a4 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -23,11 +23,12 @@ import ( var webFS embed.FS type Server struct { - cfg config.Config - store *store.Store - svc *deployer.Service - k8s k8s.Applier - mux *http.ServeMux + cfg config.Config + store *store.Store + svc *deployer.Service + k8s k8s.Applier + oauth *oauthRelayStore + mux *http.ServeMux } func New(cfg config.Config, st *store.Store, svc *deployer.Service, ka k8s.Applier) *Server { @@ -36,6 +37,7 @@ func New(cfg config.Config, st *store.Store, svc *deployer.Service, ka k8s.Appli store: st, svc: svc, k8s: ka, + oauth: newOAuthRelayStore(), mux: http.NewServeMux(), } s.routes() @@ -52,6 +54,9 @@ func (s *Server) routes() { s.mux.HandleFunc("GET /readyz", s.handleReadyz) s.mux.HandleFunc("GET /metrics", s.handleMetrics) + s.mux.HandleFunc("GET /oauth/callback", s.handleOAuthCallback) + s.mux.HandleFunc("GET /api/oauth/poll", s.handleOAuthPoll) + s.mux.HandleFunc("POST /webhook/gitea", s.handleGiteaWebhook) s.mux.HandleFunc("GET /api/apps", s.handleListApps)