Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Add the ability for users to rotate their API keys. Closes #412

Acho Arnold2f041ac82433
diff --git a/api/pkg/handlers/user_handler.go b/api/pkg/handlers/user_handler.go
index 163c671f..4bee0877 100644
--- a/api/pkg/handlers/user_handler.go
+++ b/api/pkg/handlers/user_handler.go
@@ -41,6 +41,7 @@ func NewUserHandler(
func (h *UserHandler) RegisterRoutes(router fiber.Router) {
router.Get("/users/me", h.Show)
router.Put("/users/me", h.Update)
+ router.Delete("/users/:userID/api-keys", h.DeleteApiKey)
router.Put("/users/:userID/notifications", h.UpdateNotifications)
router.Get("/users/subscription-update-url", h.subscriptionUpdateURL)
router.Delete("/users/subscription", h.cancelSubscription)
@@ -215,3 +216,37 @@ func (h *UserHandler) cancelSubscription(c *fiber.Ctx) error {
return h.responseNoContent(c, "Subscription cancelled successfully")
}
+
+// DeleteAPIKey rotates the API Key for a user
+// @Summary Rotate the user's API Key
+// @Description Rotate the user's API key in case the current API Key is compromised
+// @Security ApiKeyAuth
+// @Tags Users
+// @Accept json
+// @Produce json
+// @Param userID path string true "ID of the user to update" default(32343a19-da5e-4b1b-a767-3298a73703ca)
+// @Success 200 {object} responses.UserResponse
+// @Failure 400 {object} responses.BadRequest
+// @Failure 401 {object} responses.Unauthorized
+// @Failure 422 {object} responses.UnprocessableEntity
+// @Failure 500 {object} responses.InternalServerError
+// @Router /users/{userID}/api-keys [delete]
+func (h *UserHandler) DeleteAPIKey(c *fiber.Ctx) error {
+ ctx, span := h.tracer.StartFromFiberCtx(c)
+ defer span.End()
+
+ ctxLogger := h.tracer.CtxLogger(h.logger, span)
+
+ if c.Params("userID") != string(h.userIDFomContext(c)) {
+ return h.responseUnauthorized(c)
+ }
+
+ user, err := h.service.RotateAPIKey(ctx, h.userIDFomContext(c))
+ if err != nil {
+ msg := fmt.Sprintf("cannot rotate the api key for [%T] with ID [%s]", user, h.userIDFomContext(c))
+ ctxLogger.Error(h.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
+ return h.responseInternalServerError(c)
+ }
+
+ return h.responseOK(c, "API Key rotated successfully", user)
+}
diff --git a/api/pkg/repositories/gorm_user_repository.go b/api/pkg/repositories/gorm_user_repository.go
index 0c79405f..f853e323 100644
--- a/api/pkg/repositories/gorm_user_repository.go
+++ b/api/pkg/repositories/gorm_user_repository.go
@@ -8,6 +8,8 @@ import (
"fmt"
"time"
+ "gorm.io/gorm/clause"
+
"github.com/cockroachdb/cockroach-go/v2/crdb/crdbgorm"
"github.com/dgraph-io/ristretto"
@@ -40,6 +42,32 @@ func NewGormUserRepository(
}
}
+func (repository *gormUserRepository) RotateAPIKey(ctx context.Context, userID entities.UserID) (*entities.User, error) {
+ ctx, span := repository.tracer.Start(ctx)
+ defer span.End()
+
+ apiKey, err := repository.generateAPIKey(64)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, fmt.Sprintf("cannot generate apiKey for user [%s]", userID))
+ }
+
+ user := new(entities.User)
+ err = crdbgorm.ExecuteTx(ctx, repository.db, nil,
+ func(tx *gorm.DB) error {
+ return tx.WithContext(ctx).Model(user).
+ Clauses(clause.Returning{}).
+ Where("id = ?", userID).
+ Update("api_key", apiKey).Error
+ },
+ )
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ msg := fmt.Sprintf("user with ID [%s] does not exist", userID)
+ return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, ErrCodeNotFound, msg))
+ }
+
+ return user, nil
+}
+
func (repository *gormUserRepository) LoadBySubscriptionID(ctx context.Context, subscriptionID string) (*entities.User, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
@@ -150,7 +178,7 @@ func (repository *gormUserRepository) LoadOrStore(ctx context.Context, authUser
apiKey, err := repository.generateAPIKey(64)
if err != nil {
- return nil, false, stacktrace.Propagate(err, "cannot generate apiKey")
+ return nil, false, stacktrace.Propagate(err, fmt.Sprintf("cannot generate apiKey for user [%s]", authUser.ID))
}
user = &entities.User{
diff --git a/api/pkg/repositories/user_repository.go b/api/pkg/repositories/user_repository.go
index 9bdb81ad..2785bba1 100644
--- a/api/pkg/repositories/user_repository.go
+++ b/api/pkg/repositories/user_repository.go
@@ -20,6 +20,9 @@ type UserRepository interface {
// Load an entities.User by entities.UserID
Load(ctx context.Context, userID entities.UserID) (*entities.User, error)
+ // RotateAPIKey updates the API Key of a user
+ RotateAPIKey(ctx context.Context, userID entities.UserID) (*entities.User, error)
+
// LoadOrStore an entities.User by entities.AuthUser
LoadOrStore(ctx context.Context, user entities.AuthUser) (*entities.User, bool, error)
diff --git a/api/pkg/services/user_service.go b/api/pkg/services/user_service.go
index 6154c5b3..5515c9cd 100644
--- a/api/pkg/services/user_service.go
+++ b/api/pkg/services/user_service.go
@@ -149,6 +149,21 @@ func (service *UserService) UpdateNotificationSettings(ctx context.Context, user
return user, nil
}
+// RotateAPIKey for an entities.User
+func (service *UserService) RotateAPIKey(ctx context.Context, userID entities.UserID) (*entities.User, error) {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ user, err := service.repository.RotateAPIKey(ctx, userID)
+ if err != nil {
+ msg := fmt.Sprintf("could not rotate API key for [%T] with ID [%s]", user, userID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("rotated the api key for [%T] with ID [%s] in the [%T]", user, user.ID, service.repository))
+ return user, nil
+}
+
// UserSendPhoneDeadEmailParams are parameters for notifying a user when a phone is dead
type UserSendPhoneDeadEmailParams struct {
UserID entities.UserID
diff --git a/web/components/CopyButton.vue b/web/components/CopyButton.vue
index aa94a7e6..20a94a5f 100644
--- a/web/components/CopyButton.vue
+++ b/web/components/CopyButton.vue
@@ -7,7 +7,7 @@
:large="large"
@click="copy"
>
- <v-icon>{{ mdiContentCopy }}</v-icon>
+ <v-icon left>{{ mdiContentCopy }}</v-icon>
{{ copyText }}
</v-btn>
</template>
diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vue
index fbab6794..f98be8f3 100644
--- a/web/pages/settings/index.vue
+++ b/web/pages/settings/index.vue
@@ -75,10 +75,8 @@
class="mb-n2"
@click:append="apiKeyShow = !apiKeyShow"
></v-text-field>
- <div class="d-flex">
+ <div class="d-flex flex-wrap">
<copy-button
- :block="$vuetify.breakpoint.mdAndDown"
- :large="$vuetify.breakpoint.mdAndDown"
:value="apiKey"
color="primary"
copy-text="Copy API Key"
@@ -90,6 +88,49 @@
:href="$store.getters.getAppData.documentationUrl"
>Documentation</v-btn
>
+ <v-spacer></v-spacer>
+ <v-dialog
+ v-model="showRotateApiKey"
+ overlay-opacity="0.9"
+ max-width="550"
+ >
+ <template #activator="{ on, attrs }">
+ <v-btn
+ :small="$vuetify.breakpoint.mdAndDown"
+ :text="$vuetify.breakpoint.lgAndUp"
+ color="warning"
+ v-bind="attrs"
+ v-on="on"
+ >
+ <v-icon left>{{ mdiRefresh }}</v-icon>
+ Rotate API Key
+ </v-btn>
+ </template>
+ <v-card>
+ <v-card-title class="text-h5 text-break">
+ Are you sure you want to rotate your API Key?
+ </v-card-title>
+ <v-card-text>
+ You will have to logout and login again on the
+ <b>httpSMS</b> Android app with your new API key after you
+ rotate it.
+ </v-card-text>
+ <v-card-actions class="pb-4">
+ <v-btn
+ color="primary"
+ :loading="rotatingApiKey"
+ @click="rotateApiKey"
+ >
+ <v-icon left>{{ mdiRefresh }}</v-icon>
+ Yes Rotate Key
+ </v-btn>
+ <v-spacer></v-spacer>
+ <v-btn text @click="showRotateApiKey = false">
+ Close
+ </v-btn>
+ </v-card-actions>
+ </v-card>
+ </v-dialog>
</div>
<h5 id="webhook-settings" class="text-h4 mb-3 mt-12">Webhooks</h5>
<p class="text--secondary">
@@ -345,7 +386,7 @@
</v-row>
</v-container>
</div>
- <v-dialog v-model="showPhoneEdit" max-width="700px">
+ <v-dialog v-model="showPhoneEdit" overlay-opacity="0.9" max-width="700px">
<v-card>
<v-card-title>Edit Phone</v-card-title>
<v-card-text v-if="activePhone" class="mt-6">
@@ -441,7 +482,7 @@
</v-card-actions>
</v-card>
</v-dialog>
- <v-dialog v-model="showWebhookEdit" max-width="600px">
+ <v-dialog v-model="showWebhookEdit" overlay-opacity="0.9" max-width="600px">
<v-card>
<v-card-title>
<span v-if="!activeWebhook.id">Add a new&nbsp;</span>
@@ -556,7 +597,7 @@
</v-card-actions>
</v-card>
</v-dialog>
- <v-dialog v-model="showDiscordEdit" max-width="700px">
+ <v-dialog v-model="showDiscordEdit" overlay-opacity="0.9" max-width="700px">
<v-card>
<v-card-title>
<span v-if="!activeDiscord.id">Add a new&nbsp;</span>
@@ -682,6 +723,7 @@ import {
mdiContentSave,
mdiConnection,
mdiEye,
+ mdiRefresh,
mdiLinkVariant,
mdiEyeOff,
mdiSquareEditOutline,
@@ -697,6 +739,7 @@ export default Vue.extend({
return {
mdiEye,
mdiEyeOff,
+ mdiRefresh,
mdiArrowLeft,
mdiAccountCircle,
mdiShieldCheck,
@@ -709,6 +752,8 @@ export default Vue.extend({
apiKeyShow: false,
showPhoneEdit: false,
showDiscordEdit: false,
+ showRotateApiKey: false,
+ rotatingApiKey: false,
activeWebhook: {
id: null,
url: '',
@@ -1022,6 +1067,16 @@ export default Vue.extend({
})
},
+ rotateApiKey() {
+ this.rotatingApiKey = true
+ this.$store
+ .dispatch('rotateApiKey', this.$store.getters.getUser.id)
+ .finally(() => {
+ this.rotatingApiKey = false
+ this.showRotateApiKey = false
+ })
+ },
+
deleteWebhook(webhookId) {
this.updatingWebhook = true
this.$store
diff --git a/web/store/index.ts b/web/store/index.ts
index b8a52247..d89ebf4f 100644
--- a/web/store/index.ts
+++ b/web/store/index.ts
@@ -886,6 +886,33 @@ export const actions = {
})
},
+ rotateApiKey(context: ActionContext<State, State>, payload: string) {
+ return new Promise<EntitiesUser>((resolve, reject) => {
+ axios
+ .delete<ResponsesUserResponse>(`/v1/users/${payload}/api-keys`)
+ .then((response: AxiosResponse<ResponsesUserResponse>) => {
+ context.commit('setUser', response.data.data)
+ setApiKey(response.data.data.api_key)
+ context.dispatch('addNotification', {
+ message: 'API Key rotated successfully',
+ type: 'success',
+ })
+ resolve(response.data.data)
+ })
+ .catch(async (error: AxiosError) => {
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ (error.response?.data as any)?.message ??
+ 'Error while rotating your API key',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
updateWebhook(
context: ActionContext<State, State>,
payload: RequestsWebhookUpdate & { id: string },