forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
at master 7.4 kB view raw
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 timeout time.Duration 206} 207 208type ServiceClientOpt func(*ServiceClientOpts) 209 210func DefaultServiceClientOpts() ServiceClientOpts { 211 return ServiceClientOpts{ 212 timeout: time.Second * 5, 213 } 214} 215 216func WithService(service string) ServiceClientOpt { 217 return func(s *ServiceClientOpts) { 218 s.service = service 219 } 220} 221 222// Specify the Duration in seconds for the expiry of this token 223// 224// The time of expiry is calculated as time.Now().Unix() + exp 225func WithExp(exp int64) ServiceClientOpt { 226 return func(s *ServiceClientOpts) { 227 s.exp = time.Now().Unix() + exp 228 } 229} 230 231func WithLxm(lxm string) ServiceClientOpt { 232 return func(s *ServiceClientOpts) { 233 s.lxm = lxm 234 } 235} 236 237func WithDev(dev bool) ServiceClientOpt { 238 return func(s *ServiceClientOpts) { 239 s.dev = dev 240 } 241} 242 243func WithTimeout(timeout time.Duration) ServiceClientOpt { 244 return func(s *ServiceClientOpts) { 245 s.timeout = timeout 246 } 247} 248 249func (s *ServiceClientOpts) Audience() string { 250 return fmt.Sprintf("did:web:%s", s.service) 251} 252 253func (s *ServiceClientOpts) Host() string { 254 scheme := "https://" 255 if s.dev { 256 scheme = "http://" 257 } 258 259 return scheme + s.service 260} 261 262func (o *OAuth) ServiceClient(r *http.Request, os ...ServiceClientOpt) (*xrpc.Client, error) { 263 opts := DefaultServiceClientOpts() 264 for _, o := range os { 265 o(&opts) 266 } 267 268 client, err := o.AuthorizedClient(r) 269 if err != nil { 270 return nil, err 271 } 272 273 // force expiry to atleast 60 seconds in the future 274 sixty := time.Now().Unix() + 60 275 if opts.exp < sixty { 276 opts.exp = sixty 277 } 278 279 resp, err := comatproto.ServerGetServiceAuth(r.Context(), client, opts.Audience(), opts.exp, opts.lxm) 280 if err != nil { 281 return nil, err 282 } 283 284 return &xrpc.Client{ 285 Auth: &xrpc.AuthInfo{ 286 AccessJwt: resp.Token, 287 }, 288 Host: opts.Host(), 289 Client: &http.Client{ 290 Timeout: opts.timeout, 291 }, 292 }, nil 293}