Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

Commit

Permalink
Introduce auth provider interface (#902)
Browse files Browse the repository at this point in the history
This introduces an abstraction between firebase and our system called "AuthProvider". Right now the only auth provider is Firebase, but it could be extended in the future, with the primary use case being automated testing. There's currently no way to configure a different auth provider without writing custom code.

Part of this required using more of the Firebase server APIs. However, I found a way to plumb through the user's auth token and use that (instead of our service account), so rate limiting should be much less restrictive. In my testing, I was only able to get rate limited once and I must have tried a few hundred times over an hour. Immediately trying with a different email succeeded, demonstrating that the limiting is scoped to email (idToken) and not our service account.

The vast majority of the work involved **decoupling our controller logic from firebase** and **decoupling firebase from our smtp implementation**. There are some weird qwirks in the interface (including two places where I decided to accept an `interface{}` and force the type decision onto the implementer for flexibility), but overall I think it's pretty good.

This isn't 100% complete and will need a few tweaks to the interface{}, as we add more testing, but I think it's good to merge and iterate on in its current state.

Some other things wrapped up in the refactor:

- Extract email, email verified, and MFA factors from the session cookie. This saves a few round trip lookups to firebase for both performance and rate limiting purposes.

- Invitations for new system admins can use the system SMTP (if configured) to send invitations.
  • Loading branch information
sethvargo authored Oct 27, 2020
1 parent e3239b3 commit 1877748
Show file tree
Hide file tree
Showing 32 changed files with 1,092 additions and 698 deletions.
3 changes: 0 additions & 3 deletions cmd/server/assets/login/_loginscripts.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{{define "loginscripts"}}
<script type="text/javascript">

firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
return
Expand All @@ -9,14 +8,12 @@
});

