Skip to content

Commit

Permalink
auth: truncate token file on save
Browse files Browse the repository at this point in the history
Fixes #38.
  • Loading branch information
zephyrtronium committed Feb 29, 2024
1 parent 6c192d4 commit d0ebb35
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 4 additions & 1 deletion auth/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ func (f *FileStorage) Store(ctx context.Context, tok *oauth2.Token) error {
binary.LittleEndian.PutUint64(b, v)
r := f.enc.Seal(b, b, t, nil)
if _, err := f.f.WriteAt(r, 0); err != nil {
return fmt.Errorf("couldn't save refresh token: %w", err)
return fmt.Errorf("couldn't save token: %w", err)
}
if err := f.f.Truncate(int64(len(r))); err != nil {
return fmt.Errorf("couldn't truncate token file: %w", err)
}
return nil
}
Expand Down
21 changes: 20 additions & 1 deletion auth/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"context"
"crypto/rand"
"io"
"log/slog"
"os"
"path/filepath"
"testing"
Expand All @@ -28,6 +30,12 @@ func TestFileStorage(t *testing.T) {
if testing.Short() {
t.Skip("don't use filesystem in short testing")
}
{
// Disable slog for this test.
d := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.Level(1e9)})))
t.Cleanup(func() { slog.SetDefault(d) })
}
d, err := os.MkdirTemp("", "robot-auth-file-storage-test")
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -58,9 +66,20 @@ func TestFileStorage(t *testing.T) {
if err != nil {
t.Errorf("couldn't load bocchi: %v", err)
}
if *r != *tok {
if !Equal(r, tok) {
t.Errorf("didn't load bocchi, instead %#v", r)
}
tok.AccessToken = "kita" // shorter than before
if err := s.Store(ctx, tok); err != nil {
t.Errorf("couldn't store kita: %v", err)
}
r, err = s.Load(ctx)
if err != nil {
t.Errorf("couldn't load kita: %v", err)
}
if !Equal(r, tok) {
t.Errorf("didn't load kita, instead %#v", r)
}
if err := s.Store(ctx, nil); err != nil {
t.Errorf("couldn't clear: %v", err)
}
Expand Down

0 comments on commit d0ebb35

Please sign in to comment.