1package oauth
2
3import (
4 "errors"
5 "fmt"
6 "log/slog"
7 "net/http"
8 "time"
9
10 comatproto "github.com/bluesky-social/indigo/api/atproto"
11 "github.com/bluesky-social/indigo/atproto/auth/oauth"
12 atpclient "github.com/bluesky-social/indigo/atproto/client"
13 atcrypto "github.com/bluesky-social/indigo/atproto/crypto"
14 "github.com/bluesky-social/indigo/atproto/syntax"
15 xrpc "github.com/bluesky-social/indigo/xrpc"
16 "github.com/gorilla/sessions"
17 "github.com/posthog/posthog-go"
18 "tangled.org/core/appview/config"
19 "tangled.org/core/appview/db"
20 "tangled.org/core/idresolver"
21 "tangled.org/core/rbac"
22)
23
24type OAuth struct {
25 ClientApp *oauth.ClientApp
26 SessStore *sessions.CookieStore
27 Config *config.Config
28 JwksUri string
29 ClientName string
30 ClientUri string
31 Posthog posthog.Client
32 Db *db.DB
33 Enforcer *rbac.Enforcer
34 IdResolver *idresolver.Resolver
35 Logger *slog.Logger
36}
37
38func New(config *config.Config, ph posthog.Client, db *db.DB, enforcer *rbac.Enforcer, res *idresolver.Resolver, logger *slog.Logger) (*OAuth, error) {
39 var oauthConfig oauth.ClientConfig
40 var clientUri string
41 if config.Core.Dev {
42 clientUri = "http://127.0.0.1:3000"
43 callbackUri := clientUri + "/oauth/callback"
44 oauthConfig = oauth.NewLocalhostConfig(callbackUri, []string{"atproto", "transition:generic"})
45 } else {
46 clientUri = config.Core.AppviewHost
47 clientId := fmt.Sprintf("%s/oauth/client-metadata.json", clientUri)
48 callbackUri := clientUri + "/oauth/callback"
49 oauthConfig = oauth.NewPublicConfig(clientId, callbackUri, []string{"atproto", "transition:generic"})
50 }
51
52 // configure client secret
53 priv, err := atcrypto.ParsePrivateMultibase(config.OAuth.ClientSecret)
54 if err != nil {
55 return nil, err
56 }
57 if err := oauthConfig.SetClientSecret(priv, config.OAuth.ClientKid); err != nil {
58 return nil, err
59 }
60
61 jwksUri := clientUri + "/oauth/jwks.json"
62
63 authStore, err := NewRedisStore(&RedisStoreConfig{
64 RedisURL: config.Redis.ToURL(),
65 SessionExpiryDuration: time.Hour * 24 * 90,
66 SessionInactivityDuration: time.Hour * 24 * 14,
67 AuthRequestExpiryDuration: time.Minute * 30,
68 })
69 if err != nil {
70 return nil, err
71 }
72
73 sessStore := sessions.NewCookieStore([]byte(config.Core.CookieSecret))
74
75 clientApp := oauth.NewClientApp(&oauthConfig, authStore)
76 clientApp.Dir = res.Directory()
77 // allow non-public transports in dev mode
78 if config.Core.Dev {
79 clientApp.Resolver.Client.Transport = http.DefaultTransport
80 }
81
82 clientName := config.Core.AppviewName
83
84 logger.Info("oauth setup successfully", "IsConfidential", clientApp.Config.IsConfidential())
85 return &OAuth{
86 ClientApp: clientApp,
87 Config: config,
88 SessStore: sessStore,
89 JwksUri: jwksUri,
90 ClientName: clientName,
91 ClientUri: clientUri,
92 Posthog: ph,
93 Db: db,
94 Enforcer: enforcer,
95 IdResolver: res,
96 Logger: logger,
97 }, nil
98}
99
100func (o *OAuth) SaveSession(w http.ResponseWriter, r *http.Request, sessData *oauth.ClientSessionData) error {
101 // first we save the did in the user session
102 userSession, err := o.SessStore.Get(r, SessionName)
103 if err != nil {
104 return err
105 }
106
107 userSession.Values[SessionDid] = sessData.AccountDID.String()
108 userSession.Values[SessionPds] = sessData.HostURL
109 userSession.Values[SessionId] = sessData.SessionID
110 userSession.Values[SessionAuthenticated] = true
111 return userSession.Save(r, w)
112}
113
114func (o *OAuth) ResumeSession(r *http.Request) (*oauth.ClientSession, error) {
115 userSession, err := o.SessStore.Get(r, SessionName)
116 if err != nil {
117 return nil, fmt.Errorf("error getting user session: %w", err)
118 }
119 if userSession.IsNew {
120 return nil, fmt.Errorf("no session available for user")
121 }
122
123 d := userSession.Values[SessionDid].(string)
124 sessDid, err := syntax.ParseDID(d)
125 if err != nil {
126 return nil, fmt.Errorf("malformed DID in session cookie '%s': %w", d, err)
127 }
128
129 sessId := userSession.Values[SessionId].(string)
130
131 clientSess, err := o.ClientApp.ResumeSession(r.Context(), sessDid, sessId)
132 if err != nil {
133 return nil, fmt.Errorf("failed to resume session: %w", err)
134 }
135
136 return clientSess, nil
137}
138
139func (o *OAuth) DeleteSession(w http.ResponseWriter, r *http.Request) error {
140 userSession, err := o.SessStore.Get(r, SessionName)
141 if err != nil {
142 return fmt.Errorf("error getting user session: %w", err)
143 }
144 if userSession.IsNew {
145 return fmt.Errorf("no session available for user")
146 }
147
148 d := userSession.Values[SessionDid].(string)
149 sessDid, err := syntax.ParseDID(d)
150 if err != nil {
151 return fmt.Errorf("malformed DID in session cookie '%s': %w", d, err)
152 }
153
154 sessId := userSession.Values[SessionId].(string)
155
156 // delete the session
157 err1 := o.ClientApp.Logout(r.Context(), sessDid, sessId)
158
159 // remove the cookie
160 userSession.Options.MaxAge = -1
161 err2 := o.SessStore.Save(r, w, userSession)
162
163 return errors.Join(err1, err2)
164}
165
166type User struct {
167 Did string
168 Pds string
169}
170
171func (o *OAuth) GetUser(r *http.Request) *User {
172 sess, err := o.ResumeSession(r)
173 if err != nil {
174 return nil
175 }
176
177 return &User{
178 Did: sess.Data.AccountDID.String(),
179 Pds: sess.Data.HostURL,
180 }
181}
182
183func (o *OAuth) GetDid(r *http.Request) string {
184 if u := o.GetUser(r); u != nil {
185 return u.Did
186 }
187
188 return ""
189}
190
191func (o *OAuth) AuthorizedClient(r *http.Request) (*atpclient.APIClient, error) {
192 session, err := o.ResumeSession(r)
193 if err != nil {
194 return nil, fmt.Errorf("error getting session: %w", err)
195 }
196 return session.APIClient(), nil
197}
198
199// this is a higher level abstraction on ServerGetServiceAuth
200type ServiceClientOpts struct {
201 service string
202 exp int64
203 lxm string
204 dev bool
205}
206
207type ServiceClientOpt func(*ServiceClientOpts)
208
209func WithService(service string) ServiceClientOpt {
210 return func(s *ServiceClientOpts) {
211 s.service = service
212 }
213}
214
215// Specify the Duration in seconds for the expiry of this token
216//
217// The time of expiry is calculated as time.Now().Unix() + exp
218func WithExp(exp int64) ServiceClientOpt {
219 return func(s *ServiceClientOpts) {
220 s.exp = time.Now().Unix() + exp
221 }
222}
223
224func WithLxm(lxm string) ServiceClientOpt {
225 return func(s *ServiceClientOpts) {
226 s.lxm = lxm
227 }
228}
229
230func WithDev(dev bool) ServiceClientOpt {
231 return func(s *ServiceClientOpts) {
232 s.dev = dev
233 }
234}
235
236func (s *ServiceClientOpts) Audience() string {
237 return fmt.Sprintf("did:web:%s", s.service)
238}
239
240func (s *ServiceClientOpts) Host() string {
241 scheme := "https://"
242 if s.dev {
243 scheme = "http://"
244 }
245
246 return scheme + s.service
247}
248
249func (o *OAuth) ServiceClient(r *http.Request, os ...ServiceClientOpt) (*xrpc.Client, error) {
250 opts := ServiceClientOpts{}
251 for _, o := range os {
252 o(&opts)
253 }
254
255 client, err := o.AuthorizedClient(r)
256 if err != nil {
257 return nil, err
258 }
259
260 // force expiry to atleast 60 seconds in the future
261 sixty := time.Now().Unix() + 60
262 if opts.exp < sixty {
263 opts.exp = sixty
264 }
265
266 resp, err := comatproto.ServerGetServiceAuth(r.Context(), client, opts.Audience(), opts.exp, opts.lxm)
267 if err != nil {
268 return nil, err
269 }
270
271 return &xrpc.Client{
272 Auth: &xrpc.AuthInfo{
273 AccessJwt: resp.Token,
274 },
275 Host: opts.Host(),
276 Client: &http.Client{
277 Timeout: time.Second * 5,
278 },
279 }, nil
280}