function setSession(user) {
let factorCount = user.multiFactor.enrolledFactors.length;
user.getIdToken().then(idToken => {
$.ajax({
type: 'POST',
url: '/session',
data: {
idToken: idToken,
factorCount: factorCount,
},
headers: { 'X-CSRF-Token': '{{.csrfToken}}' },
contentType: 'application/x-www-form-urlencoded',
Expand Down
31 changes: 6 additions & 25 deletions cmd/server/assets/login/reset-password.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,44 +28,25 @@
<form class="floating-form" action="/login/reset-password" method="POST">
{{ .csrfField }}
<div class="form-label-group mb-2">
<input type="email" name="email" class="form-control" placeholder="Email address"
{{if .email}}value="{{.email}}"{{end}} required autofocus />
<input type="email" name="email" class="form-control"
placeholder="Email address" value="{{.email}}" required autofocus />
<label for="email">Email address</label>
<small class="form-text text-muted">
A reset link will be sent to this address.
</small>
</div>

<button type="submit" id="submit" class="btn btn-primary btn-block">Send reset email</button>
<a href="#"
data-submit-form
data-confirm="Are you sure you want to reset your password?"
class="btn btn-primary btn-block">Send reset email</a>
</form>
</div>
</div>
</div>
</div>
</div>
</main>

<script type="text/javascript">
$(function() {
$('#submit').on('submit', function(event) {
return window.confirm("Are you sure you want to reset your password?");
});
{{if .firebase}}
firebase.auth().sendPasswordResetEmail('{{.email}}')
.then(function() {
flash.clear();
flash.alert('Password reset email sent.');
$('#submit').prop('disabled', true);
}).catch(function(error) {
if (error.code == "auth/too-many-requests") {
$('#submit').prop('disabled', true);
}
flash.clear();
flash.error(error.message);
});
{{end}}
});
</script>
</body>

</html>
Expand Down
13 changes: 7 additions & 6 deletions cmd/server/assets/login/verify-email-check.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@
}

firebase.auth().applyActionCode(code)
.then(function(resp) {
window.location.assign("/login/manage-account?mode=verifyEmail");
}).catch(function(error) {
flash.error("Invalid email verification code. "
+ "The code may be malformed, expired, or has already been used.");
});
.then(function(resp) {
window.location.assign("/");
}).catch(function(error) {
flash.clear();
flash.error("Invalid email verification code. "
+ "The code may be malformed, expired, or has already been used.");
});
});

function getUrlVars() {
Expand Down
48 changes: 27 additions & 21 deletions cmd/server/assets/login/verify-email.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@
</div>
{{end}}

<p>Email address ownership for <em>{{.currentUser.Email}}</em> is <strong id="not">not</strong> confirmed.
</p>
<p>Email address ownership for <em>{{.currentUser.Email}}</em> is <strong id="not">not</strong> confirmed.</p>

<form method="POST">
<form method="POST" id="verify-email">
{{ .csrfField }}
<button id="verify" class="btn btn-primary btn-block" disabled>Send verification email</button>
<input type="submit" id="verify-button" class="btn btn-primary btn-block"
value="Send verification email" disabled>

<small class="form-text text-muted">
Click to send an email containing a verification link.
Expand All @@ -56,35 +56,41 @@
</div>
</main>

{{if .firebase}}
<script>
let $verify = $('#verify');
let $skip = $('#skip');
let $not = $('#not');
let $form = $("#verify-email");
let $verifyButton = $("#verify-button");
let $skip = $("#skip");
let $not = $("#not");

firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
window.location.assign("/signout");
return;
}

if ({{if eq .sendInvite "sent"}}true{{else}}user.emailVerified{{end}}) {
$not.hide();
$skip.text("Go home");
} else {
$verify.prop('disabled', false);
// If the email is already verified, move along.
if (user.emailVerified) {
flash.clear();
flash.alert("Your email address is already verified.");
window.location.assign("/home");
return;
}

{{if eq .sendInvite "send"}}
if (!user.emailVerified) {
user.sendEmailVerification().then(function() {
flash.clear();
flash.alert('Verification email sent.');
$verify.prop('disabled', true);
});
}
{{end}}
// Get an ID token and embed it onto the page.
user.getIdToken().then(idToken => {
let $idTokenField = $("<input>");
$idTokenField.attr("type", "hidden");
$idTokenField.attr("name", "idToken");
$idTokenField.attr("value", idToken);
$form.append($idTokenField);

// Now that we have a user, enable the form.
$verifyButton.prop("disabled", false);
});
});
</script>
{{end}}
</body>

</html>
Expand Down
26 changes: 1 addition & 25 deletions cmd/server/assets/users/show.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
<html lang="en">
<head>
{{template "head" .}}
{{template "firebase" .}}
</head>

<body class="tab-content">
Expand Down Expand Up @@ -43,11 +42,7 @@ <h1>{{$user.Name}}</h1>
{{$user.CanAdminRealm $currentRealm.ID}}
</div>

<form class="floating-form" action="/users/{{$user.ID}}" method="POST">
{{ .csrfField }}
<input type="hidden" name="email" value="{{$user.Email}}"/>
<button type="password-reset" id="submit" class="btn btn-primary btn-block">Send password reset</button>
</form>
<a href="/users/{{$user.ID}}/reset-password" data-method="POST" class="btn btn-primary btn-block">Send password reset</a>
</div>
</div>

Expand Down Expand Up @@ -111,25 +106,6 @@ <h1>{{$user.Name}}</h1>
}
</script>
{{end}}

{{if .firebase}}
<script type="text/javascript">
$(function() {
firebase.auth().sendPasswordResetEmail('{{$user.Email}}')
.then(function() {
flash.clear();
flash.alert('Password reset email sent.');
$('#submit').prop('disabled', true);
}).catch(function(error) {
if (error.code == "auth/too-many-requests") {
$('#submit').prop('disabled', true);
}
flash.clear();
flash.error(error.message);
});
});
</script>
{{end}}
</body>
</html>
{{end}}
9 changes: 8 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"os"
"strconv"

