Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,9 @@ it does for the web:
Apps sign in with `AuthService/Login` (and `VerifyMFA` for two-factor
accounts) and send the session token as `Authorization: Bearer <token>`.
With single sign-on they list the providers with `ListSSOProviders`, open
`/login/sso/<provider>?app=<S256 challenge>` in the system browser, which
comes back to `io.github.ssenerg.gochat:/sso?code=` (or `?error=`), and
`/login/sso/<provider>?app=<S256 challenge>` in the system browser, which,
once the person confirms on the server's page, comes back to
`io.github.ssenerg.gochat:/sso?code=` (or straight to `?error=`), and
trade the code and their PKCE verifier for a session with `RedeemSSO`.
Signed in, they link another provider account the same way: `BeginSSOLink`
gives a ticket for `&link=`, and `LinkSSO` takes the code with the
Expand Down Expand Up @@ -415,7 +416,15 @@ that carry what people post.
`ASWebAuthenticationSession`). The browser comes back to the app's
scheme with a code that lasts two minutes, works once, and only with
the PKCE verifier the app began with, so another app claiming the
scheme gets nothing of use.
scheme gets nothing of use from a flow the app began.
- Anyone can send a link that begins an app's flow with their own
challenge, and another app on the person's device may claim the
scheme, so the server never hands a code over by itself. Its page
names the GoChat account and what the code does (sign in, link, or
sign in again to delete) and warns against links someone sent; the
code goes to the app only when the person taps Continue. Claimed
HTTPS redirects would close this for good, but each server's domain
would have to be built into the apps.
- An app links an account at a provider from that browser too, though
the browser has no session. `BeginSSOLink`, called with the app's
session, gives a ticket naming the person and the app's PKCE
Expand Down
336 changes: 217 additions & 119 deletions api/protobuf/gen/gochat/v1/auth.pb.go

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions api/protobuf/proto/gochat/v1/auth.proto
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,23 @@ message FinishSSOResponse {
string provider_name = 6;
// The team an invite joined, for a new account.
Team team = 7;
// With an app_code: what it does and the GoChat account it is for, which
// the browser asks the person to confirm before the app gets the code.
AppCodeUse app_code_use = 9;
string app_username = 10;
// The account's email at the provider, when it gives one.
string email = 11;
}

// What an app's code does.
enum AppCodeUse {
APP_CODE_USE_UNSPECIFIED = 0;
// Signs the app in.
APP_CODE_USE_SIGN_IN = 1;
// Links the account at the provider to the app's.
APP_CODE_USE_LINK = 2;
// Proves to the app that its account's owner signed in again.
APP_CODE_USE_REAUTH = 3;
}

