-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandlers_oauth_device.go
More file actions
180 lines (170 loc) · 6.45 KB
/
Copy pathhandlers_oauth_device.go
File metadata and controls
180 lines (170 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// === LOCKED FILE ===
// Status: STABLE — DO NOT MODIFY without owner approval.
// Owner: Aola Sahidin (Mr.Dev)
// Repo: https://github.com/flowork-os/flowork_Router
// Locked at: 2026-05-30
// Reason: Audit pass — HTTP handler.
// OAuth Device Code Flow (RFC 8628).
package main
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/flowork-os/flowork_Router/internal/store"
)
// oauthDeviceStartHandler — POST /api/oauth/:provider/device-code
func oauthDeviceStartHandler(w http.ResponseWriter, r *http.Request, provider string) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var body struct {
ClientID string `json:"clientId"`
Scope string `json:"scope"`
DeviceAuthURL string `json:"deviceAuthUrl"`
TokenURL string `json:"tokenUrl"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
tpl := oauthTemplates[provider]
deviceURL := firstNonEmptyStr(body.DeviceAuthURL, tpl.DeviceAuthURL)
tokenURL := firstNonEmptyStr(body.TokenURL, tpl.TokenURL)
clientID := firstNonEmptyStr(body.ClientID, "PLACEHOLDER_"+tpl.ClientIDEnv)
scope := firstNonEmptyStr(body.Scope, tpl.DefaultScope)
if deviceURL == "" {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": provider + " has no device_authorization endpoint — pass deviceAuthUrl"})
return
}
form := url.Values{}
form.Set("client_id", clientID)
if scope != "" {
form.Set("scope", scope)
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, deviceURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := providerProbeClient.Do(req)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": "device-code: " + err.Error()})
return
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
var dc struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
Interval int `json:"interval"`
ExpiresIn int `json:"expires_in"`
}
if json.Unmarshal(raw, &dc) != nil || dc.DeviceCode == "" {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": "device endpoint returned no device_code", "raw": truncateStr(string(raw), 200)})
return
}
if dc.Interval <= 0 {
dc.Interval = 5
}
d, _ := store.Open()
_ = store.UpsertOAuthToken(d, &store.OAuthTokenRecord{
Provider: provider + ":device-pending",
TokenType: "device-pending",
Extra: map[string]any{
"deviceCode": dc.DeviceCode, "tokenUrl": tokenURL, "clientId": clientID,
"interval": dc.Interval, "expiresAt": time.Now().Add(time.Duration(clampDeviceExpiresIn(dc.ExpiresIn)) * time.Second).Format(time.RFC3339),
},
})
writeJSON(w, http.StatusOK, map[string]any{
"userCode": dc.UserCode, "verificationUri": dc.VerificationURI,
"verificationUriComplete": dc.VerificationURIComplete, "interval": dc.Interval, "expiresIn": dc.ExpiresIn,
})
}
// oauthDevicePollHandler — POST /api/oauth/:provider/poll
func oauthDevicePollHandler(w http.ResponseWriter, r *http.Request, provider string) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
d, _ := store.Open()
pending, _ := store.GetOAuthToken(d, provider+":device-pending")
if pending == nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"status": "error", "error": "no device-code flow in progress"})
return
}
extra, _ := pending.Extra.(map[string]any)
deviceCode, _ := extra["deviceCode"].(string)
tokenURL, _ := extra["tokenUrl"].(string)
clientID, _ := extra["clientId"].(string)
if tokenURL == "" || deviceCode == "" {
writeJSON(w, http.StatusBadRequest, map[string]any{"status": "error", "error": "incomplete pending state"})
return
}
form := url.Values{}
form.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
form.Set("device_code", deviceCode)
form.Set("client_id", clientID)
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := providerProbeClient.Do(req)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"status": "error", "error": err.Error()})
return
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
var tok struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Error string `json:"error"`
}
_ = json.Unmarshal(raw, &tok)
if tok.AccessToken != "" {
_ = store.UpsertOAuthToken(d, &store.OAuthTokenRecord{
Provider: provider, AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken,
TokenType: firstNonEmptyStr(tok.TokenType, "Bearer"), Scope: tok.Scope,
})
_ = store.DeleteOAuthToken(d, provider+":device-pending")
writeJSON(w, http.StatusOK, map[string]any{"status": "complete", "provider": provider})
return
}
switch tok.Error {
case "authorization_pending", "":
writeJSON(w, http.StatusOK, map[string]any{"status": "pending"})
case "slow_down":
writeJSON(w, http.StatusOK, map[string]any{"status": "slow_down"})
default: // expired_token, access_denied, …
_ = store.DeleteOAuthToken(d, provider+":device-pending")
writeJSON(w, http.StatusOK, map[string]any{"status": "error", "error": tok.Error})
}
}
// clampDeviceExpiresIn bounds the IdP-supplied expires_in (seconds) to a sane
// range before it is multiplied by time.Second. Without a cap a hostile or
// buggy IdP response (e.g. expires_in = math.MaxInt64) overflows time.Duration
// and produces a negative/wrong expiry, breaking the device flow.
func clampDeviceExpiresIn(v int) int {
const min = 600 // 10 minutes — the device-flow floor we already used
const max = 24 * 60 * 60 // 24 hours — generous ceiling; real IdPs return <=900s
if v < min {
return min
}
if v > max {
return max
}
return v
}
func truncateStr(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}