"github.com/google/exposure-notifications-verification-server/internal/auth"
"github.com/google/exposure-notifications-verification-server/internal/routes"
"github.com/google/exposure-notifications-verification-server/pkg/buildinfo"
"github.com/google/exposure-notifications-verification-server/pkg/cache"
Expand Down Expand Up @@ -106,7 +107,13 @@ func realMain(ctx context.Context) error {
}
defer limiterStore.Close(ctx)

mux, err := routes.Server(ctx, cfg, db, cacher, certificateSigner, limiterStore)
// Setup auth provider
authProvider, err := auth.NewFirebase(ctx, cfg.FirebaseConfig())
if err != nil {
return fmt.Errorf("failed to create firebase auth provider: %w", err)
}

mux, err := routes.Server(ctx, cfg, db, authProvider, cacher, certificateSigner, limiterStore)
if err != nil {
return fmt.Errorf("failed to setup routes: %w", err)
}
Expand Down
93 changes: 93 additions & 0 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package auth exposes interfaces for various auth methods.
package auth

import (
"context"
"fmt"
"time"

"github.com/gorilla/sessions"
)

var (
ErrSessionMissing = fmt.Errorf("session is missing")
)

// InviteUserEmailFunc sends email with the given inviteLink.
type InviteUserEmailFunc func(ctx context.Context, inviteLink string) error

// ResetPasswordEmailFunc is an email composer function.
type ResetPasswordEmailFunc func(ctx context.Context, resetLink string) error

// EmailVerificationEmailFunc is an email composer function.
type EmailVerificationEmailFunc func(ctx context.Context, verifyLink string) error

// Provider is a generic authentication provider interface.
type Provider interface {
// StoreSession stores the session in the values.
StoreSession(context.Context, *sessions.Session, *SessionInfo) error

// CheckRevoked checks if the auth has been revoked. It returns an error if
// the auth does not exist or if the auth has been revoked.
CheckRevoked(context.Context, *sessions.Session) error

// ClearSession removes any information about this auth from the session.
ClearSession(context.Context, *sessions.Session)

// CreateUser creates a user in the auth provider. If pass is "", the provider
// creates and uses a random password.
CreateUser(ctx context.Context, name, email, pass string, composer InviteUserEmailFunc) (bool, error)

// SendResetPasswordEmail resets the given user's password. If the user does not exist,
// the underlying provider determines whether itls an error or perhaps upserts
// the account.
SendResetPasswordEmail(ctx context.Context, email string, composer ResetPasswordEmailFunc) error

// ChangePassword changes the users password. The additional authentication
// information is provider-specific.
ChangePassword(ctx context.Context, newPassword string, data interface{}) error

// VerifyPasswordResetCode verifies the code is valid. It returns the email of
// the user for which the code belongs.
VerifyPasswordResetCode(ctx context.Context, code string) (string, error)

// SendEmailVerificationEmail sends the email verification email for the
// currently authenticated user. Data is arbitrary additional data that the
// provider might need (like user ID) to send the verification.
SendEmailVerificationEmail(ctx context.Context, email string, data interface{}, composer EmailVerificationEmailFunc) error

// EmailAddress extracts the email address for this auth provider from the
// session. It returns an error if the session does not exist.
EmailAddress(context.Context, *sessions.Session) (string, error)

// EmailVerified returns true if the current user is verified, false
// otherwise.
EmailVerified(context.Context, *sessions.Session) (bool, error)

// MFAEnabled returns true if MFA is enabled, false otherwise.
MFAEnabled(context.Context, *sessions.Session) (bool, error)
}

// SessionInfo is a generic struct used to store session information. Not all
// providers use all fields.
type SessionInfo struct {
// IDToken is a unique string or ID. It is usually a JWT token.
IDToken string

// TTL is the session duration.
TTL time.Duration
}
Loading

0 comments on commit 1877748

Please sign in to comment.