message RedeemSSORequest {
Expand Down
1 change: 1 addition & 0 deletions internal/server/drpc/sso.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func (s *authService) FinishSSO(ctx context.Context, req *pb.FinishSSORequest) (
out.Result = &pb.FinishSSOResponse_ReauthToken{ReauthToken: res.ReauthToken}
case res.AppCode != "":
out.Result = &pb.FinishSSOResponse_AppCode{AppCode: res.AppCode}
out.AppCodeUse, out.AppUsername, out.Email = res.AppUse, res.AppUsername, res.Email
case res.Login != nil && res.Login.MFAToken != "":
out.Result = &pb.FinishSSOResponse_MfaToken{MfaToken: res.Login.MFAToken}
case res.Login != nil:
Expand Down
3 changes: 2 additions & 1 deletion internal/services/accounts/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/gocql/gocql"
potp "github.com/pquerna/otp/totp"

pb "github.com/ssenerg/gochat/api/protobuf/gen/gochat/v1"
"github.com/ssenerg/gochat/internal/core/ids"
"github.com/ssenerg/gochat/internal/core/models"
"github.com/ssenerg/gochat/internal/core/secure"
Expand Down Expand Up @@ -311,7 +312,7 @@ func TestAppsSignInAgainToDelete(t *testing.T) {
verifier := secure.Token() + secure.Token()
appReauth := func() string {
res, err := f.sso(idp, person{}, BeginSSO{AppChallenge: s256(verifier), Reauth: true}, FinishSSO{})
if err != nil || res.AppCode == "" || res.Login != nil {
if err != nil || res.AppCode == "" || res.Login != nil || res.AppUse != pb.AppCodeUse_APP_CODE_USE_REAUTH || res.AppUsername != "ann" {
t.Fatalf("app reauth: %v %+v", err, res)
}
return res.AppCode
Expand Down
6 changes: 6 additions & 0 deletions internal/services/accounts/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ type SSOResult struct {
ReauthToken string
// Provider is the provider's name.
Provider string
// Email is the account's at the provider.
Email string
// AppUse and AppUsername say what an AppCode does and whose account it
// is for: the browser asks the person before the app gets the code.
AppUse pb.AppCodeUse
AppUsername string
// User, InviteTeamID and InviteHash are of a new account and its invite.
User *models.User
InviteTeamID gocql.UUID
Expand Down
35 changes: 24 additions & 11 deletions internal/services/accounts/sso.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ func (w *worker) finishSSO(ctx context.Context, msg FinishSSO) (*SSOResult, erro
return nil, err
}
}
out := &SSOResult{Provider: p.cfg.Name}
out := &SSOResult{Provider: p.cfg.Name, Email: id.Email}

if f.Reauth {
if !w.signedInSince(c, f) {
Expand All @@ -349,11 +349,10 @@ func (w *worker) finishSSO(ctx context.Context, msg FinishSSO) (*SSOResult, erro
if known && userID != f.LinkUser {
return nil, errLinkedElsewhere(p.cfg.Name)
}
out.AppCode, err = w.ticket(ctx, &models.SSOTicket{
return w.forApp(ctx, out, pb.AppCodeUse_APP_CODE_USE_LINK, nil, &models.SSOTicket{
Kind: models.SSOTicketAppLink, UserID: f.LinkUser, Challenge: f.AppChallenge,
Provider: p.cfg.ID, Issuer: id.Issuer, Subject: id.Subject, Email: id.Email,
}, ssoTicketTTL)
return out, err
}
if msg.P == nil || msg.P.UserID != f.LinkUser {
return nil, ierrors.New(ierrors.CodePermissionDenied, "sign in to the account you were linking, then link it again")
Expand Down Expand Up @@ -397,8 +396,7 @@ func (w *worker) finishSSO(ctx context.Context, msg FinishSSO) (*SSOResult, erro
}
w.Logger.Info("sso sign-in", zap.String("user", user.ID.String()), zap.String("provider", p.cfg.ID))
if f.AppChallenge != "" {
out.AppCode, err = w.ticket(ctx, &models.SSOTicket{Kind: models.SSOTicketApp, UserID: user.ID, Challenge: f.AppChallenge, Provider: p.cfg.ID}, ssoTicketTTL)
return out, err
return w.forApp(ctx, out, pb.AppCodeUse_APP_CODE_USE_SIGN_IN, user, &models.SSOTicket{Kind: models.SSOTicketApp, UserID: user.ID, Challenge: f.AppChallenge, Provider: p.cfg.ID}, ssoTicketTTL)
}
out.Login, err = w.signIn(ctx, user, msg.IP, msg.UserAgent)
return out, err
Expand Down Expand Up @@ -449,15 +447,30 @@ func (w *worker) reauthed(ctx context.Context, p *ssoProvider, f *models.SSOFlow
if !ids.IsZero(f.LinkUser) && (caller == nil || caller.UserID != f.LinkUser) {
return nil, ierrors.New(ierrors.CodePermissionDenied, "sign in to the account you were deleting, then try again")
}
token, err := w.ticket(ctx, &models.SSOTicket{Kind: models.SSOTicketReauth, UserID: userID, Challenge: f.AppChallenge, Provider: p.cfg.ID}, reauthTTL)
t := &models.SSOTicket{Kind: models.SSOTicketReauth, UserID: userID, Challenge: f.AppChallenge, Provider: p.cfg.ID}
if f.AppChallenge != "" {
return w.forApp(ctx, out, pb.AppCodeUse_APP_CODE_USE_REAUTH, nil, t, reauthTTL)
}
out.ReauthToken, err = w.ticket(ctx, t, reauthTTL)
return out, err
}

// forApp gives an app's code, with what it does and the account it is for
// (user, or else read): a link anyone sends can begin an app's flow, so
// the browser asks the person before the app gets it.
func (w *worker) forApp(ctx context.Context, out *SSOResult, use pb.AppCodeUse, user *models.User, t *models.SSOTicket, ttl time.Duration) (*SSOResult, error) {
if user == nil {
u, err := w.Repo.GetUser(ctx, t.UserID)
if err != nil {
return nil, err
}
user = u
}
code, err := w.ticket(ctx, t, ttl)
if err != nil {
return nil, err
}
if f.AppChallenge != "" {
out.AppCode = token
} else {
out.ReauthToken = token
}
out.AppCode, out.AppUse, out.AppUsername = code, use, user.Username
return out, nil
}

Expand Down
7 changes: 4 additions & 3 deletions internal/services/accounts/sso_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ func TestSSOLinksForAnApp(t *testing.T) {
link := func(p *models.Principal, who person) string {
t.Helper()
res, err := f.sso(idp, who, BeginSSO{AppChallenge: challenge, LinkTicket: start(p)}, FinishSSO{})
if err != nil || res.AppCode == "" || res.Linked || res.Login != nil {
if err != nil || res.AppCode == "" || res.Linked || res.Login != nil || res.AppUse != pb.AppCodeUse_APP_CODE_USE_LINK {
t.Fatalf("app link: %v %+v", err, res)
}
return res.AppCode
Expand Down Expand Up @@ -580,7 +580,8 @@ func TestSSOLinksForAnApp(t *testing.T) {
}
// The browser's own session has no say in an app's link.
res, err := f.sso(idp, person{claims: map[string]any{"sub": "carol-2"}}, BeginSSO{AppChallenge: challenge, LinkTicket: start(cp)}, FinishSSO{P: dp})
if err != nil || res.AppCode == "" || res.Linked {
// The page that asks before the app gets the code names whose it is.
if err != nil || res.AppCode == "" || res.Linked || res.AppUsername != "carol" {
t.Fatalf("a browser signed in as dave changed carol's link: %v %+v", err, res)
}
if _, err := ask[*SSOLinkInfo](f, LinkSSO{P: dp, Token: res.AppCode, Verifier: verifier}); !ierrors.Is(err, ierrors.CodePermissionDenied) {
Expand Down Expand Up @@ -719,7 +720,7 @@ func TestSSOHandsOffToApps(t *testing.T) {
verifier := secure.Token() + secure.Token()
appSignIn := func() string {
res, err := f.sso(idp, person{}, BeginSSO{AppChallenge: s256(verifier)}, FinishSSO{})
if err != nil || res.Login != nil || res.AppCode == "" {
if err != nil || res.Login != nil || res.AppCode == "" || res.AppUse != pb.AppCodeUse_APP_CODE_USE_SIGN_IN || res.AppUsername != "ann" || res.Email != "ann@example.test" {
t.Fatalf("app sign-in: %v %+v", err, res)
}
return res.AppCode
Expand Down
2 changes: 1 addition & 1 deletion internal/web/exits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ func TestAnAppSignsInAgainToDelete(t *testing.T) {
if got := auth.begun[0]; got.AppChallenge != challenge || !got.Reauth {
t.Fatalf("begin: %+v", got)
}
b.expect(b.do(http.MethodGet, ssoCallback+"?code=app&state="+state, nil), http.StatusSeeOther, appRedirect+"?code=app-code")
b.appPage(b.do(http.MethodGet, ssoCallback+"?code=app-reauth&state="+state, nil), "Tell the GoChat app that you, <strong>@ann</strong>, signed in again with Corp ID")
b.toProvider("/login/sso/corp?app=" + challenge)
if auth.begun[1].Reauth {
t.Fatal("a sign-in asked to sign in again")
Expand Down
29 changes: 23 additions & 6 deletions internal/web/sso.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package web

import (
"html/template"
"net/http"
"net/url"
"regexp"
Expand All @@ -22,7 +23,8 @@ const (
// reauthTTL is how long the server takes a sign-in again.
reauthTTL = 5 * time.Minute
// appRedirect is where an app's sign-in comes back: a scheme the apps
// claim, which then redeem the code with their PKCE verifier.
// claim, which then redeem the code with their PKCE verifier. Any app
// may claim it, so a code goes only once the person says so.
appRedirect = "io.github.ssenerg.gochat:/sso"
ssoCallback = "/login/sso/callback"
)
Expand Down Expand Up @@ -95,15 +97,30 @@ func (h *Handler) ssoFlow(r *http.Request) (ssoFlow, bool) {
return f, true
}

// toApp sends an app's browser back to it, with the code or why not.
func toApp(w http.ResponseWriter, r *http.Request, key, value string) {
http.Redirect(w, r, appRedirect+"?"+url.Values{key: {value}}.Encode(), http.StatusSeeOther)
func appURL(key, value string) string {
return appRedirect + "?" + url.Values{key: {value}}.Encode()
}

// ssoAppData asks the person before an app gets its code: a link anyone
// sends can begin an app's flow, and another app may claim the scheme.
type ssoAppData struct {
Page
Use, Provider, Username, Email string
Href template.URL
}

func (h *Handler) ssoAppPage(w http.ResponseWriter, r *http.Request, res *pb.FinishSSOResponse, code string) {
use := map[pb.AppCodeUse]string{pb.AppCodeUse_APP_CODE_USE_LINK: "link", pb.AppCodeUse_APP_CODE_USE_REAUTH: "reauth"}[res.AppCodeUse]
h.page(w, r, http.StatusOK, "sso-app", ssoAppData{
Page: Page{Title: "Continue in the app"}, Use: use, Provider: res.ProviderName, Username: res.AppUsername, Email: res.Email,
Href: template.URL(appURL("code", code)), //nolint:gosec // the apps' scheme, with an escaped query
})
}

// ssoFailed shows why a sign-in failed, on the sign-in page or in the app.
func (h *Handler) ssoFailed(w http.ResponseWriter, r *http.Request, f ssoFlow, status int, msg string) {
if f.App {
toApp(w, r, "error", msg)
http.Redirect(w, r, appURL("error", msg), http.StatusSeeOther)
return
}
h.page(w, r, status, "login", h.loginData(w, r, f.Next, msg))
Expand Down Expand Up @@ -198,7 +215,7 @@ func (h *Handler) ssoCallbackPage(w http.ResponseWriter, r *http.Request) {
}
switch out := res.Result.(type) {
case *pb.FinishSSOResponse_AppCode:
toApp(w, r, "code", out.AppCode)
h.ssoAppPage(w, r, res, out.AppCode)
case *pb.FinishSSOResponse_Session:
h.startSession(w, out.Session)
http.Redirect(w, r, h.afterSignIn(r, next), http.StatusSeeOther)
Expand Down
19 changes: 16 additions & 3 deletions internal/web/sso_flow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@ func (f *fakeAuth) FinishSSO(_ context.Context, req *pb.FinishSSORequest) (*pb.F
out.Result = &pb.FinishSSOResponse_Session{Session: f.newSession()}
case "link":
out.Result = &pb.FinishSSOResponse_LinkToken{LinkToken: strings.Repeat("L", 43)}
case "app":
case "app", "app-link", "app-reauth":
use := map[string]pb.AppCodeUse{"app": pb.AppCodeUse_APP_CODE_USE_SIGN_IN, "app-link": pb.AppCodeUse_APP_CODE_USE_LINK, "app-reauth": pb.AppCodeUse_APP_CODE_USE_REAUTH}[req.Code]
out.Result = &pb.FinishSSOResponse_AppCode{AppCode: "app-code"}
out.AppCodeUse, out.AppUsername, out.Email = use, "ann", "ann@corp.test"
default:
return nil, rpcErr(ierrors.CodePermissionDenied, "no account is linked")
}
Expand Down Expand Up @@ -161,6 +163,15 @@ func (b *browser) expect(w *httptest.ResponseRecorder, status int, location stri
}
}

// appPage checks the page that asks before an app gets its code.
func (b *browser) appPage(w *httptest.ResponseRecorder, says string) {
b.t.Helper()
body := w.Body.String()
if w.Code != http.StatusOK || w.Header().Get("Location") != "" || !strings.Contains(body, `href="`+appRedirect+`?code=app-code"`) || !strings.Contains(body, says) {
b.t.Fatalf("got %d to %q, want the page saying %q: %s", w.Code, w.Header().Get("Location"), says, body)
}
}

func newFlow(t *testing.T) (*browser, *fakeAuth) {
t.Helper()
auth := &fakeAuth{}
Expand Down Expand Up @@ -285,7 +296,9 @@ func TestSSOHandsTheCodeToTheApp(t *testing.T) {
if auth.begun[0].AppChallenge != challenge {
t.Fatalf("begin: %+v", auth.begun[0])
}
b.expect(b.do(http.MethodGet, ssoCallback+"?code=app&state="+state, nil), http.StatusSeeOther, appRedirect+"?code=app-code")
// A link anyone sends can begin an app's sign-in, so the code waits
// for the person to say it is theirs.
b.appPage(b.do(http.MethodGet, ssoCallback+"?code=app&state="+state, nil), "Sign in to the GoChat app as <strong>@ann</strong> with your Corp ID account <strong>ann@corp.test</strong>?")
state = b.toProvider("/login/sso/corp?app=" + challenge)
b.expect(b.do(http.MethodGet, ssoCallback+"?code=nobody&state="+state, nil), http.StatusSeeOther, appRedirect+"?error=no+account+is+linked")
if b.cookies["gochat_session"] != nil {
Expand All @@ -297,5 +310,5 @@ func TestSSOHandsTheCodeToTheApp(t *testing.T) {
if got := auth.begun[len(auth.begun)-1]; got.AppChallenge != challenge || got.LinkTicket != ticket || got.Reauth {
t.Fatalf("begin: %+v", got)
}
b.expect(b.do(http.MethodGet, ssoCallback+"?code=app&state="+state, nil), http.StatusSeeOther, appRedirect+"?code=app-code")
b.appPage(b.do(http.MethodGet, ssoCallback+"?code=app-link&state="+state, nil), "Sign in to <strong>@ann</strong> with your Corp ID account <strong>ann@corp.test</strong> from now on")
}
19 changes: 19 additions & 0 deletions internal/web/views/templates/pages/sso-app.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{{define "content"}}
<main class="auth">
<div class="auth-card">
<div class="brand"><img src="{{static "icon.svg"}}" alt="" width="40" height="40"><span>GoChat</span></div>
{{if eq .Use "link"}}
<h1>Link your account</h1>
<p>Sign in to <strong>@{{.Username}}</strong> with your {{.Provider}} account{{with .Email}} <strong>{{.}}</strong>{{end}} from now on, as the GoChat app asked?</p>
{{else if eq .Use "reauth"}}
<h1>Confirm it is you</h1>
<p>Tell the GoChat app that you, <strong>@{{.Username}}</strong>, signed in again with {{.Provider}}, so it can delete your account?</p>
{{else}}
<h1>Sign in to the app</h1>
<p>Sign in to the GoChat app{{with .Username}} as <strong>@{{.}}</strong>{{end}} with your {{.Provider}} account{{with .Email}} <strong>{{.}}</strong>{{end}}?</p>
{{end}}
<p class="notice">Continue only if you began this in the GoChat app on this device a moment ago. If someone sent you a link, close this page: continuing could hand them your account.</p>
<a class="btn primary block" href="{{.Href}}">Continue in the app</a>
</div>
</main>
{{end}}
5 changes: 4 additions & 1 deletion mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,12 @@ iosApp/ the Xcode project: a SwiftUI shell that shows the shared screens
- Sign in to any GoChat server, with two-factor codes, or sign up with an
invite link. Where the server has identity providers, sign in (or up)
with one in the system browser: a Custom Tab on Android, an
`ASWebAuthenticationSession` on iOS. It comes back to the app at
`ASWebAuthenticationSession` on iOS. Once the person confirms the
account on the server's page, it comes back to the app at
`io.github.ssenerg.gochat:/sso`, which Android's activity claims, and the
app trades the code for a session with the PKCE verifier it began with.
The server always asks first: anyone can send a link that begins a
flow, and another app may claim the scheme.
- Teams, channels, voice channels, direct and group conversations, with
presence, unread marks and mention counts, all live.
- Voice channels: join, talk, mute, deafen and leave, see who is talking,
Expand Down
Loading